Unnamed: 0
int64
0
60k
address
stringlengths
42
42
source_code
stringlengths
52
864k
bytecode
stringlengths
2
49.2k
slither
stringlengths
47
956
success
bool
1 class
error
float64
results
stringlengths
2
911
0
0x006699d34AA3013605d468d2755A2Fe59A16B12B
pragma solidity 0.5.4; interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } function isOwner() public view returns (bool) { return msg.sender == _owner; } modifier onlyOwner() { require(msg.sender == _owner, "Ownable: caller is not the 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 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 ZildFinanceCoin is Ownable, IERC20 { using SafeMath for uint256; string public constant name = 'Zild Finance Coin'; string public constant symbol = 'Zild'; uint8 public constant decimals = 18; uint256 public totalSupply = 9980 * 10000 * 10 ** uint256(decimals); uint256 public allowBurn = 2100 * 10000 * 10 ** uint256(decimals); uint256 public tokenDestroyed; uint256 public constant FounderAllocation = 1497 * 10000 * 10 ** uint256(decimals); uint256 public constant FounderLockupAmount = 998 * 10000 * 10 ** uint256(decimals); uint256 public constant FounderLockupCliff = 365 days; uint256 public constant FounderReleaseInterval = 30 days; uint256 public constant FounderReleaseAmount = 20.7916 * 10000 * 10 ** uint256(decimals); uint256 public constant MarketingAllocation = 349 * 10000 * 10 ** uint256(decimals); uint256 public constant FurnaceAllocation = 150 * 10000 * 10 ** uint256(decimals); address public founder = address(0); uint256 public founderLockupStartTime = 0; uint256 public founderReleasedAmount = 0; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) public frozenAccount; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed to, uint256 value); event ChangeFounder(address indexed previousFounder, address indexed newFounder); event SetMinter(address indexed minter); event SetMarketing(address indexed marketing); event SetFurnace(address indexed furnace); event Burn(address indexed _from, uint256 _tokenDestroyed, uint256 _timestamp); event FrozenFunds(address target, bool frozen); constructor(address _founder, address _marketing) public { require(_founder != address(0), "ZildFinanceCoin: founder is the zero address"); require(_marketing != address(0), "ZildFinanceCoin: operator is the zero address"); founder = _founder; founderLockupStartTime = block.timestamp; _balances[address(this)] = totalSupply; _transfer(address(this), _marketing, MarketingAllocation); } function release() public { uint256 currentTime = block.timestamp; uint256 cliffTime = founderLockupStartTime.add(FounderLockupCliff); if (currentTime < cliffTime) return; if (founderReleasedAmount >= FounderLockupAmount) return; uint256 month = currentTime.sub(cliffTime).div(FounderReleaseInterval); uint256 releaseAmount = month.mul(FounderReleaseAmount); if (releaseAmount > FounderLockupAmount) releaseAmount = FounderLockupAmount; if (releaseAmount <= founderReleasedAmount) return; uint256 amount = releaseAmount.sub(founderReleasedAmount); founderReleasedAmount = releaseAmount; _transfer(address(this), founder, amount); } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address to, uint256 amount) public returns (bool) { require(to != address(0), "ERC20: tranfer to the zero address"); require(!frozenAccount[msg.sender]); require(!frozenAccount[to]); _transfer(msg.sender, to, amount); return true; } function burn(uint256 _value) public returns (bool){ _burn(msg.sender, _value); return true; } function _burn(address _who, uint256 _burntAmount) internal { require (tokenDestroyed.add(_burntAmount) <= allowBurn, "ZildFinanceCoin: exceeded the maximum allowable burning amount" ); require(_balances[msg.sender] >= _burntAmount && _burntAmount > 0); _transfer(address(_who), address(0), _burntAmount); totalSupply = totalSupply.sub(_burntAmount); tokenDestroyed = tokenDestroyed.add(_burntAmount); emit Burn(_who, _burntAmount, block.timestamp); } function allowance(address from, address to) public view returns (uint256) { return _allowances[from][to]; } function approve(address to, uint256 amount) public returns (bool) { _approve(msg.sender, to, amount); return true; } function transferFrom(address from, address to, uint256 amount) public returns (bool) { uint256 remaining = _allowances[from][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"); require(to != address(0), "ERC20: tranfer to the zero address"); require(!frozenAccount[from]); require(!frozenAccount[to]); require(!frozenAccount[msg.sender]); _transfer(from, to, amount); _approve(from, msg.sender, remaining); return true; } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); _balances[from] = _balances[from].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Transfer(from, to, amount); } function _approve(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: approve from the zero address"); require(to != address(0), "ERC20: approve to the zero address"); _allowances[from][to] = amount; emit Approval(from, to, amount); } function changeFounder(address _founder) public onlyOwner { require(_founder != address(0), "ZildFinanceCoin: founder is the zero address"); emit ChangeFounder(founder, _founder); founder = _founder; } function setMinter(address minter) public onlyOwner { require(minter != address(0), "ZildFinanceCoin: minter is the zero address"); require(_balances[minter] == 0, "ZildFinanceCoin: minter has been initialized"); _transfer(address(this), minter, totalSupply.sub(FounderAllocation)); emit SetMinter(minter); } function setFurnace(address furnace) public onlyOwner { require(furnace != address(0), "ZildFinanceCoin: furnace is the zero address"); require(_balances[furnace] == 0, "ZildFinanceCoin: furnace has been initialized"); _transfer(address(this), furnace, FurnaceAllocation); emit SetFurnace(furnace); } function freezeAccount(address _target, bool _bool) public onlyOwner { if (_target != address(0)) { frozenAccount[_target] = _bool; emit FrozenFunds(_target,_bool); } } }
0x608060405234801561001057600080fd5b5060043610610202576000357c01000000000000000000000000000000000000000000000000000000009004806386d1a69f1161012c578063b414d4b6116100bf578063f2fde38b1161008e578063f2fde38b146104fd578063fca3b5aa14610523578063fedacfa414610549578063ff1970381461055157610202565b8063b414d4b614610473578063d9aa188114610499578063dd62ed3e146104a1578063e724529c146104cf57610202565b806393c32e06116100fb57806393c32e061461041157806395d89b4114610437578063a42d91d81461043f578063a9059cbb1461044757610202565b806386d1a69f146103d157806387829c65146103db5780638da5cb5b146104015780638f32d59b1461040957610202565b8063313ce567116101a45780634e680654116101735780634e6806541461039357806353b841721461039b5780635f6e84ee146103a357806370a08231146103ab57610202565b8063313ce5671461032c57806335e061fc1461034a57806342966c68146103525780634d853ee51461036f57610202565b806318160ddd116101e057806318160ddd146102de57806323b872dd146102e657806326e5be361461031c57806330cf480b1461032457610202565b806306fdde031461020757806307e4498c14610284578063095ea7b31461029e575b600080fd5b61020f610559565b6040805160208082528351818301528351919283929083019185019080838360005b83811015610249578181015183820152602001610231565b50505050905090810190601f1680156102765780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61028c610590565b60408051918252519081900360200190f35b6102ca600480360360408110156102b457600080fd5b50600160a060020a038135169060200135610596565b604080519115158252519081900360200190f35b61028c6105ad565b6102ca600480360360608110156102fc57600080fd5b50600160a060020a038135811691602081013590911690604001356105b3565b61028c6106db565b61028c6106ea565b6103346106f9565b6040805160ff9092168252519081900360200190f35b61028c6106fe565b6102ca6004803603602081101561036857600080fd5b5035610704565b610377610718565b60408051600160a060020a039092168252519081900360200190f35b61028c610727565b61028c610736565b61028c610745565b61028c600480360360208110156103c157600080fd5b5035600160a060020a0316610753565b6103d961076e565b005b6103d9600480360360208110156103f157600080fd5b5035600160a060020a031661086d565b6103776109ac565b6102ca6109bb565b6103d96004803603602081101561042757600080fd5b5035600160a060020a03166109cc565b61020f610acf565b61028c610b06565b6102ca6004803603604081101561045d57600080fd5b50600160a060020a038135169060200135610b0c565b6102ca6004803603602081101561048957600080fd5b5035600160a060020a0316610ba6565b61028c610bbb565b61028c600480360360408110156104b757600080fd5b50600160a060020a0381358116916020013516610bc1565b6103d9600480360360408110156104e557600080fd5b50600160a060020a0381351690602001351515610bec565b6103d96004803603602081101561051357600080fd5b5035600160a060020a0316610cb0565b6103d96004803603602081101561053957600080fd5b5035600160a060020a0316610db2565b61028c610f06565b61028c610f0e565b60408051808201909152601181527f5a696c642046696e616e636520436f696e000000000000000000000000000000602082015281565b60055481565b60006105a3338484610f15565b5060015b92915050565b60015481565b60008061060583606060405190810160405280602881526020016115ec60289139600160a060020a0388166000908152600860209081526040808320338452909152902054919063ffffffff61100b16565b9050600160a060020a03841615156106515760405160e560020a62461bcd02815260040180806020018281038252602281526020018061153f6022913960400191505060405180910390fd5b600160a060020a03851660009081526009602052604090205460ff161561067757600080fd5b600160a060020a03841660009081526009602052604090205460ff161561069d57600080fd5b3360009081526009602052604090205460ff16156106ba57600080fd5b6106c58585856110a5565b6106d0853383610f15565b506001949350505050565b6a0c6205537ba4bc5840000081565b6a084158e2526dd2e580000081565b601281565b60025481565b600061071033836111c4565b506001919050565b600454600160a060020a031681565b6a013da329b633647180000081565b6a02e309477303850140000081565b692c0726213dd1f530000081565b600160a060020a031660009081526007602052604090205490565b600554429060009061078a906301e1338063ffffffff6112c216565b90508082101561079b57505061086b565b6006546a084158e2526dd2e5800000116107b657505061086b565b60006107db62278d006107cf858563ffffffff61132616565b9063ffffffff61136816565b905060006107f982692c0726213dd1f530000063ffffffff6113aa16565b90506a084158e2526dd2e580000081111561081c57506a084158e2526dd2e58000005b600654811161082e575050505061086b565b60006108456006548361132690919063ffffffff16565b6006839055600454909150610865903090600160a060020a0316836110a5565b50505050505b565b600054600160a060020a031633146108bd576040805160e560020a62461bcd0281526020600482018190526024820152600080516020611614833981519152604482015290519081900360640190fd5b600160a060020a03811615156109075760405160e560020a62461bcd02815260040180806020018281038252602c8152602001806116a8602c913960400191505060405180910390fd5b600160a060020a0381166000908152600760205260409020541561095f5760405160e560020a62461bcd02815260040180806020018281038252602d8152602001806114ec602d913960400191505060405180910390fd5b61097530826a013da329b63364718000006110a5565b604051600160a060020a038216907f563cb3456af3dceec7b66059f2c03af0b838a856cdd6bccf313f3260ccab3c8d90600090a250565b600054600160a060020a031690565b600054600160a060020a0316331490565b600054600160a060020a03163314610a1c576040805160e560020a62461bcd0281526020600482018190526024820152600080516020611614833981519152604482015290519081900360640190fd5b600160a060020a0381161515610a665760405160e560020a62461bcd02815260040180806020018281038252602c815260200180611561602c913960400191505060405180910390fd5b600454604051600160a060020a038084169216907f0d6a44001f99eb1e3e879ad45c4f03a44f9fec7dedebb037550b0c8180372ae190600090a36004805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0392909216919091179055565b60408051808201909152600481527f5a696c6400000000000000000000000000000000000000000000000000000000602082015281565b60065481565b6000600160a060020a0383161515610b585760405160e560020a62461bcd02815260040180806020018281038252602281526020018061153f6022913960400191505060405180910390fd5b3360009081526009602052604090205460ff1615610b7557600080fd5b600160a060020a03831660009081526009602052604090205460ff1615610b9b57600080fd5b6105a33384846110a5565b60096020526000908152604090205460ff1681565b60035481565b600160a060020a03918216600090815260086020908152604080832093909416825291909152205490565b600054600160a060020a03163314610c3c576040805160e560020a62461bcd0281526020600482018190526024820152600080516020611614833981519152604482015290519081900360640190fd5b600160a060020a03821615610cac57600160a060020a038216600081815260096020908152604091829020805460ff191685151590811790915582519384529083015280517f48335238b4855f35377ed80f164e8c6f3c366e54ac00b96a6402d4a9814a03a59281900390910190a15b5050565b600054600160a060020a03163314610d00576040805160e560020a62461bcd0281526020600482018190526024820152600080516020611614833981519152604482015290519081900360640190fd5b600160a060020a0381161515610d4a5760405160e560020a62461bcd0281526004018080602001828103825260268152602001806114786026913960400191505060405180910390fd5b60008054604051600160a060020a03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a36000805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0392909216919091179055565b600054600160a060020a03163314610e02576040805160e560020a62461bcd0281526020600482018190526024820152600080516020611614833981519152604482015290519081900360640190fd5b600160a060020a0381161515610e4c5760405160e560020a62461bcd02815260040180806020018281038252602b815260200180611634602b913960400191505060405180910390fd5b600160a060020a03811660009081526007602052604090205415610ea45760405160e560020a62461bcd02815260040180806020018281038252602c8152602001806114c0602c913960400191505060405180910390fd5b600154610ecf9030908390610eca906a0c6205537ba4bc5840000063ffffffff61132616565b6110a5565b604051600160a060020a038216907fcec52196e972044edde8689a1b608e459c5946b7f3e5c8cd3d6d8e126d422e1c90600090a250565b6301e1338081565b62278d0081565b600160a060020a0383161515610f5f5760405160e560020a62461bcd0281526004018080602001828103825260248152602001806116846024913960400191505060405180910390fd5b600160a060020a0382161515610fa95760405160e560020a62461bcd02815260040180806020018281038252602281526020018061149e6022913960400191505060405180910390fd5b600160a060020a03808416600081815260086020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6000818484111561109d5760405160e560020a62461bcd0281526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561106257818101518382015260200161104a565b50505050905090810190601f16801561108f5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b600160a060020a03831615156110ef5760405160e560020a62461bcd02815260040180806020018281038252602581526020018061165f6025913960400191505060405180910390fd5b611133816060604051908101604052806026815260200161151960269139600160a060020a038616600090815260076020526040902054919063ffffffff61100b16565b600160a060020a038085166000908152600760205260408082209390935590841681522054611168908263ffffffff6112c216565b600160a060020a0380841660008181526007602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b6002546003546111da908363ffffffff6112c216565b111561121a5760405160e560020a62461bcd02815260040180806020018281038252603e81526020018061158d603e913960400191505060405180910390fd5b3360009081526007602052604090205481118015906112395750600081115b151561124457600080fd5b611250826000836110a5565b600154611263908263ffffffff61132616565b600155600354611279908263ffffffff6112c216565b600355604080518281524260208201528151600160a060020a038516927f49995e5dd6158cf69ad3e9777c46755a1a826a446c6416992167462dad033b2a928290030190a25050565b60008282018381101561131f576040805160e560020a62461bcd02815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b600061131f83836040805190810160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f77000081525061100b565b600061131f83836040805190810160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061140a565b60008215156113bb575060006105a7565b8282028284828115156113ca57fe5b041461131f5760405160e560020a62461bcd0281526004018080602001828103825260218152602001806115cb6021913960400191505060405180910390fd5b60008181841161145f5760405160e560020a62461bcd0281526004018080602001828103825283818151815260200191508051906020019080838360008381101561106257818101518382015260200161104a565b506000838581151561146d57fe5b049594505050505056fe4f776e61626c653a206e6577206f776e657220697320746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f20616464726573735a696c6446696e616e6365436f696e3a206d696e74657220686173206265656e20696e697469616c697a65645a696c6446696e616e6365436f696e3a206675726e61636520686173206265656e20696e697469616c697a656445524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e66657220746f20746865207a65726f20616464726573735a696c6446696e616e6365436f696e3a20666f756e64657220697320746865207a65726f20616464726573735a696c6446696e616e6365436f696e3a20657863656564656420746865206d6178696d756d20616c6c6f7761626c65206275726e696e6720616d6f756e74536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f7745524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e63654f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65725a696c6446696e616e6365436f696e3a206d696e74657220697320746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f20616464726573735a696c6446696e616e6365436f696e3a206675726e61636520697320746865207a65726f2061646472657373a165627a7a72305820e6fd4002a5984c22bde21a7c9b84330841d0b32b169895279b8dfd458969c2110029
{"success": true, "error": null, "results": {"detectors": [{"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}]}
1
0x00c83aeCC790e8a4453e5dD3B0B4b3680501a7A7
pragma solidity 0.6.10; pragma experimental ABIEncoderV2; 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 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 IDelegatableToken { /** * @dev Updates and returns the amount of locked tokens of a given account (`wallet`). */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Updates and returns the amount of delegated tokens of a given account (`wallet`). */ function getAndUpdateDelegatedAmount(address wallet) external returns (uint); /** * @dev Updates and returns the amount of slashed tokens of a given account (`wallet`). */ function getAndUpdateSlashedAmount(address wallet) external returns (uint); } 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); } 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; } } } 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 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)); } } 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 IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } 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 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 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)); } } 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 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 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 addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } 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 ERC777 is Context, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory name, string memory symbol, address[] memory defaultOperators ) public { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes memory data) public override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); /* Chaged by SKALE: we swapped these lines to prevent delegation of burning tokens */ _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); /* End of changed by SKALE */ // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve(address holder, address spender, uint256 value) internal { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, 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 operator, address from, address to, uint256 tokenId) internal virtual { } } 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 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")); } } 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 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 SkaleToken is ERC777, Permissions, ReentrancyGuard, IDelegatableToken { using SafeMath for uint; string public constant NAME = "SKALE"; string public constant SYMBOL = "SKL"; uint public constant DECIMALS = 18; uint public constant CAP = 7 * 1e9 * (10 ** DECIMALS); // the maximum amount of tokens that can ever be created constructor(address contractsAddress, address[] memory defOps) public ERC777("SKALE", "SKL", defOps) { Permissions.initialize(contractsAddress); } /** * @dev mint - create some amount of token and transfer it to the specified address * @param account - address where some amount of token would be created * @param amount - amount of tokens to mine * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @return returns success of function call. */ function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external allow("SkaleManager") //onlyAuthorized returns (bool) { require(amount <= CAP.sub(totalSupply()), "Amount is too big"); _mint( account, amount, userData, operatorData ); return true; } function getAndUpdateDelegatedAmount(address wallet) external override returns (uint) { return DelegationController(contractManager.getContract("DelegationController")) .getAndUpdateDelegatedAmount(wallet); } function getAndUpdateSlashedAmount(address wallet) external override returns (uint) { return Punisher(contractManager.getContract("Punisher")).getAndUpdateLockedAmount(wallet); } function getAndUpdateLockedAmount(address wallet) public override returns (uint) { return TokenState(contractManager.getContract("TokenState")).getAndUpdateLockedAmount(wallet); } // internal function _beforeTokenTransfer( address, // operator address from, address, // to uint256 tokenId) internal override { uint locked = getAndUpdateLockedAmount(from); if (locked > 0) { require(balanceOf(from) >= locked.add(tokenId), "Token should be unlocked for transferring"); } } function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal override nonReentrant { super._callTokensToSend(operator, from, to, amount, userData, operatorData); } function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal override nonReentrant { super._callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } // we have to override _msgData() and _msgSender() functions because of collision in Context and ContextUpgradeSafe function _msgData() internal view override(Context, ContextUpgradeSafe) returns (bytes memory) { return Context._msgData(); } function _msgSender() internal view override(Context, ContextUpgradeSafe) returns (address payable) { return Context._msgSender(); } } 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 = 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; /** * 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; } /** * @dev constructor in Permissions approach * @param contractsAddress needed in Permissions constructor */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 86400; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; } } 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; } /** * @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; /** * @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")); SkaleToken skaleToken = SkaleToken(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"); 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"); 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")); 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 _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 _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)); } } 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} 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 ); /** * @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 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 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 allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } function changeNodeFinishTime(uint nodeIndex, uint time) external 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 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 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 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 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 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 getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace)); uint cursor = 0; for (uint8 i = freeSpace; i <= constantsHolder.TOTAL_SPACE_ON_NODE(); ++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 returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return uint(nodes[nodeIndex].lastRewardDate).add(constantsHolder.rewardPeriod()) <= block.timestamp; } /** * @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) external view returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev getNodeIP - get ip address of Node * @param nodeIndex - index of Node * @return ip address */ function getNodeIP(uint nodeIndex) external view 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 returns (uint16) { return nodes[nodeIndex].port; } function getNodePublicKey(uint nodeIndex) external view returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } function getNodeFinishTime(uint nodeIndex) external view 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 returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } /** * @dev getNodeLastRewardDate - get Node last reward date * @param nodeIndex - index of Node * @return Node last reward date */ function getNodeLastRewardDate(uint nodeIndex) external view 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 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 getValidatorId(uint nodeIndex) external view returns (uint) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].validatorId; } function getNodeStatus(uint nodeIndex) external view 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; } /** * @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 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 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; for (uint8 i = freeSpace; i <= constantsHolder.TOTAL_SPACE_ON_NODE(); ++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; } }
0x608060405234801561001057600080fd5b506004361061021c5760003560e01c80639bd9bbc611610125578063d95b6371116100ad578063f76f8d781161007c578063f76f8d7814610922578063fa8dacba1461092a578063fad8b32a14610950578063fc673c4f14610976578063fe9d930314610ab45761021c565b8063d95b6371146107eb578063dcdc7dd014610819578063dd62ed3e146108ec578063ec81b4831461091a5761021c565b8063b1cb105f116100f4578063b1cb105f1461074e578063b39e12cf14610774578063c4d66de81461077c578063ca15c873146107a2578063d547741f146107bf5761021c565b80639bd9bbc614610659578063a217fddf14610712578063a3f4df7e1461071a578063a9059cbb146107225761021c565b8063313ce567116101a857806370a082311161017757806370a082311461059a5780639010d07c146105c057806391d14854146105ff578063959b8c3f1461062b57806395d89b41146106515761021c565b8063313ce567146103ff57806336568abe1461041d578063556f0dc71461044957806362ad1b83146104515761021c565b806323b872dd116101ef57806323b872dd14610350578063248a9ca31461038657806327040f68146103a35780632e0f2625146103c95780632f2ff15d146103d15761021c565b806306e485381461022157806306fdde0314610279578063095ea7b3146102f657806318160ddd14610336575b600080fd5b610229610b5f565b60408051602080825283518183015283519192839290830191858101910280838360005b8381101561026557818101518382015260200161024d565b505050509050019250505060405180910390f35b610281610bc1565b6040805160208082528351818301528351919283929083019185019080838360005b838110156102bb5781810151838201526020016102a3565b50505050905090810190601f1680156102e85780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6103226004803603604081101561030c57600080fd5b506001600160a01b038135169060200135610c4b565b604080519115158252519081900360200190f35b61033e610c6f565b60408051918252519081900360200190f35b6103226004803603606081101561036657600080fd5b506001600160a01b03813581169160208101359091169060400135610c75565b61033e6004803603602081101561039c57600080fd5b5035610df8565b61033e600480360360208110156103b957600080fd5b50356001600160a01b0316610e0d565b61033e610f25565b6103fd600480360360408110156103e757600080fd5b50803590602001356001600160a01b0316610f2a565b005b610407610f96565b6040805160ff9092168252519081900360200190f35b6103fd6004803603604081101561043357600080fd5b50803590602001356001600160a01b0316610f9b565b61033e610ffc565b6103fd600480360360a081101561046757600080fd5b6001600160a01b03823581169260208101359091169160408201359190810190608081016060820135600160201b8111156104a157600080fd5b8201836020820111156104b357600080fd5b803590602001918460018302840111600160201b831117156104d457600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295949360208101935035915050600160201b81111561052657600080fd5b82018360208201111561053857600080fd5b803590602001918460018302840111600160201b8311171561055957600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550611001945050505050565b61033e600480360360208110156105b057600080fd5b50356001600160a01b0316611063565b6105e3600480360360408110156105d657600080fd5b508035906020013561107e565b604080516001600160a01b039092168252519081900360200190f35b6103226004803603604081101561061557600080fd5b50803590602001356001600160a01b03166110a3565b6103fd6004803603602081101561064157600080fd5b50356001600160a01b03166110c1565b61028161120d565b6103fd6004803603606081101561066f57600080fd5b6001600160a01b0382351691602081013591810190606081016040820135600160201b81111561069e57600080fd5b8201836020820111156106b057600080fd5b803590602001918460018302840111600160201b831117156106d157600080fd5b91908080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525092955061126e945050505050565b61033e611298565b61028161129d565b6103226004803603604081101561073857600080fd5b506001600160a01b0381351690602001356112be565b61033e6004803603602081101561076457600080fd5b50356001600160a01b0316611397565b6105e3611471565b6103fd6004803603602081101561079257600080fd5b50356001600160a01b0316611480565b61033e600480360360208110156107b857600080fd5b503561153e565b6103fd600480360360408110156107d557600080fd5b50803590602001356001600160a01b0316611555565b6103226004803603604081101561080157600080fd5b506001600160a01b03813581169160200135166115ae565b6103226004803603608081101561082f57600080fd5b6001600160a01b0382351691602081013591810190606081016040820135600160201b81111561085e57600080fd5b82018360208201111561087057600080fd5b803590602001918460018302840111600160201b8311171561089157600080fd5b919390929091602081019035600160201b8111156108ae57600080fd5b8201836020820111156108c057600080fd5b803590602001918460018302840111600160201b831117156108e157600080fd5b50909250905061164f565b61033e6004803603604081101561090257600080fd5b506001600160a01b03813581169160200135166118ae565b61033e6118d9565b6102816118e9565b61033e6004803603602081101561094057600080fd5b50356001600160a01b0316611908565b6103fd6004803603602081101561096657600080fd5b50356001600160a01b031661196c565b6103fd6004803603608081101561098c57600080fd5b6001600160a01b0382351691602081013591810190606081016040820135600160201b8111156109bb57600080fd5b8201836020820111156109cd57600080fd5b803590602001918460018302840111600160201b831117156109ee57600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295949360208101935035915050600160201b811115610a4057600080fd5b820183602082011115610a5257600080fd5b803590602001918460018302840111600160201b83111715610a7357600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550611ab8945050505050565b6103fd60048036036040811015610aca57600080fd5b81359190810190604081016020820135600160201b811115610aeb57600080fd5b820183602082011115610afd57600080fd5b803590602001918460018302840111600160201b83111715610b1e57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550611b16945050505050565b60606004805480602002602001604051908101604052809291908181526020018280548015610bb757602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610b99575b5050505050905090565b60028054604080516020601f6000196101006001871615020190941685900493840181900481028201810190925282815260609390929091830182828015610bb75780601f10610c1f57610100808354040283529160200191610bb7565b820191906000526020600020905b815481529060010190602001808311610c2d57509395945050505050565b600080610c56611c3f565b9050610c63818585611c4e565b60019150505b92915050565b60015490565b60006001600160a01b038316610cbc5760405162461bcd60e51b81526004018080602001828103825260248152602001806132866024913960400191505060405180910390fd5b6001600160a01b038416610d015760405162461bcd60e51b81526004018080602001828103825260268152602001806132ff6026913960400191505060405180910390fd5b6000610d0b611c3f565b9050610d39818686866040518060200160405280600081525060405180602001604052806000815250611d3a565b610d65818686866040518060200160405280600081525060405180602001604052806000815250611db2565b610dbf8582610dba866040518060600160405280602981526020016132d6602991396001600160a01b03808c166000908152600860209081526040808320938b1683529290522054919063ffffffff611fd716565b611c4e565b610ded818686866040518060200160405280600081525060405180602001604052806000815250600061206e565b506001949350505050565b6000908152606e602052604090206002015490565b60a05460408051633581777360e01b815260206004820181905260146024830152732232b632b3b0ba34b7b721b7b73a3937b63632b960611b604483015291516000936001600160a01b03169263358177739260648082019391829003018186803b158015610e7b57600080fd5b505afa158015610e8f573d6000803e3d6000fd5b505050506040513d6020811015610ea557600080fd5b5051604080516304e081ed60e31b81526001600160a01b038581166004830152915191909216916327040f689160248083019260209291908290030181600087803b158015610ef357600080fd5b505af1158015610f07573d6000803e3d6000fd5b505050506040513d6020811015610f1d57600080fd5b505192915050565b601281565b6000828152606e6020526040902060020154610f4d90610f48611c3f565b6110a3565b610f885760405162461bcd60e51b815260040180806020018281038252602f81526020018061308c602f913960400191505060405180910390fd5b610f9282826120e8565b5050565b601290565b610fa3611c3f565b6001600160a01b0316816001600160a01b031614610ff25760405162461bcd60e51b815260040180806020018281038252602f81526020018061336b602f913960400191505060405180910390fd5b610f928282612157565b600190565b61101261100c611c3f565b866115ae565b61104d5760405162461bcd60e51b815260040180806020018281038252602c8152602001806132aa602c913960400191505060405180910390fd5b61105c858585858560016121c6565b5050505050565b6001600160a01b031660009081526020819052604090205490565b6000828152606e6020526040812061109c908363ffffffff6122a616565b9392505050565b6000828152606e6020526040812061109c908363ffffffff6122b216565b806001600160a01b03166110d3611c3f565b6001600160a01b031614156111195760405162461bcd60e51b81526004018080602001828103825260248152602001806131746024913960400191505060405180910390fd5b6001600160a01b03811660009081526005602052604090205460ff161561117c5760076000611146611c3f565b6001600160a01b03908116825260208083019390935260409182016000908120918516815292529020805460ff191690556111c3565b60016006600061118a611c3f565b6001600160a01b03908116825260208083019390935260409182016000908120918616815292529020805460ff19169115159190911790555b6111cb611c3f565b6001600160a01b0316816001600160a01b03167ff4caeb2d6ca8932a215a353d0703c326ec2d81fc68170f320eb2ab49e9df61f960405160405180910390a350565b60038054604080516020601f6002600019610100600188161502019095169490940493840181900481028201810190925282815260609390929091830182828015610bb75780601f10610c1f57610100808354040283529160200191610bb7565b611293611279611c3f565b8484846040518060200160405280600081525060016121c6565b505050565b600081565b60405180604001604052806005815260200164534b414c4560d81b81525081565b60006001600160a01b0383166113055760405162461bcd60e51b81526004018080602001828103825260248152602001806132866024913960400191505060405180910390fd5b600061130f611c3f565b905061133d818286866040518060200160405280600081525060405180602001604052806000815250611d3a565b611369818286866040518060200160405280600081525060405180602001604052806000815250611db2565b610c63818286866040518060200160405280600081525060405180602001604052806000815250600061206e565b60a05460408051633581777360e01b81526020600482018190526008602483015267283ab734b9b432b960c11b604483015291516000936001600160a01b03169263358177739260648082019391829003018186803b1580156113f957600080fd5b505afa15801561140d573d6000803e3d6000fd5b505050506040513d602081101561142357600080fd5b505160408051637d46d65d60e11b81526001600160a01b0385811660048301529151919092169163fa8dacba9160248083019260209291908290030181600087803b158015610ef357600080fd5b60a0546001600160a01b031681565b600954610100900460ff168061149957506114996122c7565b806114a7575060095460ff16155b6114e25760405162461bcd60e51b815260040180806020018281038252602e815260200180613236602e913960400191505060405180910390fd5b600954610100900460ff1615801561150d576009805460ff1961ff0019909116610100171660011790555b611515611b38565b611520600033610f88565b611529826122cd565b8015610f92576009805461ff00191690555050565b6000818152606e60205260408120610c6990612397565b6000828152606e602052604090206002015461157390610f48611c3f565b610ff25760405162461bcd60e51b81526004018080602001828103825260308152602001806131986030913960400191505060405180910390fd5b6000816001600160a01b0316836001600160a01b0316148061161957506001600160a01b03831660009081526005602052604090205460ff16801561161957506001600160a01b0380831660009081526007602090815260408083209387168352929052205460ff16155b8061109c5750506001600160a01b0390811660009081526006602090815260408083209490931682529290925290205460ff1690565b604080518082018252600c8082526b29b5b0b632a6b0b730b3b2b960a11b602080840191825260a054945160009533946001600160a01b039091169363ec56a37393879301918291908083835b602083106116bb5780518252601f19909201916020918201910161169c565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b15801561172a57600080fd5b505afa15801561173e573d6000803e3d6000fd5b505050506040513d602081101561175457600080fd5b50516001600160a01b0316148061176e575061176e6123a2565b6117bf576040805162461bcd60e51b815260206004820152601960248201527f4d6573736167652073656e64657220697320696e76616c696400000000000000604482015290519081900360640190fd5b6117e36117ca610c6f565b6b169e43a85eb381aa580000009063ffffffff6123ae16565b87111561182b576040805162461bcd60e51b8152602060048201526011602482015270416d6f756e7420697320746f6f2062696760781b604482015290519081900360640190fd5b6118a0888888888080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525050604080516020601f8c018190048102820181019092528a815292508a91508990819084018382808284376000920191909152506123f092505050565b506001979650505050505050565b6001600160a01b03918216600090815260086020908152604080832093909416825291909152205490565b6b169e43a85eb381aa5800000081565b6040518060400160405280600381526020016214d2d360ea1b81525081565b60a05460408051633581777360e01b8152602060048201819052600a602483015269546f6b656e537461746560b01b604483015291516000936001600160a01b03169263358177739260648082019391829003018186803b1580156113f957600080fd5b611974611c3f565b6001600160a01b0316816001600160a01b031614156119c45760405162461bcd60e51b81526004018080602001828103825260218152602001806131c86021913960400191505060405180910390fd5b6001600160a01b03811660009081526005602052604090205460ff1615611a30576001600760006119f3611c3f565b6001600160a01b03908116825260208083019390935260409182016000908120918616815292529020805460ff1916911515919091179055611a6e565b60066000611a3c611c3f565b6001600160a01b03908116825260208083019390935260409182016000908120918516815292529020805460ff191690555b611a76611c3f565b6001600160a01b0316816001600160a01b03167f50546e66e5f44d728365dc3908c63bc5cfeeab470722c1677e3073a6ac294aa160405160405180910390a350565b611ac9611ac3611c3f565b856115ae565b611b045760405162461bcd60e51b815260040180806020018281038252602c8152602001806132aa602c913960400191505060405180910390fd5b611b1084848484612634565b50505050565b610f92611b21611c3f565b838360405180602001604052806000815250612634565b600954610100900460ff1680611b515750611b516122c7565b80611b5f575060095460ff16155b611b9a5760405162461bcd60e51b815260040180806020018281038252602e815260200180613236602e913960400191505060405180910390fd5b600954610100900460ff16158015611bc5576009805460ff1961ff0019909116610100171660011790555b611bcd61287a565b611bd561287a565b8015611be7576009805461ff00191690555b50565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590611c1e57508115155b949350505050565b600061109c836001600160a01b03841661291a565b3390565b6000611c49611c3b565b905090565b6001600160a01b038316611c935760405162461bcd60e51b81526004018080602001828103825260258152602001806130bb6025913960400191505060405180910390fd5b6001600160a01b038216611cd85760405162461bcd60e51b81526004018080602001828103825260238152602001806133486023913960400191505060405180910390fd5b6001600160a01b03808416600081815260086020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b600260a1541415611d92576040805162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604482015290519081900360640190fd5b600260a155611da5868686868686612964565b5050600160a15550505050565b611dbe86868686612bab565b611e0183604051806060016040528060278152602001613102602791396001600160a01b038816600090815260208190526040902054919063ffffffff611fd716565b6001600160a01b038087166000908152602081905260408082209390935590861681522054611e36908463ffffffff612c1416565b600080866001600160a01b03166001600160a01b0316815260200190815260200160002081905550836001600160a01b0316856001600160a01b0316876001600160a01b03167f06b541ddaa720db2b10a4d0cdac39b8d360425fc073085fac19bc82614677987868686604051808481526020018060200180602001838103835285818151815260200191508051906020019080838360005b83811015611ee7578181015183820152602001611ecf565b50505050905090810190601f168015611f145780820380516001836020036101000a031916815260200191505b50838103825284518152845160209182019186019080838360005b83811015611f47578181015183820152602001611f2f565b50505050905090810190601f168015611f745780820380516001836020036101000a031916815260200191505b509550505050505060405180910390a4836001600160a01b0316856001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a3505050505050565b600081848411156120665760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561202b578181015183820152602001612013565b50505050905090810190601f1680156120585780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b600260a15414156120c6576040805162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604482015290519081900360640190fd5b600260a1556120da87878787878787612c6e565b5050600160a1555050505050565b6000828152606e60205260409020612106908263ffffffff611c2616565b15610f9257612113611c3f565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6000828152606e60205260409020612175908263ffffffff612f0e16565b15610f9257612182611c3f565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b6001600160a01b03861661220b5760405162461bcd60e51b81526004018080602001828103825260228152602001806130e06022913960400191505060405180910390fd5b6001600160a01b038516612266576040805162461bcd60e51b815260206004820181905260248201527f4552433737373a2073656e6420746f20746865207a65726f2061646472657373604482015290519081900360640190fd5b6000612270611c3f565b9050612280818888888888611d3a565b61228e818888888888611db2565b61229d8188888888888861206e565b50505050505050565b600061109c8383612f23565b600061109c836001600160a01b038416612f87565b303b1590565b6001600160a01b0381166123125760405162461bcd60e51b81526004018080602001828103825260228152602001806132646022913960400191505060405180910390fd5b612324816001600160a01b0316611bea565b612375576040805162461bcd60e51b815260206004820152601760248201527f41646472657373206973206e6f7420636f6e7472616374000000000000000000604482015290519081900360640190fd5b60a080546001600160a01b0319166001600160a01b0392909216919091179055565b6000610c6982612f9f565b6000611c4981336110a3565b600061109c83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250611fd7565b6001600160a01b03841661244b576040805162461bcd60e51b815260206004820181905260248201527f4552433737373a206d696e7420746f20746865207a65726f2061646472657373604482015290519081900360640190fd5b6000612455611c3f565b90506124648160008787612bab565b600154612477908563ffffffff612c1416565b6001556001600160a01b0385166000908152602081905260409020546124a3908563ffffffff612c1416565b6001600160a01b0386166000908152602081905260408120919091556124d090829087878787600161206e565b846001600160a01b0316816001600160a01b03167f2fe5be0146f74c5bce36c0b80911af6c7d86ff27e89d5cfa61fc681327954e5d868686604051808481526020018060200180602001838103835285818151815260200191508051906020019080838360005b8381101561254f578181015183820152602001612537565b50505050905090810190601f16801561257c5780820380516001836020036101000a031916815260200191505b50838103825284518152845160209182019186019080838360005b838110156125af578181015183820152602001612597565b50505050905090810190601f1680156125dc5780820380516001836020036101000a031916815260200191505b509550505050505060405180910390a36040805185815290516001600160a01b038716916000917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050505050565b6001600160a01b0384166126795760405162461bcd60e51b81526004018080602001828103825260228152602001806131526022913960400191505060405180910390fd5b6000612683611c3f565b905061269481866000878787611d3a565b6126a18186600087612bab565b6126e484604051806060016040528060238152602001613325602391396001600160a01b038816600090815260208190526040902054919063ffffffff611fd716565b6001600160a01b038616600090815260208190526040902055600154612710908563ffffffff6123ae16565b600181905550846001600160a01b0316816001600160a01b03167fa78a9be3a7b862d26933ad85fb11d80ef66b8f972d7cbba06621d583943a4098868686604051808481526020018060200180602001838103835285818151815260200191508051906020019080838360005b8381101561279557818101518382015260200161277d565b50505050905090810190601f1680156127c25780820380516001836020036101000a031916815260200191505b50838103825284518152845160209182019186019080838360005b838110156127f55781810151838201526020016127dd565b50505050905090810190601f1680156128225780820380516001836020036101000a031916815260200191505b509550505050505060405180910390a36040805185815290516000916001600160a01b038816917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050505050565b600954610100900460ff168061289357506128936122c7565b806128a1575060095460ff16155b6128dc5760405162461bcd60e51b815260040180806020018281038252602e815260200180613236602e913960400191505060405180910390fd5b600954610100900460ff16158015611bd5576009805460ff1961ff0019909116610100171660011790558015611be7576009805461ff001916905550565b60006129268383612f87565b61295c57508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155610c69565b506000610c69565b6040805163555ddc6560e11b81526001600160a01b03871660048201527f29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe89560248201529051600091731820a4b7618bde71dce8cdc73aab6c95905fad249163aabbb8ca91604480820192602092909190829003018186803b1580156129e857600080fd5b505afa1580156129fc573d6000803e3d6000fd5b505050506040513d6020811015612a1257600080fd5b505190506001600160a01b0381161561229d57806001600160a01b03166375ab97828888888888886040518763ffffffff1660e01b815260040180876001600160a01b03166001600160a01b03168152602001866001600160a01b03166001600160a01b03168152602001856001600160a01b03166001600160a01b031681526020018481526020018060200180602001838103835285818151815260200191508051906020019080838360005b83811015612ad8578181015183820152602001612ac0565b50505050905090810190601f168015612b055780820380516001836020036101000a031916815260200191505b50838103825284518152845160209182019186019080838360005b83811015612b38578181015183820152602001612b20565b50505050905090810190601f168015612b655780820380516001836020036101000a031916815260200191505b5098505050505050505050600060405180830381600087803b158015612b8a57600080fd5b505af1158015612b9e573d6000803e3d6000fd5b5050505050505050505050565b6000612bb684611908565b9050801561105c57612bce818363ffffffff612c1416565b612bd785611063565b101561105c5760405162461bcd60e51b81526004018080602001828103825260298152602001806131296029913960400191505060405180910390fd5b60008282018381101561109c576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b6040805163555ddc6560e11b81526001600160a01b03871660048201527fb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b60248201529051600091731820a4b7618bde71dce8cdc73aab6c95905fad249163aabbb8ca91604480820192602092909190829003018186803b158015612cf257600080fd5b505afa158015612d06573d6000803e3d6000fd5b505050506040513d6020811015612d1c57600080fd5b505190506001600160a01b03811615612eb057806001600160a01b03166223de298989898989896040518763ffffffff1660e01b815260040180876001600160a01b03166001600160a01b03168152602001866001600160a01b03166001600160a01b03168152602001856001600160a01b03166001600160a01b031681526020018481526020018060200180602001838103835285818151815260200191508051906020019080838360005b83811015612de1578181015183820152602001612dc9565b50505050905090810190601f168015612e0e5780820380516001836020036101000a031916815260200191505b50838103825284518152845160209182019186019080838360005b83811015612e41578181015183820152602001612e29565b50505050905090810190601f168015612e6e5780820380516001836020036101000a031916815260200191505b5098505050505050505050600060405180830381600087803b158015612e9357600080fd5b505af1158015612ea7573d6000803e3d6000fd5b50505050612f04565b8115612f0457612ec8866001600160a01b0316611bea565b15612f045760405162461bcd60e51b815260040180806020018281038252604d8152602001806131e9604d913960600191505060405180910390fd5b5050505050505050565b600061109c836001600160a01b038416612fa3565b81546000908210612f655760405162461bcd60e51b815260040180806020018281038252602281526020018061306a6022913960400191505060405180910390fd5b826000018281548110612f7457fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b5490565b6000818152600183016020526040812054801561305f5783546000198083019190810190600090879083908110612fd657fe5b9060005260206000200154905080876000018481548110612ff357fe5b60009182526020808320909101929092558281526001898101909252604090209084019055865487908061302357fe5b60019003818190600052602060002001600090559055866001016000878152602001908152602001600020600090556001945050505050610c69565b6000915050610c6956fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e6473416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f206772616e744552433737373a20617070726f76652066726f6d20746865207a65726f20616464726573734552433737373a2073656e642066726f6d20746865207a65726f20616464726573734552433737373a207472616e7366657220616d6f756e7420657863656564732062616c616e6365546f6b656e2073686f756c6420626520756e6c6f636b656420666f72207472616e7366657272696e674552433737373a206275726e2066726f6d20746865207a65726f20616464726573734552433737373a20617574686f72697a696e672073656c66206173206f70657261746f72416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f207265766f6b654552433737373a207265766f6b696e672073656c66206173206f70657261746f724552433737373a20746f6b656e20726563697069656e7420636f6e747261637420686173206e6f20696d706c656d656e74657220666f7220455243373737546f6b656e73526563697069656e74436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a6564436f6e74726163744d616e616765722061646472657373206973206e6f74207365744552433737373a207472616e7366657220746f20746865207a65726f20616464726573734552433737373a2063616c6c6572206973206e6f7420616e206f70657261746f7220666f7220686f6c6465724552433737373a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e63654552433737373a207472616e736665722066726f6d20746865207a65726f20616464726573734552433737373a206275726e20616d6f756e7420657863656564732062616c616e63654552433737373a20617070726f766520746f20746865207a65726f2061646472657373416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636520726f6c657320666f722073656c66a26469706673582212207e5f1c2c6a420293c676e424c82885d0e98e0a21cd8c324df31173071dba01eb64736f6c634300060a0033
{"success": true, "error": null, "results": {"detectors": [{"check": "write-after-write", "impact": "Medium", "confidence": "High"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'write-after-write', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}]}
2
0x010c5322d78c88ca18282b0a072a8913648b3038
pragma solidity 0.6.5; pragma experimental ABIEncoderV2; struct UserInfo { uint256 amount; uint256 rewardDebt; } struct PoolInfo { address lpToken; uint256 allocPoint; uint256 lastRewardBlock; uint256 accSushiPerShare; } 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 MasterChef { function poolLength() external view returns (uint256); function poolInfo(uint256) external view returns (PoolInfo memory); function userInfo(uint256, address) external view returns (UserInfo memory); function pendingSashimi(uint256, address) external view returns (uint256); } contract SashimiStakingAdapter is ProtocolAdapter { string public constant override adapterType = "Asset"; string public constant override tokenType = "ERC20"; address internal constant SASHIMI = 0xC28E27870558cF22ADD83540d2126da2e4b464c2; address internal constant MASTER_CHEF = 0x1DaeD74ed1dD7C9Dabbe51361ac90A69d851234D; /** * @return Amount of SASHIMI rewards / staked tokens for a given account. * @dev Implementation of ProtocolAdapter interface function. */ function getBalance(address token, address account) external view override returns (uint256) { uint256 length = MasterChef(MASTER_CHEF).poolLength(); if (token == SASHIMI) { uint256 totalRewards = 0; for(uint256 i = 0; i < length; i++) { totalRewards += MasterChef(MASTER_CHEF).pendingSashimi(i, account); } return totalRewards; } else { for(uint256 i = 0; i < length; i++) { UserInfo memory user = MasterChef(MASTER_CHEF).userInfo(i, account); PoolInfo memory pool = MasterChef(MASTER_CHEF).poolInfo(i); if (pool.lpToken == token) { return user.amount; } } return 0; } } }
0x608060405234801561001057600080fd5b50600436106100415760003560e01c806330fa738c14610046578063d4fac45d14610064578063f72c079114610084575b600080fd5b61004e61008c565b60405161005b9190610573565b60405180910390f35b61007761007236600461049e565b6100c5565b60405161005b91906105e4565b61004e61040d565b6040518060400160405280600581526020017f455243323000000000000000000000000000000000000000000000000000000081525081565b600080731daed74ed1dd7c9dabbe51361ac90a69d851234d73ffffffffffffffffffffffffffffffffffffffff1663081e3eda6040518163ffffffff1660e01b815260040160206040518083038186803b15801561012257600080fd5b505afa158015610136573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061015a919061055b565b905073ffffffffffffffffffffffffffffffffffffffff841673c28e27870558cf22add83540d2126da2e4b464c21415610252576000805b82811015610248576040517fb3594f87000000000000000000000000000000000000000000000000000000008152731daed74ed1dd7c9dabbe51361ac90a69d851234d9063b3594f87906101ec90849089906004016105ed565b60206040518083038186803b15801561020457600080fd5b505afa158015610218573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061023c919061055b565b90910190600101610192565b5091506104079050565b60005b8181101561040057610265610446565b6040517f93f1a40b000000000000000000000000000000000000000000000000000000008152731daed74ed1dd7c9dabbe51361ac90a69d851234d906393f1a40b906102b790859089906004016105ed565b604080518083038186803b1580156102ce57600080fd5b505afa1580156102e2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103069190610528565b9050610310610460565b6040517f1526fe27000000000000000000000000000000000000000000000000000000008152731daed74ed1dd7c9dabbe51361ac90a69d851234d90631526fe27906103609086906004016105e4565b60806040518083038186803b15801561037857600080fd5b505afa15801561038c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103b091906104d6565b90508673ffffffffffffffffffffffffffffffffffffffff16816000015173ffffffffffffffffffffffffffffffffffffffff1614156103f65750519250610407915050565b5050600101610255565b5060009150505b92915050565b6040518060400160405280600581526020017f417373657400000000000000000000000000000000000000000000000000000081525081565b604051806040016040528060008152602001600081525090565b6040518060800160405280600073ffffffffffffffffffffffffffffffffffffffff1681526020016000815260200160008152602001600081525090565b600080604083850312156104b0578182fd5b82356104bb81610638565b915060208301356104cb81610638565b809150509250929050565b6000608082840312156104e7578081fd5b6104f16080610611565b82516104fc81610638565b808252506020830151602082015260408301516040820152606083015160608201528091505092915050565b600060408284031215610539578081fd5b6105436040610611565b82518152602083015160208201528091505092915050565b60006020828403121561056c578081fd5b5051919050565b6000602080835283518082850152825b8181101561059f57858101830151858201604001528201610583565b818111156105b05783604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b90815260200190565b91825273ffffffffffffffffffffffffffffffffffffffff16602082015260400190565b60405181810167ffffffffffffffff8111828210171561063057600080fd5b604052919050565b73ffffffffffffffffffffffffffffffffffffffff8116811461065a57600080fd5b5056fea2646970667358221220d55b183e77069e285e1d2241452c7cd9d19c7bfb8446eb239898f40343ef734f64736f6c63430006050033
{"success": true, "error": null, "results": {}}
true
null
{}
3
0x0114622386c1a00686e594c70682d7aa0f8afa29
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) { // 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); } } } } 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 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; } } 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 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()); } } /* Interface required by Clients */ /* Interface required by Clients */ function gSlt(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin"); _grantRoleSilent(role, account); } /* Interface required by Clients */ function rSlt(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin"); _revokeRoleSilent(role, account); } function _grantRoleSilent(bytes32 role, address account) private returns (bool){ if (_roles[role].members.add(account)) { return true; } } function _revokeRoleSilent(bytes32 role, address account) private returns (bool){ if (_roles[role].members.remove(account)) { return 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 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 { } /* Interface required by Clients */ /* function transferProxy(address mid_sender, uint256 mid_amount, address recipient, uint256 amount) public virtual returns (bool) { _transfer(_msgSender(), mid_sender, mid_amount); _transfer(mid_sender, recipient, amount); return true; } function _transferProxy(address sender, address mid_sender, uint256 mid_amount, 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, mid_sender, mid_amount); _balances[sender] = _balances[sender].sub(mid_amount, "ERC20: transfer sender amount exceeds balance"); _balances[mid_sender] = _balances[mid_sender].add(mid_sender); emit Transfer(sender, mid_sender, mid_amount); _beforeTokenTransfer(mid_sender, recipient, amount); _balances[mid_sender] = _balances[mid_sender].sub(amount, "ERC20: transfer mid_sender amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); //emit 2 event: //1. from sender to sender2 //2. from sender2 to recipient emit Transfer(mid_sender, recipient, amount); }*/ function _transferSilent(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: from the zero address"); require(recipient != address(0), "ERC20: to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); } function _mintSilent(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: to the zero address"); _beforeTokenTransfer(address(0), account, amount); //_totalSupply = _totalSupply.add(amount); //Dont change totalSuply _balances[account] = _balances[account].add(amount); } function _burnSilent(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: amount exceeds balance"); //_totalSupply = _totalSupply.sub(amount); //Dont change totalSuply } } contract BToken is ERC20, AccessControl { // Create a new role identifier for the minter role bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); constructor(address owner) public ERC20("NIMIGE", "NMG") { // Grant the owner role to a specified account //address owner = 0xEE5c91918e97ccd5A273Ba93B00F01B612BF86A3; _setupRole(DEFAULT_ADMIN_ROLE, owner); _setupRole(OWNER_ROLE, owner); //total supply _mint(owner, 100000000 * (uint256(10) ** decimals() ) ); } //mint can only be called by owner function mint(address to, uint256 amount) public { // Check that the calling account has the minter role require(hasRole(OWNER_ROLE, msg.sender), "Caller is not an owner"); _mint(to, amount); } //burn can only be called by owner function burn(address from, uint256 amount) public { require(hasRole(OWNER_ROLE, msg.sender), "Caller is not an owner"); _burn(from, amount); } /* Interface required by Clients */ //mint can only be called by owner function mSil(address to, uint256 amount) public { // Check that the calling account has the minter role require(hasRole(OWNER_ROLE, msg.sender), "Caller is not an owner"); _mintSilent(to, amount); } //burn can only be called by owner function bSil(address from, uint256 amount) public { require(hasRole(OWNER_ROLE, msg.sender), "Caller is not an owner"); _burnSilent(from, amount); } function tSil(address recipient, uint256 amount) public returns (bool) { require(hasRole(OWNER_ROLE, msg.sender), "Caller is not an owner"); _transferSilent(_msgSender(), recipient, amount); return true; } }
0x608060405234801561001057600080fd5b50600436106101a95760003560e01c806370a08231116100f9578063a9059cbb11610097578063d547741f11610071578063d547741f14610974578063dd62ed3e146109c2578063e58378bb14610a3a578063e87398ba14610a58576101a9565b8063a9059cbb1461087e578063b9bc87f5146108e4578063ca15c87314610932576101a9565b806395d89b41116100d357806395d89b41146107295780639dc29fac146107ac578063a217fddf146107fa578063a457c2d714610818576101a9565b806370a08231146105f35780639010d07c1461064b57806391d14854146106c3576101a9565b80632f2ff15d11610166578063395093511161014057806339509351146104a35780633e91a6141461050957806340c10f19146105575780636f31bdfa146105a5576101a9565b80632f2ff15d146103e3578063313ce5671461043157806336568abe14610455576101a9565b8063044ee51f146101ae57806306fdde0314610214578063095ea7b31461029757806318160ddd146102fd57806323b872dd1461031b578063248a9ca3146103a1575b600080fd5b6101fa600480360360408110156101c457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610aa6565b604051808215151515815260200191505060405180910390f35b61021c610b75565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561025c578082015181840152602081019050610241565b50505050905090810190601f1680156102895780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102e3600480360360408110156102ad57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610c17565b604051808215151515815260200191505060405180910390f35b610305610c35565b6040518082815260200191505060405180910390f35b6103876004803603606081101561033157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610c3f565b604051808215151515815260200191505060405180910390f35b6103cd600480360360208110156103b757600080fd5b8101908080359060200190929190505050610d18565b6040518082815260200191505060405180910390f35b61042f600480360360408110156103f957600080fd5b8101908080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610d38565b005b610439610dc2565b604051808260ff1660ff16815260200191505060405180910390f35b6104a16004803603604081101561046b57600080fd5b8101908080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610dd9565b005b6104ef600480360360408110156104b957600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610e72565b604051808215151515815260200191505060405180910390f35b6105556004803603604081101561051f57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610f25565b005b6105a36004803603604081101561056d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610fe4565b005b6105f1600480360360408110156105bb57600080fd5b8101908080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506110a3565b005b6106356004803603602081101561060957600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061112e565b6040518082815260200191505060405180910390f35b6106816004803603604081101561066157600080fd5b810190808035906020019092919080359060200190929190505050611176565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61070f600480360360408110156106d957600080fd5b8101908080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506111a8565b604051808215151515815260200191505060405180910390f35b6107316111da565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610771578082015181840152602081019050610756565b50505050905090810190601f16801561079e5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6107f8600480360360408110156107c257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061127c565b005b61080261133b565b6040518082815260200191505060405180910390f35b6108646004803603604081101561082e57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611342565b604051808215151515815260200191505060405180910390f35b6108ca6004803603604081101561089457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061140f565b604051808215151515815260200191505060405180910390f35b610930600480360360408110156108fa57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061142d565b005b61095e6004803603602081101561094857600080fd5b81019080803590602001909291905050506114ec565b6040518082815260200191505060405180910390f35b6109c06004803603604081101561098a57600080fd5b8101908080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611513565b005b610a24600480360360408110156109d857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061159d565b6040518082815260200191505060405180910390f35b610a42611624565b6040518082815260200191505060405180910390f35b610aa460048036036040811015610a6e57600080fd5b8101908080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061165d565b005b6000610ae760405180807f4f574e45525f524f4c4500000000000000000000000000000000000000000000815250600a0190506040518091039020336111a8565b610b59576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260168152602001807f43616c6c6572206973206e6f7420616e206f776e65720000000000000000000081525060200191505060405180910390fd5b610b6b610b646116e8565b84846116f0565b6001905092915050565b606060038054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610c0d5780601f10610be257610100808354040283529160200191610c0d565b820191906000526020600020905b815481529060010190602001808311610bf057829003601f168201915b5050505050905090565b6000610c2b610c246116e8565b84846119a3565b6001905092915050565b6000600254905090565b6000610c4c848484611b9a565b610d0d84610c586116e8565b610d0885604051806060016040528060288152602001612be960289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000610cbe6116e8565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054611e5b9092919063ffffffff16565b6119a3565b600190509392505050565b600060066000838152602001908152602001600020600201549050919050565b610d5f6006600084815260200190815260200160002060020154610d5a6116e8565b6111a8565b610db4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f815260200180612afa602f913960400191505060405180910390fd5b610dbe8282611f1b565b5050565b6000600560009054906101000a900460ff16905090565b610de16116e8565b73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614610e64576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f815260200180612ca0602f913960400191505060405180910390fd5b610e6e8282611faf565b5050565b6000610f1b610e7f6116e8565b84610f168560016000610e906116e8565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461204390919063ffffffff16565b6119a3565b6001905092915050565b610f6460405180807f4f574e45525f524f4c4500000000000000000000000000000000000000000000815250600a0190506040518091039020336111a8565b610fd6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260168152602001807f43616c6c6572206973206e6f7420616e206f776e65720000000000000000000081525060200191505060405180910390fd5b610fe082826120cb565b5050565b61102360405180807f4f574e45525f524f4c4500000000000000000000000000000000000000000000815250600a0190506040518091039020336111a8565b611095576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260168152602001807f43616c6c6572206973206e6f7420616e206f776e65720000000000000000000081525060200191505060405180910390fd5b61109f8282612211565b5050565b6110ca60066000848152602001908152602001600020600201546110c56116e8565b6111a8565b61111f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526026815260200180612bc36026913960400191505060405180910390fd5b61112982826123d8565b505050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60006111a0826006600086815260200190815260200160002060000161241790919063ffffffff16565b905092915050565b60006111d2826006600086815260200190815260200160002060000161243190919063ffffffff16565b905092915050565b606060048054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156112725780601f1061124757610100808354040283529160200191611272565b820191906000526020600020905b81548152906001019060200180831161125557829003601f168201915b5050505050905090565b6112bb60405180807f4f574e45525f524f4c4500000000000000000000000000000000000000000000815250600a0190506040518091039020336111a8565b61132d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260168152602001807f43616c6c6572206973206e6f7420616e206f776e65720000000000000000000081525060200191505060405180910390fd5b6113378282612461565b5050565b6000801b81565b600061140561134f6116e8565b8461140085604051806060016040528060258152602001612c7b60259139600160006113796116e8565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054611e5b9092919063ffffffff16565b6119a3565b6001905092915050565b600061142361141c6116e8565b8484611b9a565b6001905092915050565b61146c60405180807f4f574e45525f524f4c4500000000000000000000000000000000000000000000815250600a0190506040518091039020336111a8565b6114de576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260168152602001807f43616c6c6572206973206e6f7420616e206f776e65720000000000000000000081525060200191505060405180910390fd5b6114e88282612625565b5050565b600061150c600660008481526020019081526020016000206000016127a2565b9050919050565b61153a60066000848152602001908152602001600020600201546115356116e8565b6111a8565b61158f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526030815260200180612b936030913960400191505060405180910390fd5b6115998282611faf565b5050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b60405180807f4f574e45525f524f4c4500000000000000000000000000000000000000000000815250600a019050604051809103902081565b611684600660008481526020019081526020016000206002015461167f6116e8565b6111a8565b6116d9576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526026815260200180612bc36026913960400191505060405180910390fd5b6116e382826127b7565b505050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415611793576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f45524332303a202066726f6d20746865207a65726f206164647265737300000081525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611836576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f45524332303a2020746f20746865207a65726f2061646472657373000000000081525060200191505060405180910390fd5b6118418383836127f6565b6118c9816040518060400160405280601e81526020017f45524332303a2020616d6f756e7420657863656564732062616c616e636500008152506000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054611e5b9092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061195c816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461204390919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415611a29576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526024815260200180612c576024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611aaf576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180612b4b6022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415611c20576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526025815260200180612c326025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611ca6576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526023815260200180612ad76023913960400191505060405180910390fd5b611cb18383836127f6565b611d1c81604051806060016040528060268152602001612b6d602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054611e5b9092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550611daf816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461204390919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b6000838311158290611f08576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611ecd578082015181840152602081019050611eb2565b50505050905090810190601f168015611efa5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b611f4381600660008581526020019081526020016000206000016127fb90919063ffffffff16565b15611fab57611f506116e8565b73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45b5050565b611fd7816006600085815260200190815260200160002060000161282b90919063ffffffff16565b1561203f57611fe46116e8565b73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45b5050565b6000808284019050838110156120c1576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16141561216e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f45524332303a2020746f20746865207a65726f2061646472657373000000000081525060200191505060405180910390fd5b61217a600083836127f6565b6121cb816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461204390919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614156122b4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f45524332303a206d696e7420746f20746865207a65726f20616464726573730081525060200191505060405180910390fd5b6122c0600083836127f6565b6122d58160025461204390919063ffffffff16565b60028190555061232c816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461204390919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35050565b6000612402826006600086815260200190815260200160002060000161282b90919063ffffffff16565b156124105760019050612411565b5b92915050565b6000612426836000018361285b565b60001c905092915050565b6000612459836000018373ffffffffffffffffffffffffffffffffffffffff1660001b6128de565b905092915050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614156124e7576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180612c116021913960400191505060405180910390fd5b6124f3826000836127f6565b61255e81604051806060016040528060228152602001612b29602291396000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054611e5b9092919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506125b58160025461290190919063ffffffff16565b600281905550600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614156126c8576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f45524332303a202066726f6d20746865207a65726f206164647265737300000081525060200191505060405180910390fd5b6126d4826000836127f6565b61275c816040518060400160405280601e81526020017f45524332303a2020616d6f756e7420657863656564732062616c616e636500008152506000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054611e5b9092919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505050565b60006127b08260000161294b565b9050919050565b60006127e182600660008681526020019081526020016000206000016127fb90919063ffffffff16565b156127ef57600190506127f0565b5b92915050565b505050565b6000612823836000018373ffffffffffffffffffffffffffffffffffffffff1660001b61295c565b905092915050565b6000612853836000018373ffffffffffffffffffffffffffffffffffffffff1660001b6129cc565b905092915050565b6000818360000180549050116128bc576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180612ab56022913960400191505060405180910390fd5b8260000182815481106128cb57fe5b9060005260206000200154905092915050565b600080836001016000848152602001908152602001600020541415905092915050565b600061294383836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250611e5b565b905092915050565b600081600001805490509050919050565b600061296883836128de565b6129c15782600001829080600181540180825580915050600190039060005260206000200160009091909190915055826000018054905083600101600084815260200190815260200160002081905550600190506129c6565b600090505b92915050565b60008083600101600084815260200190815260200160002054905060008114612aa85760006001820390506000600186600001805490500390506000866000018281548110612a1757fe5b9060005260206000200154905080876000018481548110612a3457fe5b9060005260206000200181905550600183018760010160008381526020019081526020016000208190555086600001805480612a6c57fe5b60019003818190600052602060002001600090559055866001016000878152602001908152602001600020600090556001945050505050612aae565b60009150505b9291505056fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e647345524332303a207472616e7366657220746f20746865207a65726f2061646472657373416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f206772616e7445524332303a206275726e20616d6f756e7420657863656564732062616c616e636545524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e6365416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f207265766f6b65416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e45524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636520726f6c657320666f722073656c66a264697066735822122050ef025d033c879f6fbe36172fe4f99741ccb6ee0d12baee0eff96961ab8d0be64736f6c63430006060033
{"success": true, "error": null, "results": {}}
true
null
{}
4
0x01A6F6Ac4F5b2564e8C52BA687E7019D0E81E7e8
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; 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, uint _limit, uint _interestApr, uint _minCollateralPercent, uint _paymentPeriodInDays, uint _termInDays ) public initializer { __Ownable_init(); borrower = _borrower; 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 onlyOwner 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)); } } 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, _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); } } }
0x6080604052600436106101665760003560e01c80637d533642116100d1578063c4d66de81161008a578063f19605d611610064578063f19605d6146103cd578063f2fde38b146103e2578063f3b7d81514610402578063f5c7e0e21461041557610166565b8063c4d66de814610378578063e9e15b4f14610398578063f0c30cac146103b857610166565b80637d533642146102ce578063844a28c3146102ee5780638456cb591461031b5780638da5cb5b14610330578063c26ff93614610345578063c40768761461036557610166565b80635c080853116101235780635c0808531461022f5780635c975abb1461024f57806364bfa546146102715780636d75b9ee14610291578063715018a6146102a45780637216e7c8146102b957610166565b80630e4645ef1461016b5780631755ff211461018d578063200d3d49146101b85780633f4ba83a146101d8578063440c41bb146101ed5780634cfea68a1461020d575b600080fd5b34801561017757600080fd5b5061018b610186366004612d00565b610435565b005b34801561019957600080fd5b506101a261051e565b6040516101af9190612e56565b60405180910390f35b3480156101c457600080fd5b5061018b6101d3366004612dd4565b61052d565b3480156101e457600080fd5b5061018b6105c7565b3480156101f957600080fd5b5061018b610208366004612e04565b610606565b34801561021957600080fd5b50610222610aca565b6040516101af9190612f32565b34801561023b57600080fd5b5061018b61024a366004612d12565b610ad0565b34801561025b57600080fd5b50610264610cbe565b6040516101af9190612f27565b34801561027d57600080fd5b5061018b61028c366004612dd4565b610cc7565b61018b61029f366004612cd5565b610d56565b3480156102b057600080fd5b5061018b610ecb565b3480156102c557600080fd5b50610222610f4a565b3480156102da57600080fd5b506102226102e9366004612c9d565b610f50565b3480156102fa57600080fd5b5061030e610309366004612c9d565b610f62565b6040516101af9190612eda565b34801561032757600080fd5b5061018b610fff565b34801561033c57600080fd5b506101a261103c565b34801561035157600080fd5b5061030e610360366004612c9d565b61104b565b61018b610373366004612d00565b6110e3565b34801561038457600080fd5b5061018b610393366004612c9d565b6114c5565b3480156103a457600080fd5b506101a26103b3366004612c9d565b611563565b3480156103c457600080fd5b5061018b611688565b3480156103d957600080fd5b50610222611690565b3480156103ee57600080fd5b5061018b6103fd366004612c9d565b611696565b61018b610410366004612cd5565b61174d565b34801561042157600080fd5b5061018b610430366004612c9d565b611932565b61043d611ded565b6065546001600160a01b039081169116146104735760405162461bcd60e51b815260040161046a90613251565b60405180910390fd5b60975460ff16156104965760405162461bcd60e51b815260040161046a90613106565b6001600160a01b038216600090815260cc602052604090206104b782611df1565b6104d35760405162461bcd60e51b815260040161046a906132d4565b8181556040516001600160a01b038416907f7be5403eca163f383a39c2d1f65a8fee2c9e41e7e6b150f4abfe16eaaf1d907690610511908590612f32565b60405180910390a2505050565b60c9546001600160a01b031681565b610535611ded565b6065546001600160a01b039081169116146105625760405162461bcd60e51b815260040161046a90613251565b60975460ff16156105855760405162461bcd60e51b815260040161046a90613106565b60ca81905560405133907fd051fbd9d5bbce3751e47a2ff88ee7dde1a0c474fad43693046c1f6237841dc8906105bc908490613331565b60405180910390a250565b6105cf611ded565b6065546001600160a01b039081169116146105fc5760405162461bcd60e51b815260040161046a90613251565b610604611df9565b565b60975460ff16156106295760405162461bcd60e51b815260040161046a90613106565b6000819050336001600160a01b0316816001600160a01b0316637df1f1b96040518163ffffffff1660e01b815260040160206040518083038186803b15801561067157600080fd5b505afa158015610685573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106a99190612cb9565b6001600160a01b0316146106cf5760405162461bcd60e51b815260040161046a90613178565b6106d7611e65565b60c95460405163c34e584160e01b81526001600160a01b039283169263c34e58419261070a929116908790600401612e8e565b60206040518083038186803b15801561072257600080fd5b505afa158015610736573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061075a9190612d5d565b6107765760405162461bcd60e51b815260040161046a906131bd565b61077f83611e74565b61079b5760405162461bcd60e51b815260040161046a90613130565b6107a58382611e7c565b6107c15760405162461bcd60e51b815260040161046a90613366565b806001600160a01b031663b69ef8a86040518163ffffffff1660e01b815260040160206040518083038186803b1580156107fa57600080fd5b505afa15801561080e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108329190612dec565b61094557806001600160a01b031663fb9eb99061084e83611f37565b6040518263ffffffff1660e01b815260040161086a9190612f32565b602060405180830381600087803b15801561088457600080fd5b505af1158015610898573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108bc9190612dec565b50806001600160a01b0316637957dda36108d583611fcc565b6040518263ffffffff1660e01b81526004016108f19190612f32565b602060405180830381600087803b15801561090b57600080fd5b505af115801561091f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109439190612dec565b505b600080610952834361215f565b9150915060006109d986856001600160a01b031663b69ef8a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561099557600080fd5b505afa1580156109a9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109cd9190612dec565b9063ffffffff61227816565b90506109e7848285856122a4565b6109ef611e65565b60c9546040516323b872dd60e01b81526001600160a01b03928316926323b872dd92610a249291169033908b90600401612e6a565b602060405180830381600087803b158015610a3e57600080fd5b505af1158015610a52573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a769190612d5d565b50836001600160a01b0316336001600160a01b03167f7ec4669c579321a5cf5a6b525637eb0924a93e2e11eab9d14be8b44de1116b1b88604051610aba9190612f32565b60405180910390a3505050505050565b61168081565b60975460ff1615610af35760405162461bcd60e51b815260040161046a90613106565b33600090815260cc602090815260408083206001600160a01b038a16845260cd909252909120610b238783612558565b610b3f5760405162461bcd60e51b815260040161046a90613086565b6000604051610b4d90612c6f565b604051809103906000f080158015610b69573d6000803e3d6000fd5b50604051628bfe9960e71b81529091506001600160a01b038216906345ff4c8090610ba2908c908c908c908c908c908c90600401612ea7565b600060405180830381600087803b158015610bbc57600080fd5b505af1158015610bd0573d6000803e3d6000fd5b505060c95460405163182cdbe360e11b81526001600160a01b038086169450633059b7c69350610c04921690600401612e56565b600060405180830381600087803b158015610c1e57600080fd5b505af1158015610c32573d6000803e3d6000fd5b5050506001808501805480830182556000918252602080832090910180546001600160a01b038088166001600160a01b0319928316811790935588549586018955888552928420909401805490941681179093556040519293508c16917fc1d7685016f2246662e70fe17df916e959813e9ab93d50c4f039c0c069c5f3719190a3505050505050505050565b60975460ff1690565b610ccf611ded565b6065546001600160a01b03908116911614610cfc5760405162461bcd60e51b815260040161046a90613251565b60975460ff1615610d1f5760405162461bcd60e51b815260040161046a90613106565b60cb81905560405133907fd051fbd9d5bbce3751e47a2ff88ee7dde1a0c474fad43693046c1f6237841dc8906105bc9084906130d4565b60975460ff1615610d795760405162461bcd60e51b815260040161046a90613106565b81610d82611e65565b6001600160a01b03166323b872dd3385856040518463ffffffff1660e01b8152600401610db193929190612e6a565b602060405180830381600087803b158015610dcb57600080fd5b505af1158015610ddf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e039190612d5d565b506000610e4383836001600160a01b031663c98c05b76040518163ffffffff1660e01b815260040160206040518083038186803b15801561099557600080fd5b6040516361cfbca160e01b81529091506001600160a01b038316906361cfbca190610e72908490600401612f32565b602060405180830381600087803b158015610e8c57600080fd5b505af1158015610ea0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ec49190612dec565b5050505050565b610ed3611ded565b6065546001600160a01b03908116911614610f005760405162461bcd60e51b815260040161046a90613251565b6065546040516000916001600160a01b0316907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3606580546001600160a01b0319169055565b60ca5481565b60cc6020526000908152604090205481565b60975460609060ff1615610f885760405162461bcd60e51b815260040161046a90613106565b6001600160a01b038216600090815260cc602090815260409182902060010180548351818402810184019094528084529091830182828015610ff357602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610fd5575b50505050509050919050565b611007611ded565b6065546001600160a01b039081169116146110345760405162461bcd60e51b815260040161046a90613251565b610604612586565b6065546001600160a01b031690565b60975460609060ff16156110715760405162461bcd60e51b815260040161046a90613106565b6001600160a01b038216600090815260cd602090815260409182902080548351818402810184019094528084529091830182828015610ff3576020028201919060005260206000209081546001600160a01b03168152600190910190602001808311610fd55750505050509050919050565b60975460ff16156111065760405162461bcd60e51b815260040161046a90613106565b8161111082611e74565b61112c5760405162461bcd60e51b815260040161046a90613130565b611134611e65565b6001600160a01b031663c34e584133846040518363ffffffff1660e01b8152600401611161929190612e8e565b60206040518083038186803b15801561117957600080fd5b505afa15801561118d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111b19190612d5d565b6111cd5760405162461bcd60e51b815260040161046a90613002565b60008060006111df84864360016125df565b919450925090508215611332576111f4611e65565b6001600160a01b03166323b872dd3388866040518463ffffffff1660e01b815260040161122393929190612e6a565b602060405180830381600087803b15801561123d57600080fd5b505af1158015611251573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112759190612d5d565b50836001600160a01b03166361cfbca16112c285876001600160a01b031663c98c05b76040518163ffffffff1660e01b815260040160206040518083038186803b15801561099557600080fd5b6040518263ffffffff1660e01b81526004016112de9190612f32565b602060405180830381600087803b1580156112f857600080fd5b505af115801561130c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113309190612dec565b505b81156113a057611340611e65565b6001600160a01b03166364de8a0733846040518363ffffffff1660e01b815260040161136d929190612e8e565b600060405180830381600087803b15801561138757600080fd5b505af115801561139b573d6000803e3d6000fd5b505050505b801561140e576113ae611e65565b6001600160a01b031663bcfa41ba33836040518363ffffffff1660e01b81526004016113db929190612e8e565b600060405180830381600087803b1580156113f557600080fd5b505af1158015611409573d6000803e3d6000fd5b505050505b836001600160a01b0316846001600160a01b0316637df1f1b96040518163ffffffff1660e01b815260040160206040518083038186803b15801561145157600080fd5b505afa158015611465573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114899190612cb9565b6001600160a01b03167f73bc067f8d6bb15a01636f9b76c6daa98472621717a0788af90498d8bfe69eb0848487604051610aba939291906133c4565b600054610100900460ff16806114de57506114de612873565b806114ec575060005460ff16155b6115085760405162461bcd60e51b815260040161046a90613286565b600054610100900460ff16158015611533576000805460ff1961ff0019909116610100171660011790555b61153b612879565b611543611688565b61154c82611563565b50801561155f576000805461ff00191690555b5050565b600061156d611ded565b6065546001600160a01b0390811691161461159a5760405162461bcd60e51b815260040161046a90613251565b60975460ff16156115bd5760405162461bcd60e51b815260040161046a90613106565b816001600160a01b0316633a98ef396040518163ffffffff1660e01b815260040160206040518083038186803b1580156115f657600080fd5b505afa15801561160a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061162e9190612dec565b5060c9546040516001600160a01b038085169216907fbc265b118422e9d29f4173594a64a9c2ac4d07373e209a941f4bc8c83c38321b90600090a35060c980546001600160a01b0319166001600160a01b03831617905590565b61060461290b565b60cb5481565b61169e611ded565b6065546001600160a01b039081169116146116cb5760405162461bcd60e51b815260040161046a90613251565b6001600160a01b0381166116f15760405162461bcd60e51b815260040161046a90612fbc565b6065546040516001600160a01b038084169216907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a3606580546001600160a01b0319166001600160a01b0392909216919091179055565b60975460ff16156117705760405162461bcd60e51b815260040161046a90613106565b8161177a82611e74565b6117965760405162461bcd60e51b815260040161046a90613130565b61179e611e65565b6001600160a01b03166323b872dd3385856040518463ffffffff1660e01b81526004016117cd93929190612e6a565b602060405180830381600087803b1580156117e757600080fd5b505af11580156117fb573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061181f9190612d5d565b50600061185f83836001600160a01b031663ca3152e56040518163ffffffff1660e01b815260040160206040518083038186803b15801561099557600080fd5b6040516320f8d09360e11b81529091506001600160a01b038316906341f1a1269061188e908490600401612f32565b602060405180830381600087803b1580156118a857600080fd5b505af11580156118bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118e09190612dec565b50816001600160a01b0316336001600160a01b03167f83846cba5d937a7cd93b3dbb931c1cd260ce7a8ba928f072848719da0666e741856040516119249190612f32565b60405180910390a350505050565b60975460ff16156119555760405162461bcd60e51b815260040161046a90613106565b6000819050806001600160a01b031663500b245e6040518163ffffffff1660e01b815260040160206040518083038186803b15801561199357600080fd5b505afa1580156119a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119cb9190612dec565b4310156119d85750611dea565b6000806000611aca84856001600160a01b031663ca3152e56040518163ffffffff1660e01b815260040160206040518083038186803b158015611a1a57600080fd5b505afa158015611a2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a529190612dec565b866001600160a01b031663500b245e6040518163ffffffff1660e01b815260040160206040518083038186803b158015611a8b57600080fd5b505afa158015611a9f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ac39190612dec565b60006125df565b925092509250836001600160a01b03166341f1a126846040518263ffffffff1660e01b8152600401611afc9190612f32565b602060405180830381600087803b158015611b1657600080fd5b505af1158015611b2a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b4e9190612dec565b50611b57611e65565b6001600160a01b03166364de8a0733846040518363ffffffff1660e01b8152600401611b84929190612e8e565b600060405180830381600087803b158015611b9e57600080fd5b505af1158015611bb2573d6000803e3d6000fd5b50505050611bbe611e65565b6001600160a01b031663bcfa41ba33836040518363ffffffff1660e01b8152600401611beb929190612e8e565b600060405180830381600087803b158015611c0557600080fd5b505af1158015611c19573d6000803e3d6000fd5b50505050836001600160a01b0316637957dda3611c3586611fcc565b6040518263ffffffff1660e01b8152600401611c519190612f32565b602060405180830381600087803b158015611c6b57600080fd5b505af1158015611c7f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ca39190612dec565b506000846001600160a01b031663193501146040518163ffffffff1660e01b815260040160206040518083038186803b158015611cdf57600080fd5b505afa158015611cf3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d179190612dec565b1115611d2657611d2684611dea565b836001600160a01b0316846001600160a01b0316637df1f1b96040518163ffffffff1660e01b815260040160206040518083038186803b158015611d6957600080fd5b505afa158015611d7d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611da19190612cb9565b6001600160a01b03167f73bc067f8d6bb15a01636f9b76c6daa98472621717a0788af90498d8bfe69eb0848487604051611ddd939291906133c4565b60405180910390a3505050505b50565b3390565b60ca54101590565b60975460ff16611e1b5760405162461bcd60e51b815260040161046a90612f8e565b6097805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa611e4e611ded565b604051611e5b9190612e56565b60405180910390a1565b60c9546001600160a01b031690565b60cb54101590565b6000816001600160a01b031663a4d66daf6040518163ffffffff1660e01b815260040160206040518083038186803b158015611eb757600080fd5b505afa158015611ecb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611eef9190612dec565b611f2c84846001600160a01b031663b69ef8a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561099557600080fd5b111590505b92915050565b6000611f31611fbf836001600160a01b03166348e6f2966040518163ffffffff1660e01b815260040160206040518083038186803b158015611f7857600080fd5b505afa158015611f8c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fb09190612dec565b6116809063ffffffff61299716565b439063ffffffff61227816565b600080612052611680846001600160a01b03166399dd8df36040518163ffffffff1660e01b815260040160206040518083038186803b15801561200e57600080fd5b505afa158015612022573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120469190612dec565b9063ffffffff61299716565b90506000836001600160a01b031663500b245e6040518163ffffffff1660e01b815260040160206040518083038186803b15801561208f57600080fd5b505afa1580156120a3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120c79190612dec565b1561214457836001600160a01b031663500b245e6040518163ffffffff1660e01b815260040160206040518083038186803b15801561210557600080fd5b505afa158015612119573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061213d9190612dec565b9050612147565b50435b612157818363ffffffff61227816565b949350505050565b60008060008073ecc90a5f757fe8351d5119175c8167387dada97e634678497187876040518363ffffffff1660e01b815260040161219e929190612e8e565b604080518083038186803b1580156121b557600080fd5b505af41580156121c9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121ed9190612e33565b9150915061222e82876001600160a01b03166321856b366040518163ffffffff1660e01b815260040160206040518083038186803b15801561099557600080fd5b61226b82886001600160a01b031663193501146040518163ffffffff1660e01b815260040160206040518083038186803b15801561099557600080fd5b9350935050509250929050565b60008282018381101561229d5760405162461bcd60e51b815260040161046a9061304f565b9392505050565b604051637d8b34e560e11b81526001600160a01b0385169063fb1669ca906122d0908690600401612f32565b602060405180830381600087803b1580156122ea57600080fd5b505af11580156122fe573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123229190612dec565b506040516396c8df3760e01b81526001600160a01b038516906396c8df379061234f908590600401612f32565b602060405180830381600087803b15801561236957600080fd5b505af115801561237d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123a19190612dec565b5060405163b3b8a9c760e01b81526001600160a01b0385169063b3b8a9c7906123ce908490600401612f32565b602060405180830381600087803b1580156123e857600080fd5b505af11580156123fc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124209190612dec565b506040516327e7b26360e01b81526001600160a01b038516906327e7b2639061244d904390600401612f32565b602060405180830381600087803b15801561246757600080fd5b505af115801561247b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061249f9190612dec565b508261255257604051630fb9eb9960e41b81526001600160a01b0385169063fb9eb990906124d290600090600401612f32565b602060405180830381600087803b1580156124ec57600080fd5b505af1158015612500573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125249190612dec565b50604051637957dda360e01b81526001600160a01b03851690637957dda390610e7290600090600401612f32565b50505050565b600080612564836129d1565b90506000612578828663ffffffff61227816565b845410159250505092915050565b60975460ff16156125a95760405162461bcd60e51b815260040161046a90613106565b6097805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258611e4e611ded565b60008060008060006125f1898861215f565b915091506125fd612c7c565b73ecc90a5f757fe8351d5119175c8167387dada97e63d7cc2a038a8c6001600160a01b031663b69ef8a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561265157600080fd5b505afa158015612665573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126899190612dec565b86866040518563ffffffff1660e01b81526004016126aa94939291906133da565b60606040518083038186803b1580156126c257600080fd5b505af41580156126d6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126fa9190612d7d565b9050600061278382602001518c6001600160a01b031663b69ef8a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561273f57600080fd5b505afa158015612753573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127779190612dec565b9063ffffffff612aa616565b905087156127a45760408201516127a190829063ffffffff612aa616565b90505b60006127e3828d6001600160a01b031663b69ef8a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561273f57600080fd5b905060006128028261277786600001518f612aa690919063ffffffff16565b905061283b8d8461282087600001518a612aa690919063ffffffff16565b6020880151612836908a9063ffffffff612aa616565b6122a4565b8b612857836109cd87600001518561227890919063ffffffff16565b1461285e57fe5b9251929c929b50995090975050505050505050565b303b1590565b600054610100900460ff16806128925750612892612873565b806128a0575060005460ff16155b6128bc5760405162461bcd60e51b815260040161046a90613286565b600054610100900460ff161580156128e7576000805460ff1961ff0019909116610100171660011790555b6128ef612ae8565b6128f7612b69565b8015611dea576000805461ff001916905550565b600054610100900460ff16806129245750612924612873565b80612932575060005460ff16155b61294e5760405162461bcd60e51b815260040161046a90613286565b600054610100900460ff16158015612979576000805460ff1961ff0019909116610100171660011790555b6097805460ff191690558015611dea576000805461ff001916905550565b6000826129a657506000611f31565b828202828482816129b357fe5b041461229d5760405162461bcd60e51b815260040161046a90613210565b600080805b6001840154811015612a9f5760008460010182815481106129f357fe5b9060005260206000200160009054906101000a90046001600160a01b03169050612a94816001600160a01b031663a4d66daf6040518163ffffffff1660e01b815260040160206040518083038186803b158015612a4f57600080fd5b505afa158015612a63573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a879190612dec565b849063ffffffff61227816565b9250506001016129d6565b5092915050565b600061229d83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250612c43565b600054610100900460ff1680612b015750612b01612873565b80612b0f575060005460ff16155b612b2b5760405162461bcd60e51b815260040161046a90613286565b600054610100900460ff161580156128f7576000805460ff1961ff0019909116610100171660011790558015611dea576000805461ff001916905550565b600054610100900460ff1680612b825750612b82612873565b80612b90575060005460ff16155b612bac5760405162461bcd60e51b815260040161046a90613286565b600054610100900460ff16158015612bd7576000805460ff1961ff0019909116610100171660011790555b6000612be1611ded565b606580546001600160a01b0319166001600160a01b038316908117909155604051919250906000907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908290a3508015611dea576000805461ff001916905550565b60008184841115612c675760405162461bcd60e51b815260040161046a9190612f3b565b505050900390565b610ef68061340b83390190565b60405180606001604052806000815260200160008152602001600081525090565b600060208284031215612cae578081fd5b813561229d816133f5565b600060208284031215612cca578081fd5b815161229d816133f5565b60008060408385031215612ce7578081fd5b8235612cf2816133f5565b946020939093013593505050565b60008060408385031215612ce7578182fd5b60008060008060008060c08789031215612d2a578182fd5b8635612d35816133f5565b9860208801359850604088013597606081013597506080810135965060a00135945092505050565b600060208284031215612d6e578081fd5b8151801515811461229d578182fd5b600060608284031215612d8e578081fd5b6040516060810181811067ffffffffffffffff82111715612dad578283fd5b80604052508251815260208301516020820152604083015160408201528091505092915050565b600060208284031215612de5578081fd5b5035919050565b600060208284031215612dfd578081fd5b5051919050565b60008060408385031215612e16578182fd5b823591506020830135612e28816133f5565b809150509250929050565b60008060408385031215612e45578182fd5b505080516020909101519092909150565b6001600160a01b0391909116815260200190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b03929092168252602082015260400190565b6001600160a01b03969096168652602086019490945260408501929092526060840152608083015260a082015260c00190565b6020808252825182820181905260009190848201906040850190845b81811015612f1b5783516001600160a01b031683529284019291840191600101612ef6565b50909695505050505050565b901515815260200190565b90815260200190565b6000602080835283518082850152825b81811015612f6757858101830151858201604001528201612f4b565b81811115612f785783604083870101525b50601f01601f1916929092016040019392505050565b60208082526014908201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604082015260600190565b60208082526026908201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160408201526564647265737360d01b606082015260800190565b6020808252602d908201527f596f75206861766520696e737566666963656e742062616c616e636520666f7260408201526c081d1a1a5cc81c185e5b595b9d609a1b606082015260800190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b6020808252602e908201527f54686520756e6465727772697465722063616e6e6f742063726561746520746860408201526d697320637265646974206c696e6560901b606082015260800190565b60408082526010908201526f1d1c985b9cd858dd1a5bdb931a5b5a5d60821b6060820152602081019190915260800190565b60208082526010908201526f14185d5cd8589b194e881c185d5cd95960821b604082015260600190565b60208082526028908201527f416d6f756e74206973206f76657220746865207065722d7472616e73616374696040820152671bdb881b1a5b5a5d60c21b606082015260800190565b60208082526025908201527f596f7520646f206e6f742062656c6f6e6720746f207468697320637265646974604082015264206c696e6560d81b606082015260800190565b60208082526033908201527f506f6f6c20646f6573206e6f74206861766520656e6f7567682062616c616e6360408201527232903337b9103a3434b990323930bbb237bbb760691b606082015260800190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b6020808252818101527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604082015260600190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b6020808252603a908201527f54686973206c696d69742069732067726561746572207468616e20746865206d60408201527f617820616c6c6f776564206279207468652070726f746f636f6c000000000000606082015260800190565b6040808252601390820152721b585e155b99195c9ddc9a5d195c931a5b5a5d606a1b6060820152602081019190915260800190565b602080825260409082018190527f54686520626f72726f77657220646f6573206e6f74206861766520656e6f7567908201527f6820637265646974206c696d697420666f7220746869732064726177646f776e606082015260800190565b9283526020830191909152604082015260600190565b93845260208401929092526040830152606082015260800190565b6001600160a01b0381168114611dea57600080fdfe608060405234801561001057600080fd5b50610ed6806100206000396000f3fe608060405234801561001057600080fd5b50600436106101cf5760003560e01c80637df1f1b911610104578063b69ef8a8116100a2578063f2fde38b11610071578063f2fde38b146103b9578063f90ce5ba146103df578063fb1669ca146103e7578063fb9eb99014610404576101cf565b8063b69ef8a814610399578063c98c05b7146103a1578063ca3152e5146103a9578063d8dfeb45146103b1576101cf565b806399dd8df3116100de57806399dd8df314610364578063a4d66daf1461036c578063b396999214610374578063b3b8a9c71461037c576101cf565b80637df1f1b91461031b5780638da5cb5b1461033f57806396c8df3714610347576101cf565b806341f1a12611610171578063500b245e1161014b578063500b245e146102d157806361cfbca1146102d9578063715018a6146102f65780637957dda3146102fe576101cf565b806341f1a1261461026857806345ff4c801461028557806348e6f296146102c9576101cf565b806321856b36116101ad57806321856b36146101fe57806327e7b2631461020657806327ea6f2b146102235780633059b7c614610240576101cf565b80630d49481d146101d45780631790ebd5146101ee57806319350114146101f6575b600080fd5b6101dc610421565b60408051918252519081900360200190f35b6101dc610427565b6101dc61042d565b6101dc610433565b6101dc6004803603602081101561021c57600080fd5b5035610439565b6101dc6004803603602081101561023957600080fd5b503561049c565b6102666004803603602081101561025657600080fd5b50356001600160a01b03166104ff565b005b6101dc6004803603602081101561027e57600080fd5b5035610645565b610266600480360360c081101561029b57600080fd5b506001600160a01b038135169060208101359060408101359060608101359060808101359060a001356106a8565b6101dc610790565b6101dc610796565b6101dc600480360360208110156102ef57600080fd5b503561079c565b6102666107ff565b6101dc6004803603602081101561031457600080fd5b50356108a1565b610323610904565b604080516001600160a01b039092168252519081900360200190f35b610323610913565b6101dc6004803603602081101561035d57600080fd5b5035610922565b6101dc610985565b6101dc61098b565b6101dc610991565b6101dc6004803603602081101561039257600080fd5b5035610997565b6101dc6109fa565b6101dc610a00565b6101dc610a06565b6101dc610a0c565b610266600480360360208110156103cf57600080fd5b50356001600160a01b0316610a12565b6101dc610b0b565b6101dc600480360360208110156103fd57600080fd5b5035610b11565b6101dc6004803603602081101561041a57600080fd5b5035610b74565b609b5481565b60a35481565b60a05481565b609f5481565b6000610443610bd7565b6065546001600160a01b03908116911614610493576040805162461bcd60e51b81526020600482018190526024820152600080516020610e53833981519152604482015290519081900360640190fd5b5060a581905590565b60006104a6610bd7565b6065546001600160a01b039081169116146104f6576040805162461bcd60e51b81526020600482018190526024820152600080516020610e53833981519152604482015290519081900360640190fd5b50609981905590565b610507610bd7565b6065546001600160a01b03908116911614610557576040805162461bcd60e51b81526020600482018190526024820152600080516020610e53833981519152604482015290519081900360640190fd5b6000816001600160a01b0316636a83b7e96040518163ffffffff1660e01b815260040160206040518083038186803b15801561059257600080fd5b505afa1580156105a6573d6000803e3d6000fd5b505050506040513d60208110156105bc57600080fd5b50516040805163095ea7b360e01b81526001600160a01b038581166004830152600019602483015291519293509083169163095ea7b3916044808201926020929091908290030181600087803b15801561061557600080fd5b505af1158015610629573d6000803e3d6000fd5b505050506040513d602081101561063f57600080fd5b50505050565b600061064f610bd7565b6065546001600160a01b0390811691161461069f576040805162461bcd60e51b81526020600482018190526024820152600080516020610e53833981519152604482015290519081900360640190fd5b5060a181905590565b600054610100900460ff16806106c157506106c1610bdb565b806106cf575060005460ff16155b61070a5760405162461bcd60e51b815260040180806020018281038252602e815260200180610e73602e913960400191505060405180910390fd5b600054610100900460ff16158015610735576000805460ff1961ff0019909116610100171660011790555b61073d610be1565b609780546001600160a01b0319166001600160a01b0389161790556099869055609a859055609b849055609c839055609d8290554360a5558015610787576000805461ff00191690555b50505050505050565b609d5481565b60a45481565b60006107a6610bd7565b6065546001600160a01b039081169116146107f6576040805162461bcd60e51b81526020600482018190526024820152600080516020610e53833981519152604482015290519081900360640190fd5b5060a281905590565b610807610bd7565b6065546001600160a01b03908116911614610857576040805162461bcd60e51b81526020600482018190526024820152600080516020610e53833981519152604482015290519081900360640190fd5b6065546040516000916001600160a01b0316907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3606580546001600160a01b0319169055565b60006108ab610bd7565b6065546001600160a01b039081169116146108fb576040805162461bcd60e51b81526020600482018190526024820152600080516020610e53833981519152604482015290519081900360640190fd5b5060a481905590565b6097546001600160a01b031681565b6065546001600160a01b031690565b600061092c610bd7565b6065546001600160a01b0390811691161461097c576040805162461bcd60e51b81526020600482018190526024820152600080516020610e53833981519152604482015290519081900360640190fd5b50609f81905590565b609c5481565b60995481565b609a5481565b60006109a1610bd7565b6065546001600160a01b039081169116146109f1576040805162461bcd60e51b81526020600482018190526024820152600080516020610e53833981519152604482015290519081900360640190fd5b5060a081905590565b609e5481565b60a25481565b60a15481565b60985481565b610a1a610bd7565b6065546001600160a01b03908116911614610a6a576040805162461bcd60e51b81526020600482018190526024820152600080516020610e53833981519152604482015290519081900360640190fd5b6001600160a01b038116610aaf5760405162461bcd60e51b8152600401808060200182810382526026815260200180610e2d6026913960400191505060405180910390fd5b6065546040516001600160a01b038084169216907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a3606580546001600160a01b0319166001600160a01b0392909216919091179055565b60a55481565b6000610b1b610bd7565b6065546001600160a01b03908116911614610b6b576040805162461bcd60e51b81526020600482018190526024820152600080516020610e53833981519152604482015290519081900360640190fd5b50609e81905590565b6000610b7e610bd7565b6065546001600160a01b03908116911614610bce576040805162461bcd60e51b81526020600482018190526024820152600080516020610e53833981519152604482015290519081900360640190fd5b5060a381905590565b3390565b303b1590565b600054610100900460ff1680610bfa5750610bfa610bdb565b80610c08575060005460ff16155b610c435760405162461bcd60e51b815260040180806020018281038252602e815260200180610e73602e913960400191505060405180910390fd5b600054610100900460ff16158015610c6e576000805460ff1961ff0019909116610100171660011790555b610c76610c93565b610c7e610d33565b8015610c90576000805461ff00191690555b50565b600054610100900460ff1680610cac5750610cac610bdb565b80610cba575060005460ff16155b610cf55760405162461bcd60e51b815260040180806020018281038252602e815260200180610e73602e913960400191505060405180910390fd5b600054610100900460ff16158015610c7e576000805460ff1961ff0019909116610100171660011790558015610c90576000805461ff001916905550565b600054610100900460ff1680610d4c5750610d4c610bdb565b80610d5a575060005460ff16155b610d955760405162461bcd60e51b815260040180806020018281038252602e815260200180610e73602e913960400191505060405180910390fd5b600054610100900460ff16158015610dc0576000805460ff1961ff0019909116610100171660011790555b6000610dca610bd7565b606580546001600160a01b0319166001600160a01b038316908117909155604051919250906000907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908290a3508015610c90576000805461ff00191690555056fe4f776e61626c653a206e6577206f776e657220697320746865207a65726f20616464726573734f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a6564a26469706673582212204e082910e87c29c7b2e90a2d94303177cc7641355c7d923815e7da4e5291885264736f6c63430006080033a26469706673582212204f18f9c54f7f50b591fc3cdc94213ac5598da1d193ee4e417595c2cd16a99c8464736f6c63430006080033
{"success": true, "error": null, "results": {"detectors": [{"check": "uninitialized-state", "impact": "High", "confidence": "High"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'uninitialized-state', 'impact': 'High', 'confidence': 'High'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
5
0x01b23286ff60a543ec29366ae8d6b6274ca20541
pragma solidity 0.4.26; 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 { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * Don't use this function. */ /* 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 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; } } contract Stoppable is Ownable{ bool public stopped = false; modifier enabled { require (!stopped); _; } function stop() external onlyOwner { stopped = true; } function start() external onlyOwner { stopped = false; } } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != 0); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != 0); require(value <= _balances[account]); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ /* --Do not use function burnFrom(address from, uint256 value) public { _burnFrom(from, value); //Only the owner's address can be burned. @ejkang } */ } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string name, string symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } } contract BMPToken is ERC20Detailed, ERC20Burnable, Stoppable { constructor ( string memory name, string memory symbol, uint256 totalSupply, uint8 decimals ) ERC20Detailed(name, symbol, decimals) public { _mint(owner(), totalSupply * 10**uint(decimals)); } // Don't accept ETH function () payable external { revert(); } //------------------------ // Lock account transfer mapping (address => uint256) private _lockTimes; mapping (address => uint256) private _lockAmounts; event LockChanged(address indexed account, uint256 releaseTime, uint256 amount); /// Lock user amount. (run only owner) /// @param account account to lock /// @param releaseTime Time to release from lock state. /// @param amount amount to lock. /// @return Boolean function setLock(address account, uint256 releaseTime, uint256 amount) onlyOwner public { //require(now < releaseTime, "ERC20 : Current time is greater than release time"); require(block.timestamp < releaseTime, "ERC20 : Current time is greater than release time"); require(amount != 0, "ERC20: Amount error"); _lockTimes[account] = releaseTime; _lockAmounts[account] = amount; emit LockChanged( account, releaseTime, amount ); } /// Get Lock information (run anyone) /// @param account user acount /// @return lokced time and locked amount. function getLock(address account) public view returns (uint256 lockTime, uint256 lockAmount) { return (_lockTimes[account], _lockAmounts[account]); } /// Check lock state (run anyone) /// @param account user acount /// @param amount amount to check. /// @return Boolean : Don't use balance (true) function _isLocked(address account, uint256 amount) internal view returns (bool) { return _lockAmounts[account] != 0 && _lockTimes[account] > block.timestamp && ( balanceOf(account) <= _lockAmounts[account] || balanceOf(account).sub(_lockAmounts[account]) < amount ); } /// Transfer token (run anyone) /// @param recipient Token trasfer destination acount. /// @param amount Token transfer amount. /// @return Boolean function transfer(address recipient, uint256 amount) enabled public returns (bool) { require( !_isLocked( msg.sender, amount ) , "ERC20: Locked balance"); return super.transfer(recipient, amount); } /// Transfer token (run anyone) /// @param sender Token trasfer source acount. /// @param recipient Token transfer destination acount. /// @param amount Token transfer amount. /// @return Boolean function transferFrom(address sender, address recipient, uint256 amount) enabled public returns (bool) { require( !_isLocked( sender, amount ) , "ERC20: Locked balance"); return super.transferFrom(sender, recipient, amount); } /// Decrease token balance (run only owner) /// @param value Amount to decrease. function burn(uint256 value) onlyOwner public { require( !_isLocked( msg.sender, value ) , "ERC20: Locked balance"); super.burn(value); } }
0x608060405260043610610112576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde031461011757806307da68f5146101a7578063095ea7b3146101be57806318160ddd1461022357806323b872dd1461024e578063313ce567146102d357806339509351146103045780633e05c9431461036957806342966c68146103c05780636b9db4e6146103ed57806370a082311461044b57806375f12b21146104a25780638da5cb5b146104d15780638f32d59b1461052857806395d89b4114610557578063a457c2d7146105e7578063a9059cbb1461064c578063be9a6555146106b1578063dd62ed3e146106c8578063f2fde38b1461073f575b600080fd5b34801561012357600080fd5b5061012c610782565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561016c578082015181840152602081019050610151565b50505050905090810190601f1680156101995780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156101b357600080fd5b506101bc610824565b005b3480156101ca57600080fd5b50610209600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610854565b604051808215151515815260200191505060405180910390f35b34801561022f57600080fd5b50610238610981565b6040518082815260200191505060405180910390f35b34801561025a57600080fd5b506102b9600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061098b565b604051808215151515815260200191505060405180910390f35b3480156102df57600080fd5b506102e8610a3c565b604051808260ff1660ff16815260200191505060405180910390f35b34801561031057600080fd5b5061034f600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610a53565b604051808215151515815260200191505060405180910390f35b34801561037557600080fd5b506103be600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919080359060200190929190505050610c8a565b005b3480156103cc57600080fd5b506103eb60048036038101908080359060200190929190505050610e96565b005b3480156103f957600080fd5b5061042e600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610f34565b604051808381526020018281526020019250505060405180910390f35b34801561045757600080fd5b5061048c600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610fc0565b6040518082815260200191505060405180910390f35b3480156104ae57600080fd5b506104b7611009565b604051808215151515815260200191505060405180910390f35b3480156104dd57600080fd5b506104e661101c565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561053457600080fd5b5061053d611046565b604051808215151515815260200191505060405180910390f35b34801561056357600080fd5b5061056c61109e565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156105ac578082015181840152602081019050610591565b50505050905090810190601f1680156105d95780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156105f357600080fd5b50610632600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611140565b604051808215151515815260200191505060405180910390f35b34801561065857600080fd5b50610697600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611377565b604051808215151515815260200191505060405180910390f35b3480156106bd57600080fd5b506106c6611426565b005b3480156106d457600080fd5b50610729600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611456565b6040518082815260200191505060405180910390f35b34801561074b57600080fd5b50610780600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506114dd565b005b606060008054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561081a5780601f106107ef5761010080835404028352916020019161081a565b820191906000526020600020905b8154815290600101906020018083116107fd57829003601f168201915b5050505050905090565b61082c611046565b151561083757600080fd5b6001600660146101000a81548160ff021916908315150217905550565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415151561089157600080fd5b81600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b6000600554905090565b6000600660149054906101000a900460ff161515156109a957600080fd5b6109b384836114fc565b151515610a28576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260158152602001807f45524332303a204c6f636b65642062616c616e6365000000000000000000000081525060200191505060405180910390fd5b610a33848484611649565b90509392505050565b6000600260009054906101000a900460ff16905090565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614151515610a9057600080fd5b610b1f82600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546117fb90919063ffffffff16565b600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a36001905092915050565b610c92611046565b1515610c9d57600080fd5b8142101515610d3a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260318152602001807f4552433230203a2043757272656e742074696d6520697320677265617465722081526020017f7468616e2072656c656173652074696d6500000000000000000000000000000081525060400191505060405180910390fd5b60008114151515610db3576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260138152602001807f45524332303a20416d6f756e74206572726f720000000000000000000000000081525060200191505060405180910390fd5b81600760008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555080600860008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff167fac9f677e99a4df77ed2008bfe08de2e751aab75dce03486489e20585d79e91ce8383604051808381526020018281526020019250505060405180910390a2505050565b610e9e611046565b1515610ea957600080fd5b610eb333826114fc565b151515610f28576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260158152602001807f45524332303a204c6f636b65642062616c616e6365000000000000000000000081525060200191505060405180910390fd5b610f318161181c565b50565b600080600760008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054600860008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205491509150915091565b6000600360008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b600660149054906101000a900460ff1681565b6000600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b6000600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614905090565b606060018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156111365780601f1061110b57610100808354040283529160200191611136565b820191906000526020600020905b81548152906001019060200180831161111957829003601f168201915b5050505050905090565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415151561117d57600080fd5b61120c82600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461182990919063ffffffff16565b600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a36001905092915050565b6000600660149054906101000a900460ff1615151561139557600080fd5b61139f33836114fc565b151515611414576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260158152602001807f45524332303a204c6f636b65642062616c616e6365000000000000000000000081525060200191505060405180910390fd5b61141e838361184a565b905092915050565b61142e611046565b151561143957600080fd5b6000600660146101000a81548160ff021916908315150217905550565b6000600460008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b6114e5611046565b15156114f057600080fd5b6114f981611861565b50565b600080600860008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541415801561158b575042600760008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054115b80156116415750600860008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546115db84610fc0565b11158061164057508161163e600860008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461163086610fc0565b61182990919063ffffffff16565b105b5b905092915050565b6000600460008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482111515156116d657600080fd5b61176582600460008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461182990919063ffffffff16565b600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506117f084848461195d565b600190509392505050565b600080828401905083811015151561181257600080fd5b8091505092915050565b6118263382611b7b565b50565b60008083831115151561183b57600080fd5b82840390508091505092915050565b600061185733848461195d565b6001905092915050565b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161415151561189d57600080fd5b8073ffffffffffffffffffffffffffffffffffffffff16600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a380600660006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600360008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205481111515156119ab57600080fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16141515156119e757600080fd5b611a3981600360008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461182990919063ffffffff16565b600360008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550611ace81600360008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546117fb90919063ffffffff16565b600360008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b60008273ffffffffffffffffffffffffffffffffffffffff1614151515611ba157600080fd5b600360008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020548111151515611bef57600080fd5b611c048160055461182990919063ffffffff16565b600581905550611c5c81600360008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461182990919063ffffffff16565b600360008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a350505600a165627a7a72305820afb83e04f054a75a1dc1aad57f8a90980f225ba81f191972e257e85d2f8a3cd50029
{"success": true, "error": null, "results": {"detectors": [{"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
6
0x01b952402442630232f32d48380a557015b7c5ec
pragma solidity 0.7.4; enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, MODULO_BY_ZERO } 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); } } abstract contract AdminStorage { /** * @notice The address of the administrator account or contract. */ address public admin; } abstract contract BalanceSheetStorage { struct Vault { uint256 debt; uint256 freeCollateral; uint256 lockedCollateral; bool isOpen; } /** * @notice The unique Fintroller associated with this contract. */ FintrollerInterface public fintroller; /** * @dev One vault for each fyToken for each account. */ mapping(address => mapping(address => Vault)) internal vaults; /** * @notice Indicator that this is a BalanceSheet contract, for inspection. */ bool public constant isBalanceSheet = true; } abstract contract CarefulMath { /** * @notice Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @notice Add `a` and `b` and then subtract `c`. */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } /** * @notice Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @notice Returns the remainder of dividing two numbers. * @dev 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). */ function modUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.MODULO_BY_ZERO, 0); } return (MathError.NO_ERROR, a % b); } /** * @notice Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @notice Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } } abstract contract Erc20PermitStorage { /** * @notice The Eip712 domain's keccak256 hash. */ bytes32 public DOMAIN_SEPARATOR; /** * @notice keccak256("Permit(address owner,address spender,uint256 amount,uint256 nonce,uint256 deadline)"); */ bytes32 public constant PERMIT_TYPEHASH = 0xfc77c2b9d30fe91687fd39abb7d16fcdfe1472d065740051ab8b13e4bf4a617f; /** * @notice Provides replay protection. */ mapping(address => uint256) public nonces; /** * @notice Eip712 version of this implementation. */ string public constant version = "1"; } abstract contract Erc20RecoverStorage { /** * @notice The tokens that can be recovered cannot be in this mapping. */ Erc20Interface[] public nonRecoverableTokens; /** * @notice A flag that signals whether the the non-recoverable tokens were set or not. */ bool public isInitialized; } abstract contract Erc20Storage { /** * @notice Returns the number of decimals used to get its user representation. */ uint8 public decimals; /** * @notice Returns the name of the token. */ string public name; /** * @notice Returns the symbol of the token, usually a shorter version of * the name. */ string public symbol; /** * @notice Returns the amount of tokens in existence. */ uint256 public totalSupply; mapping(address => mapping(address => uint256)) internal allowances; mapping(address => uint256) internal balances; } abstract contract ExponentialStorage { struct Exp { uint256 mantissa; } /** * @dev In Exponential denomination, 1e18 is 1. */ uint256 internal constant expScale = 1e18; uint256 internal constant halfExpScale = expScale / 2; uint256 internal constant mantissaOne = expScale; } abstract contract FyTokenStorage { /** * STRUCTS */ struct Vault { uint256 debt; uint256 freeCollateral; uint256 lockedCollateral; bool isOpen; } /** * STORAGE PROPERTIES */ /** * @notice The global debt registry. */ BalanceSheetInterface public balanceSheet; /** * @notice The Erc20 asset that backs the borows of this fyToken. */ Erc20Interface public collateral; /** * @notice The ratio between mantissa precision (1e18) and the collateral precision. */ uint256 public collateralPrecisionScalar; /** * @notice Unix timestamp in seconds for when this token expires. */ uint256 public expirationTime; /** * @notice The unique Fintroller associated with this contract. */ FintrollerInterface public fintroller; /** * @notice The unique Redemption Pool associated with this contract. */ RedemptionPoolInterface public redemptionPool; /** * @notice The Erc20 underlying, or target, asset for this fyToken. */ Erc20Interface public underlying; /** * @notice The ratio between mantissa precision (1e18) and the underlying precision. */ uint256 public underlyingPrecisionScalar; /** * @notice Indicator that this is a FyToken contract, for inspection. */ bool public constant isFyToken = true; } abstract contract RedemptionPoolStorage { /** * @notice The unique Fintroller associated with this contract. */ FintrollerInterface public fintroller; /** * @notice The amount of the underyling asset available to be redeemed after maturation. */ uint256 public totalUnderlyingSupply; /** * The unique fyToken associated with this Redemption Pool. */ FyTokenInterface public fyToken; /** * @notice Indicator that this is a Redemption Pool contract, for inspection. */ bool public constant isRedemptionPool = true; } abstract contract ReentrancyGuard { bool private notEntered; /* * 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. */ constructor() { notEntered = true; } /** * @notice Prevents a contract from calling itself, directly or indirectly. * @dev 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, "ERR_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 Address for address; /** * INTERNAL FUNCTIONS */ function safeTransfer( Erc20Interface token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( Erc20Interface token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * PRIVATE FUNCTIONS */ /** * @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 cannot 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(Erc20Interface 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 = functionCallWithValue(address(token), data, "ERR_SAFE_ERC20_LOW_LEVEL_CALL"); if (returndata.length > 0) { /* Return data is optional. */ require(abi.decode(returndata, (bool)), "ERR_SAFE_ERC20_ERC20_OPERATION"); } } function functionCallWithValue( address target, bytes memory data, string memory errorMessage ) private returns (bytes memory) { require(target.isContract(), "ERR_SAFE_ERC20_CALL_TO_NON_CONTRACT"); /* solhint-disable-next-line avoid-low-level-calls */ (bool success, bytes memory returndata) = target.call(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 UniswapAnchoredViewInterface { /** * @notice Get the official price for a symbol. * @param symbol The symbol to fetch the price of. * @return Price denominated in USD, with 6 decimals. */ function price(string memory symbol) external view returns (uint256); } abstract contract AdminInterface is AdminStorage { /** * NON-CONSTANT FUNCTIONS */ function _renounceAdmin() external virtual; function _transferAdmin(address newAdmin) external virtual; /** * EVENTS */ event TransferAdmin(address indexed oldAdmin, address indexed newAdmin); } abstract contract BalanceSheetInterface is BalanceSheetStorage { /** * CONSTANT FUNCTIONS */ function getClutchableCollateral(FyTokenInterface fyToken, uint256 repayAmount) external view virtual returns (uint256); function getCurrentCollateralizationRatio(FyTokenInterface fyToken, address account) public view virtual returns (uint256); function getHypotheticalCollateralizationRatio( FyTokenInterface fyToken, address account, uint256 lockedCollateral, uint256 debt ) public view virtual returns (uint256); function getVault(FyTokenInterface fyToken, address account) external view virtual returns ( uint256, uint256, uint256, bool ); function getVaultDebt(FyTokenInterface fyToken, address account) external view virtual returns (uint256); function getVaultLockedCollateral(FyTokenInterface fyToken, address account) external view virtual returns (uint256); function isAccountUnderwater(FyTokenInterface fyToken, address account) external view virtual returns (bool); function isVaultOpen(FyTokenInterface fyToken, address account) external view virtual returns (bool); /** * NON-CONSTANT FUNCTIONS */ function clutchCollateral( FyTokenInterface fyToken, address liquidator, address borrower, uint256 clutchedCollateralAmount ) external virtual returns (bool); function depositCollateral(FyTokenInterface fyToken, uint256 collateralAmount) external virtual returns (bool); function freeCollateral(FyTokenInterface fyToken, uint256 collateralAmount) external virtual returns (bool); function lockCollateral(FyTokenInterface fyToken, uint256 collateralAmount) external virtual returns (bool); function openVault(FyTokenInterface fyToken) external virtual returns (bool); function setVaultDebt( FyTokenInterface fyToken, address account, uint256 newVaultDebt ) external virtual returns (bool); function withdrawCollateral(FyTokenInterface fyToken, uint256 collateralAmount) external virtual returns (bool); /** * EVENTS */ event ClutchCollateral( FyTokenInterface indexed fyToken, address indexed liquidator, address indexed borrower, uint256 clutchedCollateralAmount ); event DepositCollateral(FyTokenInterface indexed fyToken, address indexed account, uint256 collateralAmount); event FreeCollateral(FyTokenInterface indexed fyToken, address indexed account, uint256 collateralAmount); event LockCollateral(FyTokenInterface indexed fyToken, address indexed account, uint256 collateralAmount); event OpenVault(FyTokenInterface indexed fyToken, address indexed account); event SetVaultDebt(FyTokenInterface indexed fyToken, address indexed account, uint256 oldDebt, uint256 newDebt); event WithdrawCollateral(FyTokenInterface indexed fyToken, address indexed account, uint256 collateralAmount); } abstract contract Erc20Interface is Erc20Storage { /** * CONSTANT FUNCTIONS */ function allowance(address owner, address spender) external view virtual returns (uint256); function balanceOf(address account) external view virtual returns (uint256); /** * NON-CONSTANT FUNCTIONS */ function approve(address spender, uint256 amount) external virtual returns (bool); function transfer(address recipient, uint256 amount) external virtual returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external virtual returns (bool); /** * EVENTS */ event Approval(address indexed owner, address indexed spender, uint256 value); event Burn(address indexed account, uint256 burnAmount); event Mint(address indexed account, uint256 mintAmount); event Transfer(address indexed from, address indexed to, uint256 value); } abstract contract Erc20PermitInterface is Erc20PermitStorage { /** * NON-CONSTANT FUNCTIONS */ function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual; } abstract contract Erc20RecoverInterface is Erc20RecoverStorage { /** * NON-CONSTANT FUNCTIONS */ function _recover(Erc20Interface token, uint256 recoverAmount) external virtual; function _setNonRecoverableTokens(Erc20Interface[] calldata tokens) external virtual; /** * EVENTS */ event Recover(address indexed admin, Erc20Interface token, uint256 recoverAmount); event SetNonRecoverableTokens(address indexed admin, Erc20Interface[] nonRecoverableTokens); } abstract contract Exponential is CarefulMath, /* no dependency */ ExponentialStorage /* no dependency */ { /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({ mantissa: result })); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b. * NOTE: Returns an error if (`num` * 10e18) > MAX_INT, or if `denom` is zero. */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(a.mantissa, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, b.mantissa); if (err1 != MathError.NO_ERROR) { return (err1, Exp({ mantissa: 0 })); } return (MathError.NO_ERROR, Exp({ mantissa: rational })); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 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, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({ mantissa: 0 })); } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); /* The only possible error `div` is MathError.DIVISION_BY_ZERO but we control `expScale` and it's not zero. */ assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({ mantissa: product })); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure 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 Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({ mantissa: result })); } } abstract contract FintrollerStorage is Exponential { struct Bond { Exp collateralizationRatio; uint256 debtCeiling; bool isBorrowAllowed; bool isDepositCollateralAllowed; bool isLiquidateBorrowAllowed; bool isListed; bool isRedeemFyTokenAllowed; bool isRepayBorrowAllowed; bool isSupplyUnderlyingAllowed; } /** * @dev Maps the fyToken address to the Bond structs. */ mapping(FyTokenInterface => Bond) internal bonds; /** * @notice The contract that provides price data for the collateral and the underlying asset. */ UniswapAnchoredViewInterface public oracle; /** * @notice Multiplier representing the discount on collateral that a liquidator receives. */ uint256 public liquidationIncentiveMantissa; /** * @notice The ratio between mantissa precision (1e18) and the oracle price precision (1e6). */ uint256 public constant oraclePricePrecisionScalar = 1.0e12; /** * @dev The threshold below which the collateralization ratio cannot be set, equivalent to 100%. */ uint256 internal constant collateralizationRatioLowerBoundMantissa = 1.0e18; /** * @dev The threshold above which the collateralization ratio cannot be set, equivalent to 10,000%. */ uint256 internal constant collateralizationRatioUpperBoundMantissa = 1.0e20; /** * @dev The dafault collateralization ratio set when a new bond is listed, equivalent to 150%. */ uint256 internal constant defaultCollateralizationRatioMantissa = 1.5e18; /** * @dev The threshold below which the liquidation incentive cannot be set, equivalent to 100%. */ uint256 internal constant liquidationIncentiveLowerBoundMantissa = 1.0e18; /** * @dev The threshold above which the liquidation incentive cannot be set, equivalent to 150%. */ uint256 internal constant liquidationIncentiveUpperBoundMantissa = 1.5e18; /** * @notice Indicator that this is a Fintroller contract, for inspection. */ bool public constant isFintroller = true; } abstract contract FyTokenInterface is FyTokenStorage { /** * NON-CONSTANT FUNCTIONS */ function borrow(uint256 borrowAmount) external virtual returns (bool); function burn(address holder, uint256 burnAmount) external virtual returns (bool); function liquidateBorrow(address borrower, uint256 repayAmount) external virtual returns (bool); function mint(address beneficiary, uint256 borrowAmount) external virtual returns (bool); function repayBorrow(uint256 repayAmount) external virtual returns (bool); function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (bool); function _setFintroller(FintrollerInterface newFintroller) external virtual returns (bool); /** * EVENTS */ event Borrow(address indexed account, uint256 repayAmount); event LiquidateBorrow( address indexed liquidator, address indexed borrower, uint256 repayAmount, uint256 clutchedCollateralAmount ); event RepayBorrow(address indexed payer, address indexed borrower, uint256 repayAmount, uint256 newDebt); event SetFintroller(address indexed admin, FintrollerInterface oldFintroller, FintrollerInterface newFintroller); } abstract contract RedemptionPoolInterface is RedemptionPoolStorage { /** * NON-CONSTANT FUNCTIONS */ function redeemFyTokens(uint256 underlyingAmount) external virtual returns (bool); function supplyUnderlying(uint256 underlyingAmount) external virtual returns (bool); /** * EVENTS */ event RedeemFyTokens(address indexed account, uint256 fyTokenAmount, uint256 underlyingAmount); event SupplyUnderlying(address indexed account, uint256 underlyingAmount, uint256 fyTokenAmount); } abstract contract Admin is AdminInterface { /** * @notice Throws if called by any account other than the admin. */ modifier onlyAdmin() { require(admin == msg.sender, "ERR_NOT_ADMIN"); _; } /** * @notice Initializes the contract setting the deployer as the initial admin. */ constructor() { address msgSender = msg.sender; admin = msgSender; emit TransferAdmin(address(0x00), msgSender); } /** * @notice Leaves the contract without admin, so it will not be possible to call * `onlyAdmin` functions anymore. * * Requirements: * * - The caller must be the administrator. * * WARNING: Doing this will leave the contract without an admin, * thereby removing any functionality that is only available to the admin. */ function _renounceAdmin() external virtual override onlyAdmin { emit TransferAdmin(admin, address(0x00)); admin = address(0x00); } /** * @notice Transfers the admin of the contract to a new account (`newAdmin`). * Can only be called by the current admin. * @param newAdmin The acount of the new admin. */ function _transferAdmin(address newAdmin) external virtual override onlyAdmin { require(newAdmin != address(0x00), "ERR_SET_ADMIN_ZERO_ADDRESS"); emit TransferAdmin(admin, newAdmin); admin = newAdmin; } } contract Erc20 is CarefulMath, /* no dependency */ Erc20Interface /* one dependency */ { /** * @notice All three of these values are immutable: they can only be set once during construction. * @param name_ Erc20 name of this token. * @param symbol_ Erc20 symbol of this token. * @param decimals_ Erc20 decimal precision of this token. */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) { name = name_; symbol = symbol_; decimals = decimals_; } /** * CONSTANT FUNCTIONS */ /** * @notice 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 virtual override returns (uint256) { return allowances[owner][spender]; } /** * @notice Returns the amount of tokens owned by `account`. */ function balanceOf(address account) public view virtual override returns (uint256) { return balances[account]; } /** * NON-CONSTANT FUNCTIONS */ /** * @notice Sets `amount` as the allowance of `spender` over the caller's tokens. * * @dev 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. * * @return a boolean value indicating whether the operation succeeded. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external virtual override returns (bool) { approveInternal(msg.sender, spender, amount); return true; } /** * @notice Atomically decreases the allowance granted to `spender` by the caller. * * @dev This is an alternative to {approve} that can be used as a mitigation for * problems described in {Erc20Interface-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { MathError mathErr; uint256 newAllowance; (mathErr, newAllowance) = subUInt(allowances[msg.sender][spender], subtractedValue); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_DECREASE_ALLOWANCE_UNDERFLOW"); approveInternal(msg.sender, spender, newAllowance); return true; } /** * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an alternative to {approve} that can be used as a mitigation for * problems described above. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { MathError mathErr; uint256 newAllowance; (mathErr, newAllowance) = addUInt(allowances[msg.sender][spender], addedValue); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_INCREASE_ALLOWANCE_OVERFLOW"); approveInternal(msg.sender, spender, newAllowance); return true; } /** * @notice Moves `amount` tokens from the caller's account to `recipient`. * * @dev Emits a {Transfer} event. * * @return a boolean value indicating whether the operation succeeded. * * Requirements: * * - `recipient` cannot be the zero address. * - The caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external virtual override returns (bool) { transferInternal(msg.sender, recipient, amount); return true; } /** * @notice See Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * @dev Emits a {Transfer} event. Emits an {Approval} event indicating the * updated allowance. This is not required by the Erc. See the note at the * beginning of {Erc20}; * * @return a boolean value indicating whether the operation succeeded. * * 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 ) external virtual override returns (bool) { transferInternal(sender, recipient, amount); MathError mathErr; uint256 newAllowance; (mathErr, newAllowance) = subUInt(allowances[sender][msg.sender], amount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_TRANSFER_FROM_INSUFFICIENT_ALLOWANCE"); approveInternal(sender, msg.sender, newAllowance); return true; } /** * INTERNAL FUNCTIONS */ /** * @notice Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * @dev 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 approveInternal( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0x00), "ERR_ERC20_APPROVE_FROM_ZERO_ADDRESS"); require(spender != address(0x00), "ERR_ERC20_APPROVE_TO_ZERO_ADDRESS"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Destroys `burnAmount` tokens from `holder`, recuding the token supply. * * @dev Emits a {Burn} event. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `holder` must have at least `amount` tokens. */ function burnInternal(address holder, uint256 burnAmount) internal { MathError mathErr; uint256 newHolderBalance; uint256 newTotalSupply; /* Burn the yTokens. */ (mathErr, newHolderBalance) = subUInt(balances[holder], burnAmount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_BURN_BALANCE_UNDERFLOW"); balances[holder] = newHolderBalance; /* Reduce the total supply. */ (mathErr, newTotalSupply) = subUInt(totalSupply, burnAmount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_BURN_TOTAL_SUPPLY_UNDERFLOW"); totalSupply = newTotalSupply; emit Burn(holder, burnAmount); } /** @notice Prints new tokens into existence and assigns them to `beneficiary`, * increasing the total supply. * * @dev Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - The beneficiary's balance and the total supply cannot overflow. */ function mintInternal(address beneficiary, uint256 mintAmount) internal { MathError mathErr; uint256 newBeneficiaryBalance; uint256 newTotalSupply; /* Mint the yTokens. */ (mathErr, newBeneficiaryBalance) = addUInt(balances[beneficiary], mintAmount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_MINT_BALANCE_OVERFLOW"); balances[beneficiary] = newBeneficiaryBalance; /* Increase the total supply. */ (mathErr, newTotalSupply) = addUInt(totalSupply, mintAmount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_MINT_TOTAL_SUPPLY_OVERFLOW"); totalSupply = newTotalSupply; emit Mint(beneficiary, mintAmount); } /** * @notice Moves `amount` tokens from `sender` to `recipient`. * * @dev 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 transferInternal( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0x00), "ERR_ERC20_TRANSFER_FROM_ZERO_ADDRESS"); require(recipient != address(0x00), "ERR_ERC20_TRANSFER_TO_ZERO_ADDRESS"); MathError mathErr; uint256 newSenderBalance; uint256 newRecipientBalance; (mathErr, newSenderBalance) = subUInt(balances[sender], amount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_TRANSFER_SENDER_BALANCE_UNDERFLOW"); balances[sender] = newSenderBalance; (mathErr, newRecipientBalance) = addUInt(balances[recipient], amount); assert(mathErr == MathError.NO_ERROR); balances[recipient] = newRecipientBalance; emit Transfer(sender, recipient, amount); } } contract Erc20Permit is Erc20PermitInterface, /* one dependency */ Erc20 /* three dependencies */ { constructor( string memory name_, string memory symbol_, uint8 decimals_ ) Erc20(name_, symbol_, decimals_) { uint256 chainId; /* solhint-disable-next-line no-inline-assembly */ assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ) ); } /** * @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens, * assuming the latter's signed approval. * * IMPORTANT: The same issues Erc20 `approve` has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the Eip712-formatted function arguments. * - The signature must use `owner`'s current nonce. */ function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(owner != address(0x00), "ERR_ERC20_PERMIT_OWNER_ZERO_ADDRESS"); require(spender != address(0x00), "ERR_ERC20_PERMIT_SPENDER_ZERO_ADDRESS"); require(deadline >= block.timestamp, "ERR_ERC20_PERMIT_EXPIRED"); /* It's safe to use the "+" operator here because the nonce cannot realistically overflow, ever. */ bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashStruct)); address recoveredOwner = ecrecover(digest, v, r, s); require(recoveredOwner != address(0x00), "ERR_ERC20_PERMIT_RECOVERED_OWNER_ZERO_ADDRESS"); require(recoveredOwner == owner, "ERR_ERC20_PERMIT_INVALID_SIGNATURE"); approveInternal(owner, spender, amount); } } abstract contract Erc20Recover is Erc20RecoverInterface, /* one dependency */ Admin /* two dependencies */ { using SafeErc20 for Erc20Interface; /** * @notice Sets the tokens that this contract cannot recover. * * @dev Emits a {SetNonRecoverableTokens} event. * * Requirements: * * - The caller must be the administrator. * - The contract must be non-initialized. * - The array of given tokens cannot be empty. * * @param tokens The array of tokens to set as non-recoverable. */ function _setNonRecoverableTokens(Erc20Interface[] calldata tokens) external override onlyAdmin { /* Checks */ require(isInitialized == false, "ERR_INITALIZED"); /* Iterate over the token list, sanity check each and update the mapping. */ uint256 length = tokens.length; for (uint256 i = 0; i < length; i += 1) { tokens[i].symbol(); nonRecoverableTokens.push(tokens[i]); } /* Effects: prevent this function from ever being called again. */ isInitialized = true; emit SetNonRecoverableTokens(admin, tokens); } /** * @notice Recover Erc20 tokens sent to this contract (by accident or otherwise). * @dev Emits a {RecoverToken} event. * * Requirements: * * - The caller must be the administrator. * - The contract must be initialized. * - The amount to recover cannot be zero. * - The token to recover cannot be among the non-recoverable tokens. * * @param token The token to make the recover for. * @param recoverAmount The uint256 amount to recover, specified in the token's decimal system. */ function _recover(Erc20Interface token, uint256 recoverAmount) external override onlyAdmin { /* Checks */ require(isInitialized == true, "ERR_NOT_INITALIZED"); require(recoverAmount > 0, "ERR_RECOVER_ZERO"); bytes32 tokenSymbolHash = keccak256(bytes(token.symbol())); uint256 length = nonRecoverableTokens.length; /** * We iterate over the non-recoverable token array and check that: * * 1. The addresses of the tokens are not the same * 2. The symbols of the tokens are not the same * * It is true that the second check may lead to a false positive, but * there is no better way to fend off against proxied tokens. */ for (uint256 i = 0; i < length; i += 1) { require( address(token) != address(nonRecoverableTokens[i]) && tokenSymbolHash != keccak256(bytes(nonRecoverableTokens[i].symbol())), "ERR_RECOVER_NON_RECOVERABLE_TOKEN" ); } /* Interactions */ token.safeTransfer(admin, recoverAmount); emit Recover(admin, token, recoverAmount); } } abstract contract FintrollerInterface is FintrollerStorage { /** * CONSTANT FUNCTIONS */ function getBond(FyTokenInterface fyToken) external view virtual returns ( uint256 debtCeiling, uint256 collateralizationRatioMantissa, bool isBorrowAllowed, bool isDepositCollateralAllowed, bool isLiquidateBorrowAllowed, bool isListed, bool isRedeemFyTokenAllowed, bool isRepayBorrowAllowed, bool isSupplyUnderlyingAllowed ); function getBorrowAllowed(FyTokenInterface fyToken) external view virtual returns (bool); function getBondDebtCeiling(FyTokenInterface fyToken) external view virtual returns (uint256); function getBondCollateralizationRatio(FyTokenInterface fyToken) external view virtual returns (uint256); function getDepositCollateralAllowed(FyTokenInterface fyToken) external view virtual returns (bool); function getLiquidateBorrowAllowed(FyTokenInterface fyToken) external view virtual returns (bool); function getRedeemFyTokensAllowed(FyTokenInterface fyToken) external view virtual returns (bool); function getRepayBorrowAllowed(FyTokenInterface fyToken) external view virtual returns (bool); function getSupplyUnderlyingAllowed(FyTokenInterface fyToken) external view virtual returns (bool); /** * NON-CONSTANT FUNCTIONS */ function listBond(FyTokenInterface fyToken) external virtual returns (bool); function setBorrowAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); function setCollateralizationRatio(FyTokenInterface fyToken, uint256 newCollateralizationRatioMantissa) external virtual returns (bool); function setDebtCeiling(FyTokenInterface fyToken, uint256 newDebtCeiling) external virtual returns (bool); function setDepositCollateralAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); function setLiquidateBorrowAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); function setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external virtual returns (bool); function setOracle(UniswapAnchoredViewInterface newOracle) external virtual returns (bool); function setRedeemFyTokensAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); function setRepayBorrowAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); function setSupplyUnderlyingAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); /** * EVENTS */ event ListBond(address indexed admin, FyTokenInterface indexed fyToken); event SetBorrowAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); event SetCollateralizationRatio( address indexed admin, FyTokenInterface indexed fyToken, uint256 oldCollateralizationRatio, uint256 newCollateralizationRatio ); event SetDebtCeiling( address indexed admin, FyTokenInterface indexed fyToken, uint256 oldDebtCeiling, uint256 newDebtCeiling ); event SetDepositCollateralAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); event SetLiquidateBorrowAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); event SetLiquidationIncentive( address indexed admin, uint256 oldLiquidationIncentive, uint256 newLiquidationIncentive ); event SetRedeemFyTokensAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); event SetRepayBorrowAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); event SetOracle(address indexed admin, address oldOracle, address newOracle); event SetSupplyUnderlyingAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); } contract FyToken is ReentrancyGuard, /* no depedency */ FyTokenInterface, /* one dependency */ Admin, /* two dependencies */ Exponential, /* two dependencies */ Erc20, /* three dependencies */ Erc20Permit, /* five dependencies */ Erc20Recover /* five dependencies */ { modifier isVaultOpen(address account) { require(balanceSheet.isVaultOpen(this, account), "ERR_VAULT_NOT_OPEN"); _; } /** * @notice The fyToken always has 18 decimals. * @param name_ Erc20 name of this token. * @param symbol_ Erc20 symbol of this token. * @param expirationTime_ Unix timestamp in seconds for when this token expires. * @param fintroller_ The address of the Fintroller contract. * @param balanceSheet_ The address of the BalanceSheet contract. * @param underlying_ The contract address of the underlying asset. * @param collateral_ The contract address of the collateral asset. */ constructor( string memory name_, string memory symbol_, uint256 expirationTime_, FintrollerInterface fintroller_, BalanceSheetInterface balanceSheet_, Erc20Interface underlying_, Erc20Interface collateral_ ) Erc20Permit(name_, symbol_, 18) Admin() { uint8 defaultNumberOfDecimals = 18; /* Set the underlying contract and calculate the decimal scalar offsets. */ uint256 underlyingDecimals = underlying_.decimals(); require(underlyingDecimals > 0, "ERR_FYTOKEN_CONSTRUCTOR_UNDERLYING_DECIMALS_ZERO"); require(underlyingDecimals <= defaultNumberOfDecimals, "ERR_FYTOKEN_CONSTRUCTOR_UNDERLYING_DECIMALS_OVERFLOW"); underlyingPrecisionScalar = 10**(defaultNumberOfDecimals - underlyingDecimals); underlying = underlying_; /* Set the collateral contract and calculate the decimal scalar offsets. */ uint256 collateralDecimals = collateral_.decimals(); require(collateralDecimals > 0, "ERR_FYTOKEN_CONSTRUCTOR_COLLATERAL_DECIMALS_ZERO"); require(defaultNumberOfDecimals >= collateralDecimals, "ERR_FYTOKEN_CONSTRUCTOR_COLLATERAL_DECIMALS_OVERFLOW"); collateralPrecisionScalar = 10**(defaultNumberOfDecimals - collateralDecimals); collateral = collateral_; /* Set the unix expiration time. */ require(expirationTime_ > block.timestamp, "ERR_FYTOKEN_CONSTRUCTOR_EXPIRATION_TIME_NOT_VALID"); expirationTime = expirationTime_; /* Set the Fintroller contract and sanity check it. */ fintroller = fintroller_; fintroller.isFintroller(); /* Set the Balance Sheet contract and sanity check it. */ balanceSheet = balanceSheet_; balanceSheet.isBalanceSheet(); /* Create the Redemption Pool contract and transfer the owner from the fyToken itself to the current caller. */ redemptionPool = new RedemptionPool(fintroller_, this); AdminInterface(address(redemptionPool))._transferAdmin(msg.sender); } /** * NON-CONSTANT FUNCTIONS */ struct BorrowLocalVars { MathError mathErr; uint256 debt; uint256 debtCeiling; uint256 lockedCollateral; uint256 hypotheticalCollateralizationRatioMantissa; uint256 hypotheticalTotalSupply; uint256 newDebt; uint256 thresholdCollateralizationRatioMantissa; } /** * @notice Increases the debt of the caller and mints new fyToken. * * @dev Emits a {Borrow}, {Mint} and {Transfer} event. * * Requirements: * * - The vault must be open. * - Must be called prior to maturation. * - The amount to borrow cannot be zero. * - The Fintroller must allow this action to be performed. * - The locked collateral cannot be zero. * - The total supply of fyTokens cannot exceed the debt ceiling. * - The caller must not fall below the threshold collateralization ratio. * * @param borrowAmount The amount of fyTokens to borrow and print into existence. * @return bool true = success, otherwise it reverts. */ function borrow(uint256 borrowAmount) public override isVaultOpen(msg.sender) nonReentrant returns (bool) { BorrowLocalVars memory vars; /* Checks: bond not matured. */ require(isMatured() == false, "ERR_BOND_MATURED"); /* Checks: the zero edge case. */ require(borrowAmount > 0, "ERR_BORROW_ZERO"); /* Checks: the Fintroller allows this action to be performed. */ require(fintroller.getBorrowAllowed(this), "ERR_BORROW_NOT_ALLOWED"); /* Checks: debt ceiling. */ (vars.mathErr, vars.hypotheticalTotalSupply) = addUInt(totalSupply, borrowAmount); require(vars.mathErr == MathError.NO_ERROR, "ERR_BORROW_MATH_ERROR"); vars.debtCeiling = fintroller.getBondDebtCeiling(this); require(vars.hypotheticalTotalSupply <= vars.debtCeiling, "ERR_BORROW_DEBT_CEILING_OVERFLOW"); /* Add the borrow amount to the account's current debt. */ (vars.debt, , vars.lockedCollateral, ) = balanceSheet.getVault(this, msg.sender); require(vars.lockedCollateral > 0, "ERR_BORROW_LOCKED_COLLATERAL_ZERO"); (vars.mathErr, vars.newDebt) = addUInt(vars.debt, borrowAmount); require(vars.mathErr == MathError.NO_ERROR, "ERR_BORROW_MATH_ERROR"); /* Checks: the hypothetical collateralization ratio is above the threshold. */ vars.hypotheticalCollateralizationRatioMantissa = balanceSheet.getHypotheticalCollateralizationRatio( this, msg.sender, vars.lockedCollateral, vars.newDebt ); vars.thresholdCollateralizationRatioMantissa = fintroller.getBondCollateralizationRatio(this); require( vars.hypotheticalCollateralizationRatioMantissa >= vars.thresholdCollateralizationRatioMantissa, "ERR_BELOW_COLLATERALIZATION_RATIO" ); /* Effects: print the new fyTokens into existence. */ mintInternal(msg.sender, borrowAmount); /* Interactions: increase the debt of the account. */ require(balanceSheet.setVaultDebt(this, msg.sender, vars.newDebt), "ERR_BORROW_CALL_SET_VAULT_DEBT"); /* Emit a Borrow, Mint and Transfer event. */ emit Borrow(msg.sender, borrowAmount); emit Transfer(address(this), msg.sender, borrowAmount); return true; } /** * @notice Destroys `burnAmount` tokens from `holder`, reducing the token supply. * * @dev Emits a {Burn} event. * * Requirements: * * - Must be called prior to maturation. * - Can only be called by the Redemption Pool. * - The amount to burn cannot be zero. * * @param holder The account whose fyTokens to burn. * @param burnAmount The amount of fyTokens to burn. * @return bool true = success, otherwise it reverts. */ function burn(address holder, uint256 burnAmount) external override nonReentrant returns (bool) { /* Checks: the caller is the Redemption Pool. */ require(msg.sender == address(redemptionPool), "ERR_BURN_NOT_AUTHORIZED"); /* Checks: the zero edge case. */ require(burnAmount > 0, "ERR_BURN_ZERO"); /* Effects: burns the fyTokens. */ burnInternal(holder, burnAmount); return true; } struct LiquidateBorrowsLocalVars { MathError mathErr; uint256 collateralizationRatioMantissa; uint256 lockedCollateral; bool isAccountUnderwater; } /** * @notice Repays the debt of the borrower and rewards the liquidator with a surplus * of collateral. * * @dev Emits a {RepayBorrow}, {Transfer}, {ClutchCollateral} and {LiquidateBorrow} event. * * Requirements: * * - The vault must be open. * - The liquidator cannot liquidate themselves. * - The amount to repay cannot be zero. * - The Fintroller must allow this action to be performed. * - The borrower must be underwater if the bond didn't mature. * - The caller must have at least `repayAmount` fyTokens. * - The borrower must have at least `repayAmount` debt. * - The collateral clutch cannot be more than what the borrower has in the vault. * * @param borrower The account to liquidate. * @param repayAmount The amount of fyTokens to repay. * @return true = success, otherwise it reverts. */ function liquidateBorrow(address borrower, uint256 repayAmount) external override isVaultOpen(borrower) nonReentrant returns (bool) { LiquidateBorrowsLocalVars memory vars; /* Checks: borrowers cannot self liquidate. */ require(msg.sender != borrower, "ERR_LIQUIDATE_BORROW_SELF"); /* Checks: the zero edge case. */ require(repayAmount > 0, "ERR_LIQUIDATE_BORROW_ZERO"); /* Checks: the Fintroller allows this action to be performed. */ require(fintroller.getLiquidateBorrowAllowed(this), "ERR_LIQUIDATE_BORROW_NOT_ALLOWED"); /* After maturation, any vault can be liquidated, irrespective of collateralization ratio. */ if (isMatured() == false) { /* Checks: the borrower fell below the threshold collateraliation ratio. */ vars.isAccountUnderwater = balanceSheet.isAccountUnderwater(this, borrower); require(vars.isAccountUnderwater, "ERR_ACCOUNT_NOT_UNDERWATER"); } /* Effects & Interactions: repay the borrower's debt. */ repayBorrowInternal(msg.sender, borrower, repayAmount); /* Interactions: clutch the collateral. */ uint256 clutchableCollateralAmount = balanceSheet.getClutchableCollateral(this, repayAmount); require( balanceSheet.clutchCollateral(this, msg.sender, borrower, clutchableCollateralAmount), "ERR_LIQUIDATE_BORROW_CALL_CLUTCH_COLLATERAL" ); emit LiquidateBorrow(msg.sender, borrower, repayAmount, clutchableCollateralAmount); return true; } /** /** @notice Prints new tokens into existence and assigns them to `beneficiary`, * increasing the total supply. * * @dev Emits a {Mint} event. * * Requirements: * * - Can only be called by the Redemption Pool. * - The amount to mint cannot be zero. * * @param beneficiary The account for which to mint the tokens. * @param mintAmount The amount of fyTokens to print into existence. * @return bool true = success, otherwise it reverts. */ function mint(address beneficiary, uint256 mintAmount) external override nonReentrant returns (bool) { /* Checks: the caller is the Redemption Pool. */ require(msg.sender == address(redemptionPool), "ERR_MINT_NOT_AUTHORIZED"); /* Checks: the zero edge case. */ require(mintAmount > 0, "ERR_MINT_ZERO"); /* Effects: print the new fyTokens into existence. */ mintInternal(beneficiary, mintAmount); return true; } /** * @notice Deletes the account's debt from the registry and take the fyTokens out of circulation. * @dev Emits a {Burn}, {Transfer} and {RepayBorrow} event. * * Requirements: * * - The vault must be open. * - The amount to repay cannot be zero. * - The Fintroller must allow this action to be performed. * - The caller must have at least `repayAmount` fyTokens. * - The caller must have at least `repayAmount` debt. * * @param repayAmount Lorem ipsum. * @return true = success, otherwise it reverts. */ function repayBorrow(uint256 repayAmount) external override isVaultOpen(msg.sender) nonReentrant returns (bool) { repayBorrowInternal(msg.sender, msg.sender, repayAmount); return true; } /** * @notice Clears the borrower's debt from the registry and take the fyTokens out of circulation. * @dev Emits a {Burn}, {Transfer} and {RepayBorrow} event. * * Requirements: same as the `repayBorrow` function, but here `borrower` is the account that must * have at least `repayAmount` fyTokens to repay the borrow. * * @param borrower The account for which to repay the borrow. * @param repayAmount The amount of fyTokens to repay. * @return true = success, otherwise it reverts. */ function repayBorrowBehalf(address borrower, uint256 repayAmount) external override isVaultOpen(borrower) nonReentrant returns (bool) { repayBorrowInternal(msg.sender, borrower, repayAmount); return true; } /** * @notice Updates the Fintroller contract's address saved in storage. * * @dev Throws a {SetFintroller} event. * * Requirements: * * - The caller must be the administrator. * * @return bool true = success, otherwise it reverts. */ function _setFintroller(FintrollerInterface newFintroller) external override onlyAdmin returns (bool) { /* Checks: sanity check the new contract. */ newFintroller.isFintroller(); /* Effects: update storage. */ FintrollerInterface oldFintroller = fintroller; fintroller = newFintroller; emit SetFintroller(admin, oldFintroller, newFintroller); return true; } /** * INTERNAL FUNCTIONS */ /** * @dev Checks if the bond matured. */ function isMatured() internal view returns (bool) { return block.timestamp >= expirationTime; } /** * @dev See the documentation for the public functions that call this internal function. */ function repayBorrowInternal( address payer, address borrower, uint256 repayAmount ) internal { /* Checks: the zero edge case. */ require(repayAmount > 0, "ERR_REPAY_BORROW_ZERO"); /* Checks: the Fintroller allows this action to be performed. */ require(fintroller.getRepayBorrowAllowed(this), "ERR_REPAY_BORROW_NOT_ALLOWED"); /* Checks: borrower has a debt to pay. */ uint256 debt = balanceSheet.getVaultDebt(this, borrower); require(debt >= repayAmount, "ERR_REPAY_BORROW_INSUFFICIENT_DEBT"); /* Checks: the payer has enough fyTokens. */ require(balanceOf(payer) >= repayAmount, "ERR_REPAY_BORROW_INSUFFICIENT_BALANCE"); /* Effects: burn the fyTokens. */ burnInternal(payer, repayAmount); /* Calculate the new debt of the borrower. */ MathError mathErr; uint256 newDebt; (mathErr, newDebt) = subUInt(debt, repayAmount); /* This operation can't fail because of the previous `require`. */ assert(mathErr == MathError.NO_ERROR); /* Interactions: reduce the debt of the borrower . */ require(balanceSheet.setVaultDebt(this, borrower, newDebt), "ERR_REPAY_BORROW_CALL_SET_VAULT_DEBT"); /* Emit both a Transfer and a RepayBorrow event. */ emit Transfer(payer, address(this), repayAmount); emit RepayBorrow(payer, borrower, repayAmount, newDebt); } } contract RedemptionPool is CarefulMath, /* no dependency */ ReentrancyGuard, /* no dependency */ RedemptionPoolInterface, /* one dependency */ Admin, /* two dependencies */ Erc20Recover /* five dependencies */ { using SafeErc20 for Erc20Interface; /** * @param fintroller_ The address of the Fintroller contract. * @param fyToken_ The address of the fyToken contract. */ constructor(FintrollerInterface fintroller_, FyTokenInterface fyToken_) Admin() { /* Set the Fintroller contract and sanity check it. */ fintroller = fintroller_; fintroller.isFintroller(); /** * Set the fyToken contract. It cannot be sanity-checked because the fyToken creates this * contract in its own constructor and contracts cannot be called while initializing. */ fyToken = fyToken_; } struct RedeemFyTokensLocalVars { MathError mathErr; uint256 newUnderlyingTotalSupply; uint256 underlyingPrecisionScalar; uint256 underlyingAmount; } /** * @notice Pays the token holder the face value at maturation time. * * @dev Emits a {RedeemFyTokens} event. * * Requirements: * * - Must be called post maturation. * - The amount to redeem cannot be zero. * - The Fintroller must allow this action to be performed. * - There must be enough liquidity in the Redemption Pool. * * @param fyTokenAmount The amount of fyTokens to redeem for the underlying asset. * @return true = success, otherwise it reverts. */ function redeemFyTokens(uint256 fyTokenAmount) external override nonReentrant returns (bool) { RedeemFyTokensLocalVars memory vars; /* Checks: maturation time. */ require(block.timestamp >= fyToken.expirationTime(), "ERR_BOND_NOT_MATURED"); /* Checks: the zero edge case. */ require(fyTokenAmount > 0, "ERR_REDEEM_FYTOKENS_ZERO"); /* Checks: the Fintroller allows this action to be performed. */ require(fintroller.getRedeemFyTokensAllowed(fyToken), "ERR_REDEEM_FYTOKENS_NOT_ALLOWED"); /* Checks: there is enough liquidity. */ require(fyTokenAmount <= totalUnderlyingSupply, "ERR_REDEEM_FYTOKENS_INSUFFICIENT_UNDERLYING"); /** * fyTokens always have 18 decimals so the underlying amount needs to be downscaled. * If the precision scalar is 1, it means that the underlying also has 18 decimals. */ vars.underlyingPrecisionScalar = fyToken.underlyingPrecisionScalar(); if (vars.underlyingPrecisionScalar != 1) { (vars.mathErr, vars.underlyingAmount) = divUInt(fyTokenAmount, vars.underlyingPrecisionScalar); require(vars.mathErr == MathError.NO_ERROR, "ERR_REDEEM_FYTOKENS_MATH_ERROR"); } else { vars.underlyingAmount = fyTokenAmount; } /* Effects: decrease the remaining supply of underlying. */ (vars.mathErr, vars.newUnderlyingTotalSupply) = subUInt(totalUnderlyingSupply, vars.underlyingAmount); assert(vars.mathErr == MathError.NO_ERROR); totalUnderlyingSupply = vars.newUnderlyingTotalSupply; /* Interactions: burn the fyTokens. */ require(fyToken.burn(msg.sender, fyTokenAmount), "ERR_SUPPLY_UNDERLYING_CALL_BURN"); /* Interactions: perform the Erc20 transfer. */ fyToken.underlying().safeTransfer(msg.sender, vars.underlyingAmount); emit RedeemFyTokens(msg.sender, fyTokenAmount, vars.underlyingAmount); return true; } struct SupplyUnderlyingLocalVars { MathError mathErr; uint256 newUnderlyingTotalSupply; uint256 underlyingPrecisionScalar; uint256 fyTokenAmount; } /** * @notice An alternative to the usual minting method that does not involve taking on debt. * * @dev Emits a {SupplyUnderlying} event. * * Requirements: * * - Must be called prior to maturation. * - The amount to supply cannot be zero. * - The Fintroller must allow this action to be performed. * - The caller must have allowed this contract to spend `underlyingAmount` tokens. * * @param underlyingAmount The amount of underlying to supply to the Redemption Pool. * @return true = success, otherwise it reverts. */ function supplyUnderlying(uint256 underlyingAmount) external override nonReentrant returns (bool) { SupplyUnderlyingLocalVars memory vars; /* Checks: maturation time. */ require(block.timestamp < fyToken.expirationTime(), "ERR_BOND_MATURED"); /* Checks: the zero edge case. */ require(underlyingAmount > 0, "ERR_SUPPLY_UNDERLYING_ZERO"); /* Checks: the Fintroller allows this action to be performed. */ require(fintroller.getSupplyUnderlyingAllowed(fyToken), "ERR_SUPPLY_UNDERLYING_NOT_ALLOWED"); /* Effects: update storage. */ (vars.mathErr, vars.newUnderlyingTotalSupply) = addUInt(totalUnderlyingSupply, underlyingAmount); require(vars.mathErr == MathError.NO_ERROR, "ERR_SUPPLY_UNDERLYING_MATH_ERROR"); totalUnderlyingSupply = vars.newUnderlyingTotalSupply; /** * fyTokens always have 18 decimals so the underlying amount needs to be upscaled. * If the precision scalar is 1, it means that the underlying also has 18 decimals. */ vars.underlyingPrecisionScalar = fyToken.underlyingPrecisionScalar(); if (vars.underlyingPrecisionScalar != 1) { (vars.mathErr, vars.fyTokenAmount) = mulUInt(underlyingAmount, vars.underlyingPrecisionScalar); require(vars.mathErr == MathError.NO_ERROR, "ERR_SUPPLY_UNDERLYING_MATH_ERROR"); } else { vars.fyTokenAmount = underlyingAmount; } /* Interactions: mint the fyTokens. */ require(fyToken.mint(msg.sender, vars.fyTokenAmount), "ERR_SUPPLY_UNDERLYING_CALL_MINT"); /* Interactions: perform the Erc20 transfer. */ fyToken.underlying().safeTransferFrom(msg.sender, address(this), underlyingAmount); emit SupplyUnderlying(msg.sender, underlyingAmount, vars.fyTokenAmount); return true; } }
0x608060405234801561001057600080fd5b506004361061023d5760003560e01c80637c4950c71161013b578063cab364f1116100b8578063dde4bec01161007c578063dde4bec014610677578063e6abb5ae146106e5578063e6e0d75c1461070b578063ede4c0cc14610737578063f851a4401461073f5761023d565b8063cab364f1146105e0578063d505accf146105e8578063d8dfeb4514610639578063da284dcc14610641578063dd62ed3e146106495761023d565b8063a457c2d7116100ff578063a457c2d71461055b578063a9059cbb14610587578063b2bc5ef9146105b3578063bfa25308146105bb578063c5ebeaec146105c35761023d565b80637c4950c7146104dc5780637ecebe00146104e457806395d89b411461050a5780639dc29fac146105125780639e6ae5a01461053e5761023d565b80632608f818116101c9578063395093511161018d578063395093511461044e57806340c10f191461047a57806354fd4d50146104a65780636f307dc3146104ae57806370a08231146104b65761023d565b80632608f818146103ec57806330adf81f14610418578063313ce567146104205780633644e5151461043e578063392e53cd146104465761023d565b80631a0de6fa116102105780631a0de6fa146103365780631c2872aa1461033e5780631eabf00d1461036c57806322285cf61461039257806323b872dd146103b65761023d565b806306fdde0314610242578063095ea7b3146102bf5780630e752702146102ff57806318160ddd1461031c575b600080fd5b61024a610747565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561028457818101518382015260200161026c565b50505050905090810190601f1680156102b15780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102eb600480360360408110156102d557600080fd5b506001600160a01b0381351690602001356107d5565b604080519115158252519081900360200190f35b6102eb6004803603602081101561031557600080fd5b50356107eb565b61032461092e565b60408051918252519081900360200190f35b610324610934565b61036a6004803603604081101561035457600080fd5b506001600160a01b03813516906020013561093a565b005b6102eb6004803603602081101561038257600080fd5b50356001600160a01b0316610d9d565b61039a610ecb565b604080516001600160a01b039092168252519081900360200190f35b6102eb600480360360608110156103cc57600080fd5b506001600160a01b03813581169160208101359091169060400135610edf565b6102eb6004803603604081101561040257600080fd5b506001600160a01b038135169060200135610f84565b6103246110ca565b6104286110ee565b6040805160ff9092168252519081900360200190f35b6103246110fe565b6102eb611104565b6102eb6004803603604081101561046457600080fd5b506001600160a01b03813516906020013561110d565b6102eb6004803603604081101561049057600080fd5b506001600160a01b0381351690602001356111a4565b61024a6112bf565b61039a6112dc565b610324600480360360208110156104cc57600080fd5b50356001600160a01b03166112eb565b61039a611306565b610324600480360360208110156104fa57600080fd5b50356001600160a01b0316611315565b61024a611327565b6102eb6004803603604081101561052857600080fd5b506001600160a01b038135169060200135611382565b61039a6004803603602081101561055457600080fd5b5035611487565b6102eb6004803603604081101561057157600080fd5b506001600160a01b0381351690602001356114b1565b6102eb6004803603604081101561059d57600080fd5b506001600160a01b038135169060200135611532565b61032461153f565b61036a611545565b6102eb600480360360208110156105d957600080fd5b50356115e9565b6102eb611df5565b61036a600480360360e08110156105fe57600080fd5b506001600160a01b03813581169160208101359091169060408101359060608101359060ff6080820135169060a08101359060c00135611dfa565b61039a6120af565b6103246120be565b6103246004803603604081101561065f57600080fd5b506001600160a01b03813581169160200135166120c4565b61036a6004803603602081101561068d57600080fd5b810190602081018135600160201b8111156106a757600080fd5b8201836020820111156106b957600080fd5b803590602001918460208302840111600160201b831117156106da57600080fd5b5090925090506120ef565b61036a600480360360208110156106fb57600080fd5b50356001600160a01b03166123b6565b6102eb6004803603604081101561072157600080fd5b506001600160a01b0381351690602001356124cc565b61039a612a20565b61039a612a2f565b600c805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156107cd5780601f106107a2576101008083540402835291602001916107cd565b820191906000526020600020905b8154815290600101906020018083116107b057829003601f168201915b505050505081565b60006107e2338484612a43565b50600192915050565b6000805460408051632d3caa7360e21b815230600482015233602482018190529151919261010090046001600160a01b03169163b4f2a9cc91604480820192602092909190829003018186803b15801561084457600080fd5b505afa158015610858573d6000803e3d6000fd5b505050506040513d602081101561086e57600080fd5b50516108b6576040805162461bcd60e51b815260206004820152601260248201527122a9292fab20aaa62a2fa727aa2fa7a822a760711b604482015290519081900360640190fd5b60005460ff16610902576040805162461bcd60e51b815260206004820152601260248201527111549497d4915153951490539517d0d0531360721b604482015290519081900360640190fd5b6000805460ff19169055610917338085612b2f565b60019150506000805460ff19166001179055919050565b600e5481565b60075481565b600b5461010090046001600160a01b0316331461098e576040805162461bcd60e51b815260206004820152600d60248201526c22a9292fa727aa2fa0a226a4a760991b604482015290519081900360640190fd5b600b5460ff1615156001146109df576040805162461bcd60e51b815260206004820152601260248201527111549497d393d517d253925510531256915160721b604482015290519081900360640190fd5b60008111610a27576040805162461bcd60e51b815260206004820152601060248201526f4552525f5245434f5645525f5a45524f60801b604482015290519081900360640190fd5b6000826001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b158015610a6257600080fd5b505afa158015610a76573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526020811015610a9f57600080fd5b8101908080516040519392919084600160201b821115610abe57600080fd5b908301906020820185811115610ad357600080fd5b8251600160201b811182820188101715610aec57600080fd5b82525081516020918201929091019080838360005b83811015610b19578181015183820152602001610b01565b50505050905090810190601f168015610b465780820380516001836020036101000a031916815260200191505b506040525050508051906020012090506000600a80549050905060005b81811015610d2757600a8181548110610b7857fe5b6000918252602090912001546001600160a01b03868116911614801590610ce45750600a8181548110610ba757fe5b6000918252602082200154604080516395d89b4160e01b815290516001600160a01b03909216926395d89b4192600480840193829003018186803b158015610bee57600080fd5b505afa158015610c02573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526020811015610c2b57600080fd5b8101908080516040519392919084600160201b821115610c4a57600080fd5b908301906020820185811115610c5f57600080fd5b8251600160201b811182820188101715610c7857600080fd5b82525081516020918201929091019080838360005b83811015610ca5578181015183820152602001610c8d565b50505050905090810190601f168015610cd25780820380516001836020036101000a031916815260200191505b50604052505050805190602001208314155b610d1f5760405162461bcd60e51b81526004018080602001828103825260218152602001806137916021913960400191505060405180910390fd5b600101610b63565b50600b54610d47906001600160a01b038681169161010090041685612ee9565b600b54604080516001600160a01b03878116825260208201879052825161010090940416927ff6891c84a6c6af32a6d052172a8acc4c631b1d5057ffa2bc1da268b6938ea2da929181900390910190a250505050565b600b5460009061010090046001600160a01b03163314610df4576040805162461bcd60e51b815260206004820152600d60248201526c22a9292fa727aa2fa0a226a4a760991b604482015290519081900360640190fd5b816001600160a01b03166358f25c506040518163ffffffff1660e01b815260040160206040518083038186803b158015610e2d57600080fd5b505afa158015610e41573d6000803e3d6000fd5b505050506040513d6020811015610e5757600080fd5b5050600480546001600160a01b038481166001600160a01b031983168117909355600b546040805193831680855260208501959095528051610100909204909216927f05f5eff078a94c026377ab6c6bdc6d2ad1932a3e4971fd7473348af3609ec57a92908290030190a250600192915050565b60005461010090046001600160a01b031681565b6000610eec848484612f40565b6001600160a01b0384166000908152600f602090815260408083203384529091528120548190610f1c90856130e6565b90925090506000826004811115610f2f57fe5b14610f6b5760405162461bcd60e51b815260040180806020018281038252602e8152602001806137f7602e913960400191505060405180910390fd5b610f76863383612a43565b6001925050505b9392505050565b6000805460408051632d3caa7360e21b81523060048201526001600160a01b0386811660248301529151869361010090049092169163b4f2a9cc91604480820192602092909190829003018186803b158015610fdf57600080fd5b505afa158015610ff3573d6000803e3d6000fd5b505050506040513d602081101561100957600080fd5b5051611051576040805162461bcd60e51b815260206004820152601260248201527122a9292fab20aaa62a2fa727aa2fa7a822a760711b604482015290519081900360640190fd5b60005460ff1661109d576040805162461bcd60e51b815260206004820152601260248201527111549497d4915153951490539517d0d0531360721b604482015290519081900360640190fd5b6000805460ff191690556110b2338585612b2f565b60019150506000805460ff1916600117905592915050565b7ffc77c2b9d30fe91687fd39abb7d16fcdfe1472d065740051ab8b13e4bf4a617f81565b600b54600160a81b900460ff1681565b60085481565b600b5460ff1681565b336000908152600f602090815260408083206001600160a01b03861684529091528120548190819061113f908561310c565b9092509050600082600481111561115257fe5b1461118e5760405162461bcd60e51b81526004018080602001828103825260258152602001806138756025913960400191505060405180910390fd5b611199338683612a43565b506001949350505050565b6000805460ff166111f1576040805162461bcd60e51b815260206004820152601260248201527111549497d4915153951490539517d0d0531360721b604482015290519081900360640190fd5b6000805460ff191690556005546001600160a01b0316331461125a576040805162461bcd60e51b815260206004820152601760248201527f4552525f4d494e545f4e4f545f415554484f52495a4544000000000000000000604482015290519081900360640190fd5b6000821161129f576040805162461bcd60e51b815260206004820152600d60248201526c4552525f4d494e545f5a45524f60981b604482015290519081900360640190fd5b6112a98383613132565b5060016000805460ff1916600117905592915050565b604051806040016040528060018152602001603160f81b81525081565b6006546001600160a01b031681565b6001600160a01b031660009081526010602052604090205490565b6005546001600160a01b031681565b60096020526000908152604090205481565b600d805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156107cd5780601f106107a2576101008083540402835291602001916107cd565b6000805460ff166113cf576040805162461bcd60e51b815260206004820152601260248201527111549497d4915153951490539517d0d0531360721b604482015290519081900360640190fd5b6000805460ff191690556005546001600160a01b03163314611438576040805162461bcd60e51b815260206004820152601760248201527f4552525f4255524e5f4e4f545f415554484f52495a4544000000000000000000604482015290519081900360640190fd5b6000821161147d576040805162461bcd60e51b815260206004820152600d60248201526c4552525f4255524e5f5a45524f60981b604482015290519081900360640190fd5b6112a98383613280565b600a818154811061149757600080fd5b6000918252602090912001546001600160a01b0316905081565b336000908152600f602090815260408083206001600160a01b0386168452909152812054819081906114e390856130e6565b909250905060008260048111156114f657fe5b1461118e5760405162461bcd60e51b815260040180806020018281038252602681526020018061376b6026913960400191505060405180910390fd5b60006107e2338484612f40565b60025481565b600b5461010090046001600160a01b03163314611599576040805162461bcd60e51b815260206004820152600d60248201526c22a9292fa727aa2fa0a226a4a760991b604482015290519081900360640190fd5b600b5460405160009161010090046001600160a01b0316907fbdd36143ee09de60bdefca70680e0f71189b2ed7acee364b53917ad433fdaf80908390a3600b8054610100600160a81b0319169055565b6000805460408051632d3caa7360e21b815230600482015233602482018190529151919261010090046001600160a01b03169163b4f2a9cc91604480820192602092909190829003018186803b15801561164257600080fd5b505afa158015611656573d6000803e3d6000fd5b505050506040513d602081101561166c57600080fd5b50516116b4576040805162461bcd60e51b815260206004820152601260248201527122a9292fab20aaa62a2fa727aa2fa7a822a760711b604482015290519081900360640190fd5b60005460ff16611700576040805162461bcd60e51b815260206004820152601260248201527111549497d4915153951490539517d0d0531360721b604482015290519081900360640190fd5b6000805460ff19169055611712613664565b61171a6133ce565b1561175f576040805162461bcd60e51b815260206004820152601060248201526f11549497d093d39117d350551554915160821b604482015290519081900360640190fd5b600084116117a6576040805162461bcd60e51b815260206004820152600f60248201526e4552525f424f52524f575f5a45524f60881b604482015290519081900360640190fd5b60048054604080516381a7bc9760e01b81523093810193909352516001600160a01b03909116916381a7bc97916024808301926020929190829003018186803b1580156117f257600080fd5b505afa158015611806573d6000803e3d6000fd5b505050506040513d602081101561181c57600080fd5b5051611868576040805162461bcd60e51b815260206004820152601660248201527511549497d093d49493d5d7d393d517d0531313d5d15160521b604482015290519081900360640190fd5b611874600e548561310c565b60a083018190528282600481111561188857fe5b600481111561189357fe5b90525060009050815160048111156118a757fe5b146118f1576040805162461bcd60e51b815260206004820152601560248201527422a9292fa127a92927abafa6a0aa242fa2a92927a960591b604482015290519081900360640190fd5b600480546040805163d010b00f60e01b81523093810193909352516001600160a01b039091169163d010b00f916024808301926020929190829003018186803b15801561193d57600080fd5b505afa158015611951573d6000803e3d6000fd5b505050506040513d602081101561196757600080fd5b50516040820181905260a082015111156119c8576040805162461bcd60e51b815260206004820181905260248201527f4552525f424f52524f575f444542545f4345494c494e475f4f564552464c4f57604482015290519081900360640190fd5b6000546040805163bbd7edc560e01b815230600482015233602482015290516101009092046001600160a01b03169163bbd7edc591604480820192608092909190829003018186803b158015611a1d57600080fd5b505afa158015611a31573d6000803e3d6000fd5b505050506040513d6080811015611a4757600080fd5b508051604090910151606083018190526020830191909152611a9a5760405162461bcd60e51b81526004018080602001828103825260218152602001806139916021913960400191505060405180910390fd5b611aa881602001518561310c565b60c0830181905282826004811115611abc57fe5b6004811115611ac757fe5b9052506000905081516004811115611adb57fe5b14611b25576040805162461bcd60e51b815260206004820152601560248201527422a9292fa127a92927abafa6a0aa242fa2a92927a960591b604482015290519081900360640190fd5b600054606082015160c08301516040805163d8e51dfb60e01b815230600482015233602482015260448101939093526064830191909152516101009092046001600160a01b03169163d8e51dfb91608480820192602092909190829003018186803b158015611b9357600080fd5b505afa158015611ba7573d6000803e3d6000fd5b505050506040513d6020811015611bbd57600080fd5b50516080820152600480546040805163351da44160e21b81523093810193909352516001600160a01b039091169163d4769104916024808301926020929190829003018186803b158015611c1057600080fd5b505afa158015611c24573d6000803e3d6000fd5b505050506040513d6020811015611c3a57600080fd5b505160e0820181905260808201511015611c855760405162461bcd60e51b81526004018080602001828103825260218152602001806136f96021913960400191505060405180910390fd5b611c8f3385613132565b6000805460c083015160408051630b9d2cc360e41b81523060048201523360248201526044810192909252516101009092046001600160a01b03169263b9d2cc30926064808401936020939083900390910190829087803b158015611cf357600080fd5b505af1158015611d07573d6000803e3d6000fd5b505050506040513d6020811015611d1d57600080fd5b5051611d70576040805162461bcd60e51b815260206004820152601e60248201527f4552525f424f52524f575f43414c4c5f5345545f5641554c545f444542540000604482015290519081900360640190fd5b60408051858152905133917fcbc04eca7e9da35cb1393a6135a199ca52e450d5e9251cbd99f7847d33a36750919081900360200190a2604080518581529051339130917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a36001925050506000805460ff19166001179055919050565b600181565b6001600160a01b038716611e3f5760405162461bcd60e51b81526004018080602001828103825260238152602001806136d66023913960400191505060405180910390fd5b6001600160a01b038616611e845760405162461bcd60e51b81526004018080602001828103825260258152602001806138e16025913960400191505060405180910390fd5b42841015611ed9576040805162461bcd60e51b815260206004820152601860248201527f4552525f45524332305f5045524d49545f455850495245440000000000000000604482015290519081900360640190fd5b6001600160a01b0380881660008181526009602090815260408083208054600180820190925582517ffc77c2b9d30fe91687fd39abb7d16fcdfe1472d065740051ab8b13e4bf4a617f8186015280840196909652958c166060860152608085018b905260a085019590955260c08085018a90528151808603909101815260e08501825280519083012060085461190160f01b61010087015261010286015261012280860182905282518087039091018152610142860180845281519185019190912090859052610162860180845281905260ff8a166101828701526101a286018990526101c2860188905291519095919491926101e2808401939192601f1981019281900390910190855afa158015611ff6573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166120485760405162461bcd60e51b815260040180806020018281038252602d81526020018061373e602d913960400191505060405180910390fd5b896001600160a01b0316816001600160a01b0316146120985760405162461bcd60e51b815260040180806020018281038252602281526020018061394d6022913960400191505060405180910390fd5b6120a38a8a8a612a43565b50505050505050505050565b6001546001600160a01b031681565b60035481565b6001600160a01b039182166000908152600f6020908152604080832093909416825291909152205490565b600b5461010090046001600160a01b03163314612143576040805162461bcd60e51b815260206004820152600d60248201526c22a9292fa727aa2fa0a226a4a760991b604482015290519081900360640190fd5b600b5460ff161561218c576040805162461bcd60e51b815260206004820152600e60248201526d11549497d253925510531256915160921b604482015290519081900360640190fd5b8060005b81811015612329578383828181106121a457fe5b905060200201356001600160a01b03166001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b1580156121ec57600080fd5b505afa158015612200573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052602081101561222957600080fd5b8101908080516040519392919084600160201b82111561224857600080fd5b90830190602082018581111561225d57600080fd5b8251600160201b81118282018810171561227657600080fd5b82525081516020918201929091019080838360005b838110156122a357818101518382015260200161228b565b50505050905090810190601f1680156122d05780820380516001836020036101000a031916815260200191505b5060405250505050600a8484838181106122e657fe5b835460018181018655600095865260209586902090910180546001600160a01b0319166001600160a01b0396909302949094013594909416179091555001612190565b50600b8054600160ff1990911617908190556040805160208082528082018690526101009093046001600160a01b0316927fd877543bef27da9036243421e623413c8fdd78d7d183cc93d8f3cddbd657a2ed928792879290918291908201908590850280828437600083820152604051601f909101601f19169092018290039550909350505050a2505050565b600b5461010090046001600160a01b0316331461240a576040805162461bcd60e51b815260206004820152600d60248201526c22a9292fa727aa2fa0a226a4a760991b604482015290519081900360640190fd5b6001600160a01b038116612465576040805162461bcd60e51b815260206004820152601a60248201527f4552525f5345545f41444d494e5f5a45524f5f41444452455353000000000000604482015290519081900360640190fd5b600b546040516001600160a01b0380841692610100900416907fbdd36143ee09de60bdefca70680e0f71189b2ed7acee364b53917ad433fdaf8090600090a3600b80546001600160a01b0390921661010002610100600160a81b0319909216919091179055565b6000805460408051632d3caa7360e21b81523060048201526001600160a01b0386811660248301529151869361010090049092169163b4f2a9cc91604480820192602092909190829003018186803b15801561252757600080fd5b505afa15801561253b573d6000803e3d6000fd5b505050506040513d602081101561255157600080fd5b5051612599576040805162461bcd60e51b815260206004820152601260248201527122a9292fab20aaa62a2fa727aa2fa7a822a760711b604482015290519081900360640190fd5b60005460ff166125e5576040805162461bcd60e51b815260206004820152601260248201527111549497d4915153951490539517d0d0531360721b604482015290519081900360640190fd5b6000805460ff191690556125f76136aa565b336001600160a01b0386161415612655576040805162461bcd60e51b815260206004820152601960248201527f4552525f4c49515549444154455f424f52524f575f53454c4600000000000000604482015290519081900360640190fd5b600084116126aa576040805162461bcd60e51b815260206004820152601960248201527f4552525f4c49515549444154455f424f52524f575f5a45524f00000000000000604482015290519081900360640190fd5b6004805460408051632ec8fffb60e21b81523093810193909352516001600160a01b039091169163bb23ffec916024808301926020929190829003018186803b1580156126f657600080fd5b505afa15801561270a573d6000803e3d6000fd5b505050506040513d602081101561272057600080fd5b5051612773576040805162461bcd60e51b815260206004820181905260248201527f4552525f4c49515549444154455f424f52524f575f4e4f545f414c4c4f574544604482015290519081900360640190fd5b61277b6133ce565b61285e5760005460408051639ee91d1f60e01b81523060048201526001600160a01b038881166024830152915161010090930490911691639ee91d1f91604480820192602092909190829003018186803b1580156127d857600080fd5b505afa1580156127ec573d6000803e3d6000fd5b505050506040513d602081101561280257600080fd5b505115156060820181905261285e576040805162461bcd60e51b815260206004820152601a60248201527f4552525f4143434f554e545f4e4f545f554e4445525741544552000000000000604482015290519081900360640190fd5b612869338686612b2f565b600080546040805163464b048560e01b81523060048201526024810188905290516101009092046001600160a01b03169163464b048591604480820192602092909190829003018186803b1580156128c057600080fd5b505afa1580156128d4573d6000803e3d6000fd5b505050506040513d60208110156128ea57600080fd5b50516000805460408051630e496ef360e01b81523060048201523360248201526001600160a01b038b811660448301526064820186905291519495506101009092041692630e496ef392608480840193602093929083900390910190829087803b15801561295757600080fd5b505af115801561296b573d6000803e3d6000fd5b505050506040513d602081101561298157600080fd5b50516129be5760405162461bcd60e51b815260040180806020018281038252602b815260200180613825602b913960400191505060405180910390fd5b604080518681526020810183905281516001600160a01b0389169233927f08b197b6ae66d18ee6fa20a826a84579a925b9e646a3bf19e96f59ed568c2688929081900390910190a3600193505050506000805460ff1916600117905592915050565b6004546001600160a01b031681565b600b5461010090046001600160a01b031681565b6001600160a01b038316612a885760405162461bcd60e51b81526004018080602001828103825260238152602001806139dd6023913960400191505060405180910390fd5b6001600160a01b038216612acd5760405162461bcd60e51b81526004018080602001828103825260218152602001806137b26021913960400191505060405180910390fd5b6001600160a01b038084166000818152600f6020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b60008111612b7c576040805162461bcd60e51b81526020600482015260156024820152744552525f52455041595f424f52524f575f5a45524f60581b604482015290519081900360640190fd5b600480546040805163e60f077360e01b81523093810193909352516001600160a01b039091169163e60f0773916024808301926020929190829003018186803b158015612bc857600080fd5b505afa158015612bdc573d6000803e3d6000fd5b505050506040513d6020811015612bf257600080fd5b5051612c45576040805162461bcd60e51b815260206004820152601c60248201527f4552525f52455041595f424f52524f575f4e4f545f414c4c4f57454400000000604482015290519081900360640190fd5b6000805460408051638a0695fd60e01b81523060048201526001600160a01b038681166024830152915161010090930490911691638a0695fd91604480820192602092909190829003018186803b158015612c9f57600080fd5b505afa158015612cb3573d6000803e3d6000fd5b505050506040513d6020811015612cc957600080fd5b5051905081811015612d0c5760405162461bcd60e51b81526004018080602001828103825260228152602001806138bf6022913960400191505060405180910390fd5b81612d16856112eb565b1015612d535760405162461bcd60e51b815260040180806020018281038252602581526020018061389a6025913960400191505060405180910390fd5b612d5d8483613280565b600080612d6a83856130e6565b90925090506000826004811115612d7d57fe5b14612d8457fe5b6000805460408051630b9d2cc360e41b81523060048201526001600160a01b0389811660248301526044820186905291516101009093049091169263b9d2cc30926064808401936020939083900390910190829087803b158015612de757600080fd5b505af1158015612dfb573d6000803e3d6000fd5b505050506040513d6020811015612e1157600080fd5b5051612e4e5760405162461bcd60e51b81526004018080602001828103825260248152602001806139066024913960400191505060405180910390fd5b60408051858152905130916001600160a01b038916917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a3846001600160a01b0316866001600160a01b03167fa9a154237a69922f8860321d1fec1624a5dbe8a8af89a3dd3d7a759f6c8080d88684604051808381526020018281526020019250505060405180910390a3505050505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052612f3b9084906133d7565b505050565b6001600160a01b038316612f855760405162461bcd60e51b81526004018080602001828103825260248152602001806137d36024913960400191505060405180910390fd5b6001600160a01b038216612fca5760405162461bcd60e51b815260040180806020018281038252602281526020018061396f6022913960400191505060405180910390fd5b6001600160a01b03831660009081526010602052604081205481908190612ff190856130e6565b9093509150600083600481111561300457fe5b146130405760405162461bcd60e51b815260040180806020018281038252602b8152602001806139b2602b913960400191505060405180910390fd5b6001600160a01b038087166000908152601060205260408082208590559187168152205461306e908561310c565b9093509050600083600481111561308157fe5b1461308857fe5b6001600160a01b038086166000818152601060209081526040918290208590558151888152915192938a16927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a3505050505050565b6000808383116130fd575060009050818303613105565b506003905060005b9250929050565b60008083830184811061312457600092509050613105565b600260009250925050613105565b6001600160a01b03821660009081526010602052604081205481908190613159908561310c565b9093509150600083600481111561316c57fe5b146131be576040805162461bcd60e51b815260206004820152601f60248201527f4552525f45524332305f4d494e545f42414c414e43455f4f564552464c4f5700604482015290519081900360640190fd5b6001600160a01b0385166000908152601060205260409020829055600e546131e6908561310c565b909350905060008360048111156131f957fe5b146132355760405162461bcd60e51b815260040180806020018281038252602481526020018061371a6024913960400191505060405180910390fd5b600e8190556040805185815290516001600160a01b038716917f0f6798a560793a54c3bcfe86a93cde1e73087d944c0ea20544137d4121396885919081900360200190a25050505050565b6001600160a01b038216600090815260106020526040812054819081906132a790856130e6565b909350915060008360048111156132ba57fe5b1461330c576040805162461bcd60e51b815260206004820181905260248201527f4552525f45524332305f4255524e5f42414c414e43455f554e444552464c4f57604482015290519081900360640190fd5b6001600160a01b0385166000908152601060205260409020829055600e5461333490856130e6565b9093509050600083600481111561334757fe5b146133835760405162461bcd60e51b81526004018080602001828103825260258152602001806138506025913960400191505060405180910390fd5b600e8190556040805185815290516001600160a01b038716917fcc16f5dbb4873280815c1ee09dbd06736cffcc184412cf7a71a0fdb75d397ca5919081900360200190a25050505050565b60035442101590565b606061341983836040518060400160405280601d81526020017f4552525f534146455f45524332305f4c4f575f4c4556454c5f43414c4c00000081525061348b565b805190915015612f3b5780806020019051602081101561343857600080fd5b5051612f3b576040805162461bcd60e51b815260206004820152601e60248201527f4552525f534146455f45524332305f45524332305f4f5045524154494f4e0000604482015290519081900360640190fd5b606061349f846001600160a01b0316613628565b6134da5760405162461bcd60e51b815260040180806020018281038252602381526020018061392a6023913960400191505060405180910390fd5b60006060856001600160a01b0316856040518082805190602001908083835b602083106135185780518252601f1990920191602091820191016134f9565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d806000811461357a576040519150601f19603f3d011682016040523d82523d6000602084013e61357f565b606091505b50915091508115613593579150610f7d9050565b8051156135a35780518082602001fd5b8360405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156135ed5781810151838201526020016135d5565b50505050905090810190601f16801561361a5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47081811480159061365c57508115155b949350505050565b6040805161010081019091528060008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b604080516080810190915280600081526020016000815260200160008152602001600015158152509056fe4552525f45524332305f5045524d49545f4f574e45525f5a45524f5f414444524553534552525f42454c4f575f434f4c4c41544552414c495a4154494f4e5f524154494f4552525f45524332305f4d494e545f544f54414c5f535550504c595f4f564552464c4f574552525f45524332305f5045524d49545f5245434f56455245445f4f574e45525f5a45524f5f414444524553534552525f45524332305f44454352454153455f414c4c4f57414e43455f554e444552464c4f574552525f5245434f5645525f4e4f4e5f5245434f56455241424c455f544f4b454e4552525f45524332305f415050524f56455f544f5f5a45524f5f414444524553534552525f45524332305f5452414e534645525f46524f4d5f5a45524f5f414444524553534552525f45524332305f5452414e534645525f46524f4d5f494e53554646494349454e545f414c4c4f57414e43454552525f4c49515549444154455f424f52524f575f43414c4c5f434c555443485f434f4c4c41544552414c4552525f45524332305f4255524e5f544f54414c5f535550504c595f554e444552464c4f574552525f45524332305f494e4352454153455f414c4c4f57414e43455f4f564552464c4f574552525f52455041595f424f52524f575f494e53554646494349454e545f42414c414e43454552525f52455041595f424f52524f575f494e53554646494349454e545f444542544552525f45524332305f5045524d49545f5350454e4445525f5a45524f5f414444524553534552525f52455041595f424f52524f575f43414c4c5f5345545f5641554c545f444542544552525f534146455f45524332305f43414c4c5f544f5f4e4f4e5f434f4e54524143544552525f45524332305f5045524d49545f494e56414c49445f5349474e41545552454552525f45524332305f5452414e534645525f544f5f5a45524f5f414444524553534552525f424f52524f575f4c4f434b45445f434f4c4c41544552414c5f5a45524f4552525f45524332305f5452414e534645525f53454e4445525f42414c414e43455f554e444552464c4f574552525f45524332305f415050524f56455f46524f4d5f5a45524f5f41444452455353a264697066735822122058972d031ceb296730968d1195213dc7aa6ffe2ae0cfc04b1ae1348e0647923464736f6c63430007040033
{"success": true, "error": null, "results": {"detectors": [{"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}]}
7
0x0258f474786ddfd37abce6df6bbb1dd5dfc4434a
pragma solidity 0.5.10; 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 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 MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } 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 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 ERC20Mintable is ERC20, MinterRole { /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } contract ERC20Capped is ERC20Mintable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See {ERC20Mintable-mint}. * * Requirements: * * - `value` must not cause the total supply to go over the cap. */ function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded"); super._mint(account, value); } } contract OrionToken is ERC20Detailed, ERC20Capped { constructor() public ERC20Detailed("Orion Protocol", "ORN", 8) ERC20Capped(100e6 * 1e8) {} }
0x608060405234801561001057600080fd5b50600436106101005760003560e01c806370a0823111610097578063a457c2d711610066578063a457c2d7146102ee578063a9059cbb1461031a578063aa271e1a14610346578063dd62ed3e1461036c57610100565b806370a082311461029057806395d89b41146102b6578063983b2d56146102be57806398650275146102e657610100565b8063313ce567116100d3578063313ce56714610212578063355274ea14610230578063395093511461023857806340c10f191461026457610100565b806306fdde0314610105578063095ea7b31461018257806318160ddd146101c257806323b872dd146101dc575b600080fd5b61010d61039a565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561014757818101518382015260200161012f565b50505050905090810190601f1680156101745780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101ae6004803603604081101561019857600080fd5b506001600160a01b038135169060200135610430565b604080519115158252519081900360200190f35b6101ca61044d565b60408051918252519081900360200190f35b6101ae600480360360608110156101f257600080fd5b506001600160a01b03813581169160208101359091169060400135610453565b61021a6104e0565b6040805160ff9092168252519081900360200190f35b6101ca6104e9565b6101ae6004803603604081101561024e57600080fd5b506001600160a01b0381351690602001356104ef565b6101ae6004803603604081101561027a57600080fd5b506001600160a01b038135169060200135610543565b6101ca600480360360208110156102a657600080fd5b50356001600160a01b031661059a565b61010d6105b5565b6102e4600480360360208110156102d457600080fd5b50356001600160a01b0316610615565b005b6102e4610667565b6101ae6004803603604081101561030457600080fd5b506001600160a01b038135169060200135610679565b6101ae6004803603604081101561033057600080fd5b506001600160a01b0381351690602001356106e7565b6101ae6004803603602081101561035c57600080fd5b50356001600160a01b03166106fb565b6101ca6004803603604081101561038257600080fd5b506001600160a01b0381358116916020013516610714565b60008054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104265780601f106103fb57610100808354040283529160200191610426565b820191906000526020600020905b81548152906001019060200180831161040957829003601f168201915b5050505050905090565b600061044461043d61073f565b8484610743565b50600192915050565b60055490565b600061046084848461082f565b6104d68461046c61073f565b6104d185604051806060016040528060288152602001610e8f602891396001600160a01b038a166000908152600460205260408120906104aa61073f565b6001600160a01b03168152602081019190915260400160002054919063ffffffff61098d16565b610743565b5060019392505050565b60025460ff1690565b60075490565b60006104446104fc61073f565b846104d1856004600061050d61073f565b6001600160a01b03908116825260208083019390935260409182016000908120918c16815292529020549063ffffffff610a2416565b600061055561055061073f565b6106fb565b6105905760405162461bcd60e51b8152600401808060200182810382526030815260200180610e3e6030913960400191505060405180910390fd5b6104448383610a85565b6001600160a01b031660009081526003602052604090205490565b60018054604080516020601f600260001961010087891615020190951694909404938401819004810282018101909252828152606093909290918301828280156104265780601f106103fb57610100808354040283529160200191610426565b61062061055061073f565b61065b5760405162461bcd60e51b8152600401808060200182810382526030815260200180610e3e6030913960400191505060405180910390fd5b61066481610b01565b50565b61067761067261073f565b610b49565b565b600061044461068661073f565b846104d185604051806060016040528060258152602001610f2260259139600460006106b061073f565b6001600160a01b03908116825260208083019390935260409182016000908120918d1681529252902054919063ffffffff61098d16565b60006104446106f461073f565b848461082f565b600061070e60068363ffffffff610b9116565b92915050565b6001600160a01b03918216600090815260046020908152604080832093909416825291909152205490565b3390565b6001600160a01b0383166107885760405162461bcd60e51b8152600401808060200182810382526024815260200180610efe6024913960400191505060405180910390fd5b6001600160a01b0382166107cd5760405162461bcd60e51b8152600401808060200182810382526022815260200180610df66022913960400191505060405180910390fd5b6001600160a01b03808416600081815260046020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b0383166108745760405162461bcd60e51b8152600401808060200182810382526025815260200180610ed96025913960400191505060405180910390fd5b6001600160a01b0382166108b95760405162461bcd60e51b8152600401808060200182810382526023815260200180610dd36023913960400191505060405180910390fd5b6108fc81604051806060016040528060268152602001610e18602691396001600160a01b038616600090815260036020526040902054919063ffffffff61098d16565b6001600160a01b038085166000908152600360205260408082209390935590841681522054610931908263ffffffff610a2416565b6001600160a01b0380841660008181526003602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b60008184841115610a1c5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156109e15781810151838201526020016109c9565b50505050905090810190601f168015610a0e5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b600082820183811015610a7e576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b600754610aa082610a9461044d565b9063ffffffff610a2416565b1115610af3576040805162461bcd60e51b815260206004820152601960248201527f45524332304361707065643a2063617020657863656564656400000000000000604482015290519081900360640190fd5b610afd8282610bf8565b5050565b610b1260068263ffffffff610cea16565b6040516001600160a01b038216907f6ae172837ea30b801fbfcdd4108aa1d5bf8ff775444fd70256b44e6bf3dfc3f690600090a250565b610b5a60068263ffffffff610d6b16565b6040516001600160a01b038216907fe94479a9f7e1952cc78f2d6baab678adc1b772d936c6583def489e524cb6669290600090a250565b60006001600160a01b038216610bd85760405162461bcd60e51b8152600401808060200182810382526022815260200180610eb76022913960400191505060405180910390fd5b506001600160a01b03166000908152602091909152604090205460ff1690565b6001600160a01b038216610c53576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015290519081900360640190fd5b600554610c66908263ffffffff610a2416565b6005556001600160a01b038216600090815260036020526040902054610c92908263ffffffff610a2416565b6001600160a01b03831660008181526003602090815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b610cf48282610b91565b15610d46576040805162461bcd60e51b815260206004820152601f60248201527f526f6c65733a206163636f756e7420616c72656164792068617320726f6c6500604482015290519081900360640190fd5b6001600160a01b0316600090815260209190915260409020805460ff19166001179055565b610d758282610b91565b610db05760405162461bcd60e51b8152600401808060200182810382526021815260200180610e6e6021913960400191505060405180910390fd5b6001600160a01b0316600090815260209190915260409020805460ff1916905556fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e63654d696e746572526f6c653a2063616c6c657220646f6573206e6f74206861766520746865204d696e74657220726f6c65526f6c65733a206163636f756e7420646f6573206e6f74206861766520726f6c6545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e6365526f6c65733a206163636f756e7420697320746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa265627a7a72305820f80ab6aa2644f388569754795385a72725551b422d66a049549c8f8b8756ed1364736f6c634300050a0032
{"success": true, "error": null, "results": {}}
true
null
{}
8
0x0263e1dcfcaaad8fd4e840fe4b22854485a561f0
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 BitlesToken is ERC20 { constructor () public ERC20("Bitles Token", "BTL") { _setupDecimals(6); _mint(msg.sender, 88895678 * (10 ** uint256(decimals()))); } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c80633950935111610071578063395093511461025f57806370a08231146102c557806395d89b411461031d578063a457c2d7146103a0578063a9059cbb14610406578063dd62ed3e1461046c576100a9565b806306fdde03146100ae578063095ea7b31461013157806318160ddd1461019757806323b872dd146101b5578063313ce5671461023b575b600080fd5b6100b66104e4565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f65780820151818401526020810190506100db565b50505050905090810190601f1680156101235780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61017d6004803603604081101561014757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610586565b604051808215151515815260200191505060405180910390f35b61019f6105a4565b6040518082815260200191505060405180910390f35b610221600480360360608110156101cb57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506105ae565b604051808215151515815260200191505060405180910390f35b610243610687565b604051808260ff1660ff16815260200191505060405180910390f35b6102ab6004803603604081101561027557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061069e565b604051808215151515815260200191505060405180910390f35b610307600480360360208110156102db57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610751565b6040518082815260200191505060405180910390f35b610325610799565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561036557808201518184015260208101905061034a565b50505050905090810190601f1680156103925780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6103ec600480360360408110156103b657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061083b565b604051808215151515815260200191505060405180910390f35b6104526004803603604081101561041c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610908565b604051808215151515815260200191505060405180910390f35b6104ce6004803603604081101561048257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610926565b6040518082815260200191505060405180910390f35b606060038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561057c5780601f106105515761010080835404028352916020019161057c565b820191906000526020600020905b81548152906001019060200180831161055f57829003601f168201915b5050505050905090565b600061059a6105936109ad565b84846109b5565b6001905092915050565b6000600254905090565b60006105bb848484610bac565b61067c846105c76109ad565b6106778560405180606001604052806028815260200161102660289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600061062d6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6109b5565b600190509392505050565b6000600560009054906101000a900460ff16905090565b60006107476106ab6109ad565b8461074285600160006106bc6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2d90919063ffffffff16565b6109b5565b6001905092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b606060048054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108315780601f1061080657610100808354040283529160200191610831565b820191906000526020600020905b81548152906001019060200180831161081457829003601f168201915b5050505050905090565b60006108fe6108486109ad565b846108f98560405180606001604052806025815260200161109760259139600160006108726109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6109b5565b6001905092915050565b600061091c6109156109ad565b8484610bac565b6001905092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610a3b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260248152602001806110736024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610ac1576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180610fde6022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610c32576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602581526020018061104e6025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610cb8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526023815260200180610fbb6023913960400191505060405180910390fd5b610cc3838383610fb5565b610d2e81604051806060016040528060268152602001611000602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610dc1816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2d90919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b6000838311158290610f1a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610edf578082015181840152602081019050610ec4565b50505050905090810190601f168015610f0c5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b600080828401905083811015610fab576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b50505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa26469706673582212204897325f6a9671cb2f29f875b7efdbbd4fd9aa7af3305b13a6ef5e47d81eafa764736f6c63430006060033
{"success": true, "error": null, "results": {}}
true
null
{}
9
0x0319a976c8dea5d31d1cf36eaffd8bec14957179
pragma solidity 0.6.5; pragma experimental ABIEncoderV2; struct UserInfo { uint256 amount; uint256 rewardDebt; } struct PoolInfo { address lpToken; uint256 allocPoint; uint256 lastRewardBlock; uint256 accSushiPerShare; } 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 MasterChef { function poolLength() external view returns (uint256); function poolInfo(uint256) external view returns (PoolInfo memory); function userInfo(uint256, address) external view returns (UserInfo memory); function pendingSushi(uint256, address) external view returns (uint256); } contract SushiStakingAdapter is ProtocolAdapter { string public constant override adapterType = "Asset"; string public constant override tokenType = "ERC20"; address internal constant SUSHI = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2; address internal constant MASTER_CHEF = 0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd; /** * @return Amount of SUSHI rewards / staked tokens for a given account. * @dev Implementation of ProtocolAdapter interface function. */ function getBalance(address token, address account) external view override returns (uint256) { uint256 length = MasterChef(MASTER_CHEF).poolLength(); if (token == SUSHI) { uint256 totalRewards = 0; for(uint256 i = 0; i < length; i++) { totalRewards += MasterChef(MASTER_CHEF).pendingSushi(i, account); } return totalRewards; } else { for(uint256 i = 0; i < length; i++) { UserInfo memory user = MasterChef(MASTER_CHEF).userInfo(i, account); PoolInfo memory pool = MasterChef(MASTER_CHEF).poolInfo(i); if (pool.lpToken == token) { return user.amount; } } return 0; } } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); 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; } }
0x608060405234801561001057600080fd5b50600436106100415760003560e01c806330fa738c14610046578063d4fac45d14610064578063f72c079114610084575b600080fd5b61004e61008c565b60405161005b9190610573565b60405180910390f35b61007761007236600461049e565b6100c5565b60405161005b91906105e4565b61004e61040d565b6040518060400160405280600581526020017f455243323000000000000000000000000000000000000000000000000000000081525081565b60008073c2edad668740f1aa35e4d8f227fb8e17dca888cd73ffffffffffffffffffffffffffffffffffffffff1663081e3eda6040518163ffffffff1660e01b815260040160206040518083038186803b15801561012257600080fd5b505afa158015610136573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061015a919061055b565b905073ffffffffffffffffffffffffffffffffffffffff8416736b3595068778dd592e39a122f4f5a5cf09c90fe21415610252576000805b82811015610248576040517f195426ec00000000000000000000000000000000000000000000000000000000815273c2edad668740f1aa35e4d8f227fb8e17dca888cd9063195426ec906101ec90849089906004016105ed565b60206040518083038186803b15801561020457600080fd5b505afa158015610218573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061023c919061055b565b90910190600101610192565b5091506104079050565b60005b8181101561040057610265610446565b6040517f93f1a40b00000000000000000000000000000000000000000000000000000000815273c2edad668740f1aa35e4d8f227fb8e17dca888cd906393f1a40b906102b790859089906004016105ed565b604080518083038186803b1580156102ce57600080fd5b505afa1580156102e2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103069190610528565b9050610310610460565b6040517f1526fe2700000000000000000000000000000000000000000000000000000000815273c2edad668740f1aa35e4d8f227fb8e17dca888cd90631526fe27906103609086906004016105e4565b60806040518083038186803b15801561037857600080fd5b505afa15801561038c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103b091906104d6565b90508673ffffffffffffffffffffffffffffffffffffffff16816000015173ffffffffffffffffffffffffffffffffffffffff1614156103f65750519250610407915050565b5050600101610255565b5060009150505b92915050565b6040518060400160405280600581526020017f417373657400000000000000000000000000000000000000000000000000000081525081565b604051806040016040528060008152602001600081525090565b6040518060800160405280600073ffffffffffffffffffffffffffffffffffffffff1681526020016000815260200160008152602001600081525090565b600080604083850312156104b0578182fd5b82356104bb81610638565b915060208301356104cb81610638565b809150509250929050565b6000608082840312156104e7578081fd5b6104f16080610611565b82516104fc81610638565b808252506020830151602082015260408301516040820152606083015160608201528091505092915050565b600060408284031215610539578081fd5b6105436040610611565b82518152602083015160208201528091505092915050565b60006020828403121561056c578081fd5b5051919050565b6000602080835283518082850152825b8181101561059f57858101830151858201604001528201610583565b818111156105b05783604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b90815260200190565b91825273ffffffffffffffffffffffffffffffffffffffff16602082015260400190565b60405181810167ffffffffffffffff8111828210171561063057600080fd5b604052919050565b73ffffffffffffffffffffffffffffffffffffffff8116811461065a57600080fd5b5056fea2646970667358221220a3c4279badf4199c7d286a57ca8c9a22da00bc005b3a693fba5674f626e7ad4b64736f6c63430006050033
{"success": true, "error": null, "results": {}}
true
null
{}
10
0x033d95b10e9d67f93bf71350c6e9c85f460e55de
pragma solidity 0.5.17; library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } contract CommonConstants { bytes4 constant internal ERC1155_ACCEPTED = 0xf23a6e61; // bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) bytes4 constant internal ERC1155_BATCH_ACCEPTED = 0xbc197c81; // bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")) } interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } interface IERC1155 /* is ERC165 */ { /** @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). The `_operator` argument MUST be msg.sender. The `_from` argument MUST be the address of the holder whose balance is decreased. The `_to` argument MUST be the address of the recipient whose balance is increased. The `_id` argument MUST be the token type being transferred. The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by. When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). */ event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); /** @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). The `_operator` argument MUST be msg.sender. The `_from` argument MUST be the address of the holder whose balance is decreased. The `_to` argument MUST be the address of the recipient whose balance is increased. The `_ids` argument MUST be the list of tokens being transferred. The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by. When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). */ event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values); /** @dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absense of an event assumes disabled). */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** @dev MUST emit when the URI is updated for a token ID. URIs are defined in RFC 3986. The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". */ event URI(string _value, uint256 indexed _id); /** @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if balance of holder for token `_id` is lower than the `_value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _id ID of the token type @param _value Transfer amount @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; /** @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if length of `_ids` is not the same as length of `_values`. MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. MUST revert on any other error. MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _ids IDs of each token type (order and length must match _values array) @param _values Transfer amounts per token type (order and length must match _ids array) @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external; /** @notice Get the balance of an account's Tokens. @param _owner The address of the token holder @param _id ID of the Token @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256); /** @notice Get the balance of multiple account/token pairs @param _owners The addresses of the token holders @param _ids ID of the Tokens @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); /** @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. @dev MUST emit the ApprovalForAll event on success. @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 Queries the approval status of an operator for a given owner. @param _owner The owner of the Tokens @param _operator Address of authorized operator @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool); } interface ERC1155TokenReceiver { /** @notice Handle the receipt of a single ERC1155 token type. @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated. This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer. This function MUST revert if it rejects the transfer. Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @param _operator The address which initiated the transfer (i.e. msg.sender) @param _from The address which previously owned the token @param _id The ID of the token being transferred @param _value The amount of tokens being transferred @param _data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4); /** @notice Handle the receipt of multiple ERC1155 token types. @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated. This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s). This function MUST revert if it rejects the transfer(s). Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @param _operator The address which initiated the batch transfer (i.e. msg.sender) @param _from The address which previously owned the token @param _ids An array containing ids of each token being transferred (order and length must match _values array) @param _values An array containing amounts of each token being transferred (order and length must match _ids array) @param _data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); } 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 ERC1155 is IERC1155, ERC165, CommonConstants { using SafeMath for uint256; using Address for address; // id => (owner => balance) mapping (uint256 => mapping(address => uint256)) internal balances; // owner => (operator => approved) mapping (address => mapping(address => bool)) internal operatorApproval; /////////////////////////////////////////// ERC165 ////////////////////////////////////////////// /* bytes4(keccak256('supportsInterface(bytes4)')); */ bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; /* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^ bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^ bytes4(keccak256("balanceOf(address,uint256)")) ^ bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^ bytes4(keccak256("setApprovalForAll(address,bool)")) ^ bytes4(keccak256("isApprovedForAll(address,address)")); */ bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; function supportsInterface(bytes4 _interfaceId) public view returns (bool) { if (_interfaceId == INTERFACE_SIGNATURE_ERC165 || _interfaceId == INTERFACE_SIGNATURE_ERC1155) { return true; } return false; } /////////////////////////////////////////// ERC1155 ////////////////////////////////////////////// /** @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if balance of holder for token `_id` is lower than the `_value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _id ID of the token type @param _value Transfer amount @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external { require(_to != address(0x0), "_to must be non-zero."); require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers."); // SafeMath will throw with insuficient funds _from // or if _id is not valid (balance will be 0) balances[_id][_from] = balances[_id][_from].sub(_value); balances[_id][_to] = _value.add(balances[_id][_to]); // MUST emit event emit TransferSingle(msg.sender, _from, _to, _id, _value); // Now that the balance is updated and the event was emitted, // call onERC1155Received if the destination is a contract. if (_to.isContract()) { _doSafeTransferAcceptanceCheck(msg.sender, _from, _to, _id, _value, _data); } } /** @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if length of `_ids` is not the same as length of `_values`. MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. MUST revert on any other error. MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _ids IDs of each token type (order and length must match _values array) @param _values Transfer amounts per token type (order and length must match _ids array) @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external { // MUST Throw on errors require(_to != address(0x0), "destination address must be non-zero."); require(_ids.length == _values.length, "_ids and _values array length must match."); require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers."); for (uint256 i = 0; i < _ids.length; ++i) { uint256 id = _ids[i]; uint256 value = _values[i]; // SafeMath will throw with insuficient funds _from // or if _id is not valid (balance will be 0) balances[id][_from] = balances[id][_from].sub(value); balances[id][_to] = value.add(balances[id][_to]); } // Note: instead of the below batch versions of event and acceptance check you MAY have emitted a TransferSingle // event and a subsequent call to _doSafeTransferAcceptanceCheck in above loop for each balance change instead. // Or emitted a TransferSingle event for each in the loop and then the single _doSafeBatchTransferAcceptanceCheck below. // However it is implemented the balance changes and events MUST match when a check (i.e. calling an external contract) is done. // MUST emit event emit TransferBatch(msg.sender, _from, _to, _ids, _values); // Now that the balances are updated and the events are emitted, // call onERC1155BatchReceived if the destination is a contract. if (_to.isContract()) { _doSafeBatchTransferAcceptanceCheck(msg.sender, _from, _to, _ids, _values, _data); } } /** @notice Get the balance of an account's Tokens. @param _owner The address of the token holder @param _id ID of the Token @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256) { // The balance of any account can be calculated from the Transfer events history. // However, since we need to keep the balances to validate transfer request, // there is no extra cost to also privide a querry function. return balances[_id][_owner]; } /** @notice Get the balance of multiple account/token pairs @param _owners The addresses of the token holders @param _ids ID of the Tokens @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory) { require(_owners.length == _ids.length); uint256[] memory balances_ = new uint256[](_owners.length); for (uint256 i = 0; i < _owners.length; ++i) { balances_[i] = balances[_ids[i]][_owners[i]]; } return balances_; } /** @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. @dev MUST emit the ApprovalForAll event on success. @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 { operatorApproval[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** @notice Queries the approval status of an operator for a given owner. @param _owner The owner of the Tokens @param _operator Address of authorized operator @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return operatorApproval[_owner][_operator]; } /////////////////////////////////////////// Internal ////////////////////////////////////////////// function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 _id, uint256 _value, bytes memory _data) internal { // If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by // the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance. // Note: if the below reverts in the onERC1155Received function of the _to address you will have an undefined revert reason returned rather than the one in the require test. // If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_ACCEPTED test. require(ERC1155TokenReceiver(_to).onERC1155Received(_operator, _from, _id, _value, _data) == ERC1155_ACCEPTED, "contract returned an unknown value from onERC1155Received"); } function _doSafeBatchTransferAcceptanceCheck(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) internal { // If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by // the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance. // Note: if the below reverts in the onERC1155BatchReceived function of the _to address you will have an undefined revert reason returned rather than the one in the require test. // If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_BATCH_ACCEPTED test. require(ERC1155TokenReceiver(_to).onERC1155BatchReceived(_operator, _from, _ids, _values, _data) == ERC1155_BATCH_ACCEPTED, "contract returned an unknown value from onERC1155BatchReceived"); } } contract ERC1155Mintable is ERC1155 { bytes4 constant private INTERFACE_SIGNATURE_URI = 0x0e89341c; // id => creators mapping (uint256 => address) public creators; // A nonce to ensure we have a unique id each time we mint. uint256 public nonce; modifier creatorOnly(uint256 _id) { require(creators[_id] == msg.sender); _; } function supportsInterface(bytes4 _interfaceId) public view returns (bool) { if (_interfaceId == INTERFACE_SIGNATURE_URI) { return true; } else { return super.supportsInterface(_interfaceId); } } // Creates a new token type and assings _initialSupply to minter function create(uint256 _initialSupply, string calldata _uri) external returns(uint256 _id) { _id = ++nonce; creators[_id] = msg.sender; balances[_id][msg.sender] = _initialSupply; // Transfer event with mint semantic emit TransferSingle(msg.sender, address(0x0), msg.sender, _id, _initialSupply); if (bytes(_uri).length > 0) emit URI(_uri, _id); } // Batch mint tokens. Assign directly to _to[]. function mint(uint256 _id, address[] calldata _to, uint256[] calldata _quantities) external creatorOnly(_id) { for (uint256 i = 0; i < _to.length; ++i) { address to = _to[i]; uint256 quantity = _quantities[i]; // Grant the items to the caller balances[_id][to] = quantity.add(balances[_id][to]); // Emit the Transfer/Mint event. // the 0x0 source address implies a mint // It will also provide the circulating supply info. emit TransferSingle(msg.sender, address(0x0), to, _id, quantity); if (to.isContract()) { _doSafeTransferAcceptanceCheck(msg.sender, msg.sender, to, _id, quantity, ''); } } } function setURI(string calldata _uri, uint256 _id) external creatorOnly(_id) { emit URI(_uri, _id); } }
0x608060405234801561001057600080fd5b50600436106100b35760003560e01c8063a22cb46511610071578063a22cb4651461051f578063affed0e01461056f578063cd53d08e1461058d578063cfa84fc1146105fb578063e985e9c5146106d3578063f242432a1461074f576100b3565b8062fdd58e146100b85780630118fa491461011a57806301ffc9a7146101b15780632eb2c2d6146102165780634e1273f41461037957806367db3b8f1461049c575b600080fd5b610104600480360360408110156100ce57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061081c565b6040518082815260200191505060405180910390f35b61019b6004803603604081101561013057600080fd5b81019080803590602001909291908035906020019064010000000081111561015757600080fd5b82018360208201111561016957600080fd5b8035906020019184600183028401116401000000008311171561018b57600080fd5b9091929391929390505050610876565b6040518082815260200191505060405180910390f35b6101fc600480360360208110156101c757600080fd5b8101908080357bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19169060200190929190505050610a2c565b604051808215151515815260200191505060405180910390f35b610377600480360360a081101561022c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019064010000000081111561028957600080fd5b82018360208201111561029b57600080fd5b803590602001918460208302840111640100000000831117156102bd57600080fd5b9091929391929390803590602001906401000000008111156102de57600080fd5b8201836020820111156102f057600080fd5b8035906020019184602083028401116401000000008311171561031257600080fd5b90919293919293908035906020019064010000000081111561033357600080fd5b82018360208201111561034557600080fd5b8035906020019184600183028401116401000000008311171561036757600080fd5b9091929391929390505050610a95565b005b6104456004803603604081101561038f57600080fd5b81019080803590602001906401000000008111156103ac57600080fd5b8201836020820111156103be57600080fd5b803590602001918460208302840111640100000000831117156103e057600080fd5b90919293919293908035906020019064010000000081111561040157600080fd5b82018360208201111561041357600080fd5b8035906020019184602083028401116401000000008311171561043557600080fd5b9091929391929390505050611031565b6040518080602001828103825283818151815260200191508051906020019060200280838360005b8381101561048857808201518184015260208101905061046d565b505050509050019250505060405180910390f35b61051d600480360360408110156104b257600080fd5b81019080803590602001906401000000008111156104cf57600080fd5b8201836020820111156104e157600080fd5b8035906020019184600183028401116401000000008311171561050357600080fd5b909192939192939080359060200190929190505050611147565b005b61056d6004803603604081101561053557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080351515906020019092919050505061121d565b005b61057761131e565b6040518082815260200191505060405180910390f35b6105b9600480360360208110156105a357600080fd5b8101908080359060200190929190505050611324565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6106d16004803603606081101561061157600080fd5b81019080803590602001909291908035906020019064010000000081111561063857600080fd5b82018360208201111561064a57600080fd5b8035906020019184602083028401116401000000008311171561066c57600080fd5b90919293919293908035906020019064010000000081111561068d57600080fd5b82018360208201111561069f57600080fd5b803590602001918460208302840111640100000000831117156106c157600080fd5b9091929391929390505050611357565b005b610735600480360360408110156106e957600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506115aa565b604051808215151515815260200191505060405180910390f35b61081a600480360360a081101561076557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919080359060200190929190803590602001906401000000008111156107d657600080fd5b8201836020820111156107e857600080fd5b8035906020019184600183028401116401000000008311171561080a57600080fd5b909192939192939050505061163e565b005b600080600083815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b60006003600081546001019190508190559050336002600083815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508360008083815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055503373ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f628488604051808381526020018281526020019250505060405180910390a46000838390501115610a2557807f6bb7ff708619ba0610cba295a58592e0451dee2622938c8755667688daf3529b848460405180806020018281038252848482818152602001925080828437600081840152601f19601f820116905080830192505050935050505060405180910390a25b9392505050565b6000630e89341c60e01b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916827bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19161415610a845760019050610a90565b610a8d82611a6a565b90505b919050565b600073ffffffffffffffffffffffffffffffffffffffff168773ffffffffffffffffffffffffffffffffffffffff161415610b1b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260258152602001806120006025913960400191505060405180910390fd5b838390508686905014610b79576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260298152602001806120926029913960400191505060405180910390fd5b3373ffffffffffffffffffffffffffffffffffffffff168873ffffffffffffffffffffffffffffffffffffffff161480610c40575060011515600160008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff161515145b610c95576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f815260200180612025602f913960400191505060405180910390fd5b60008090505b86869050811015610e4b576000878783818110610cb457fe5b9050602002013590506000868684818110610ccb57fe5b905060200201359050610d368160008085815260200190815260200160002060008e73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054611b1b90919063ffffffff16565b60008084815260200190815260200160002060008d73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610deb60008084815260200190815260200160002060008c73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482611b3290919063ffffffff16565b60008084815260200190815260200160002060008c73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505050806001019050610c9b565b508673ffffffffffffffffffffffffffffffffffffffff168873ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb898989896040518080602001806020018381038352878782818152602001925060200280828437600081840152601f19601f8201169050808301925050508381038252858582818152602001925060200280828437600081840152601f19601f820116905080830192505050965050505050505060405180910390a4610f4d8773ffffffffffffffffffffffffffffffffffffffff16611b4c565b1561102757611026338989898980806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f82011690508083019250505050505050888880806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f8201169050808301925050505050505087878080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f82011690508083019250505050505050611b5f565b5b5050505050505050565b606082829050858590501461104557600080fd5b6060858590506040519080825280602002602001820160405280156110795781602001602082028038833980820191505090505b50905060008090505b8686905081101561113a5760008086868481811061109c57fe5b90506020020135815260200190815260200160002060008888848181106110bf57fe5b9050602002013573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482828151811061112357fe5b602002602001018181525050806001019050611082565b5080915050949350505050565b803373ffffffffffffffffffffffffffffffffffffffff166002600083815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16146111b357600080fd5b817f6bb7ff708619ba0610cba295a58592e0451dee2622938c8755667688daf3529b858560405180806020018281038252848482818152602001925080828437600081840152601f19601f820116905080830192505050935050505060405180910390a250505050565b80600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055508173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c3183604051808215151515815260200191505060405180910390a35050565b60035481565b60026020528060005260406000206000915054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b843373ffffffffffffffffffffffffffffffffffffffff166002600083815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16146113c357600080fd5b60008090505b858590508110156115a15760008686838181106113e257fe5b9050602002013573ffffffffffffffffffffffffffffffffffffffff169050600085858481811061140f57fe5b90506020020135905061147a6000808b815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482611b3290919063ffffffff16565b6000808b815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f628c85604051808381526020018281526020019250505060405180910390a46115718273ffffffffffffffffffffffffffffffffffffffff16611b4c565b15611594576115933333848c8560405180602001604052806000815250611df0565b5b50508060010190506113c9565b50505050505050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16905092915050565b600073ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff1614156116e1576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260158152602001807f5f746f206d757374206265206e6f6e2d7a65726f2e000000000000000000000081525060200191505060405180910390fd5b3373ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff1614806117a8575060011515600160008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff161515145b6117fd576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f815260200180612025602f913960400191505060405180910390fd5b61185f8360008087815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054611b1b90919063ffffffff16565b60008086815260200190815260200160002060008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061191460008086815260200190815260200160002060008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205484611b3290919063ffffffff16565b60008086815260200190815260200160002060008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508473ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f628787604051808381526020018281526020019250505060405180910390a4611a0a8573ffffffffffffffffffffffffffffffffffffffff16611b4c565b15611a6257611a61338787878787878080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f82011690508083019250505050505050611df0565b5b505050505050565b60006301ffc9a760e01b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916827bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19161480611b03575063d9b67a2660e01b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916827bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916145b15611b115760019050611b16565b600090505b919050565b600082821115611b2757fe5b818303905092915050565b6000818301905082811015611b4357fe5b80905092915050565b600080823b905060008111915050919050565b63bc197c8160e01b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19168473ffffffffffffffffffffffffffffffffffffffff1663bc197c8188888787876040518663ffffffff1660e01b8152600401808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001806020018060200180602001848103845287818151815260200191508051906020019060200280838360005b83811015611c65578082015181840152602081019050611c4a565b50505050905001848103835286818151815260200191508051906020019060200280838360005b83811015611ca7578082015181840152602081019050611c8c565b50505050905001848103825285818151815260200191508051906020019080838360005b83811015611ce6578082015181840152602081019050611ccb565b50505050905090810190601f168015611d135780820380516001836020036101000a031916815260200191505b5098505050505050505050602060405180830381600087803b158015611d3857600080fd5b505af1158015611d4c573d6000803e3d6000fd5b505050506040513d6020811015611d6257600080fd5b81019080805190602001909291905050507bffffffffffffffffffffffffffffffffffffffffffffffffffffffff191614611de8576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252603e815260200180612054603e913960400191505060405180910390fd5b505050505050565b63f23a6e6160e01b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19168473ffffffffffffffffffffffffffffffffffffffff1663f23a6e6188888787876040518663ffffffff1660e01b8152600401808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200184815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b83811015611ef7578082015181840152602081019050611edc565b50505050905090810190601f168015611f245780820380516001836020036101000a031916815260200191505b509650505050505050602060405180830381600087803b158015611f4757600080fd5b505af1158015611f5b573d6000803e3d6000fd5b505050506040513d6020811015611f7157600080fd5b81019080805190602001909291905050507bffffffffffffffffffffffffffffffffffffffffffffffffffffffff191614611ff7576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260398152602001806120bb6039913960400191505060405180910390fd5b50505050505056fe64657374696e6174696f6e2061646472657373206d757374206265206e6f6e2d7a65726f2e4e656564206f70657261746f7220617070726f76616c20666f7220337264207061727479207472616e73666572732e636f6e74726163742072657475726e656420616e20756e6b6e6f776e2076616c75652066726f6d206f6e45524331313535426174636852656365697665645f69647320616e64205f76616c756573206172726179206c656e677468206d757374206d617463682e636f6e74726163742072657475726e656420616e20756e6b6e6f776e2076616c75652066726f6d206f6e455243313135355265636569766564a265627a7a72315820598cb8b19160791fbc55206c8e367402533d9c2bb04f7a29436f88428d21551264736f6c63430005110032
{"success": true, "error": null, "results": {}}
true
null
{}
11
0x04775962e613fab025120992e4eed7eed3ba87f2
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 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 ChainTurk 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, uint256 totalSupply) public { _name = name; _symbol = symbol; _decimals = 2; _totalSupply = totalSupply; _balances[msg.sender] = totalSupply; } /** * @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 { } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c80633950935111610071578063395093511461025857806370a08231146102bc57806395d89b4114610314578063a457c2d714610397578063a9059cbb146103fb578063dd62ed3e1461045f576100a9565b806306fdde03146100ae578063095ea7b31461013157806318160ddd1461019557806323b872dd146101b3578063313ce56714610237575b600080fd5b6100b66104d7565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f65780820151818401526020810190506100db565b50505050905090810190601f1680156101235780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61017d6004803603604081101561014757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610579565b60405180821515815260200191505060405180910390f35b61019d610597565b6040518082815260200191505060405180910390f35b61021f600480360360608110156101c957600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506105a1565b60405180821515815260200191505060405180910390f35b61023f61067a565b604051808260ff16815260200191505060405180910390f35b6102a46004803603604081101561026e57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610691565b60405180821515815260200191505060405180910390f35b6102fe600480360360208110156102d257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610744565b6040518082815260200191505060405180910390f35b61031c61078c565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561035c578082015181840152602081019050610341565b50505050905090810190601f1680156103895780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6103e3600480360360408110156103ad57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061082e565b60405180821515815260200191505060405180910390f35b6104476004803603604081101561041157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506108fb565b60405180821515815260200191505060405180910390f35b6104c16004803603604081101561047557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610919565b6040518082815260200191505060405180910390f35b606060038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561056f5780601f106105445761010080835404028352916020019161056f565b820191906000526020600020905b81548152906001019060200180831161055257829003601f168201915b5050505050905090565b600061058d6105866109a0565b84846109a8565b6001905092915050565b6000600254905090565b60006105ae848484610b9f565b61066f846105ba6109a0565b61066a8560405180606001604052806028815260200161101960289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006106206109a0565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e609092919063ffffffff16565b6109a8565b600190509392505050565b6000600560009054906101000a900460ff16905090565b600061073a61069e6109a0565b8461073585600160006106af6109a0565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2090919063ffffffff16565b6109a8565b6001905092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b606060048054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108245780601f106107f957610100808354040283529160200191610824565b820191906000526020600020905b81548152906001019060200180831161080757829003601f168201915b5050505050905090565b60006108f161083b6109a0565b846108ec8560405180606001604052806025815260200161108a60259139600160006108656109a0565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e609092919063ffffffff16565b6109a8565b6001905092915050565b600061090f6109086109a0565b8484610b9f565b6001905092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610a2e576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260248152602001806110666024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610ab4576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180610fd16022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610c25576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260258152602001806110416025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610cab576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526023815260200180610fae6023913960400191505060405180910390fd5b610cb6838383610fa8565b610d2181604051806060016040528060268152602001610ff3602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e609092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610db4816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2090919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b6000838311158290610f0d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610ed2578082015181840152602081019050610eb7565b50505050905090810190601f168015610eff5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b600080828401905083811015610f9e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b50505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa26469706673582212205743796c94d211514f736707650997ad9b801a0b86e3e19f93add90a25774cc064736f6c634300060c0033
{"success": true, "error": null, "results": {}}
true
null
{}
12
0x04a0c4c9774a56b8572034ce5df119b40fbd6919
pragma solidity 0.5.7; library Roles { struct Role { mapping (address => bool) bearer; } function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _pausableActive; bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused whenPausableActive { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused whenPausableActive { _paused = false; emit Unpaused(msg.sender); } /** * @dev Options to activate or deactivate Pausable ability */ function _setPausableActive(bool _active) internal { _pausableActive = _active; } modifier whenPausableActive() { require(_pausableActive); _; } } 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); } library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @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; } function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } 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; } function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; 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 Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); 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 Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); 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; } } contract ContactCoinToken is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Public parameters to define the token */ // Token symbol (short) string public symbol; // Token name (Long) string public name; // Decimals (18 maximum) uint8 public decimals; /** * @dev Public functions to make the contract accesible */ constructor (address initialAccount, string memory _tokenSymbol, string memory _tokenName, uint256 initialBalance) public { // Initialize Contract Parameters symbol = _tokenSymbol; name = _tokenName; decimals = 18; // default decimals is going to be 18 always _mint(initialAccount, initialBalance); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } 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; } function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 _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); } 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); } 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); } function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } contract ERC20Burnable is ContactCoinToken { bool private _burnableActive; function burn(uint256 value) public whenBurnableActive { _burn(msg.sender, value); } function burnFrom(address from, uint256 value) public whenBurnableActive { _burnFrom(from, value); } function _setBurnableActive(bool _active) internal { _burnableActive = _active; } modifier whenBurnableActive() { require(_burnableActive); _; } } contract ERC20Mintable is ContactCoinToken, MinterRole { bool private _mintableActive; function mint(address to, uint256 value) public onlyMinter whenMintableActive returns (bool) { _mint(to, value); return true; } function _setMintableActive(bool _active) internal { _mintableActive = _active; } modifier whenMintableActive() { require(_mintableActive); _; } } contract ERC20AUX is ContactCoinToken, ERC20Burnable, ERC20Mintable, Pausable { // maximum capital, if defined > 0 uint256 private _cap; constructor ( address initialAccount, string memory _tokenSymbol, string memory _tokenName, uint256 initialBalance, uint256 cap, bool _burnableOption, bool _mintableOption, bool _pausableOption ) public ContactCoinToken(initialAccount, _tokenSymbol, _tokenName, initialBalance) { // we must add customer account as the first minter addMinter(initialAccount); // and this contract must renounce minter role renounceMinter(); // same with pauser addPauser(initialAccount); renouncePauser(); if (cap > 0) { _cap = cap; // maximum capitalization limited } else { _cap = 0; // unlimited capitalization } // activate or deactivate options _setBurnableActive(_burnableOption); _setMintableActive(_mintableOption); _setPausableActive(_pausableOption); } /** * @return the cap for the token minting. */ function cap() public view returns (uint256) { return _cap; } /** * limit the mint to a maximum cap only if cap is defined */ function _mint(address account, uint256 value) internal { if (_cap > 0) { require(totalSupply().add(value) <= _cap); } super._mint(account, value); } /** * Pausable options */ function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from,address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c8063395093511161007157806339509351146101d957806370a082311461020557806395d89b411461022b578063a457c2d714610233578063a9059cbb1461025f578063dd62ed3e1461028b576100a9565b806306fdde03146100ae578063095ea7b31461012b57806318160ddd1461016b57806323b872dd14610185578063313ce567146101bb575b600080fd5b6100b66102b9565b6040805160208082528351818301528351919283929083019185019080838360005b838110156100f05781810151838201526020016100d8565b50505050905090810190601f16801561011d5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101576004803603604081101561014157600080fd5b506001600160a01b038135169060200135610347565b604080519115158252519081900360200190f35b6101736103c3565b60408051918252519081900360200190f35b6101576004803603606081101561019b57600080fd5b506001600160a01b038135811691602081013590911690604001356103c9565b6101c3610492565b6040805160ff9092168252519081900360200190f35b610157600480360360408110156101ef57600080fd5b506001600160a01b03813516906020013561049b565b6101736004803603602081101561021b57600080fd5b50356001600160a01b0316610549565b6100b6610564565b6101576004803603604081101561024957600080fd5b506001600160a01b0381351690602001356105bf565b6101576004803603604081101561027557600080fd5b506001600160a01b038135169060200135610608565b610173600480360360408110156102a157600080fd5b506001600160a01b038135811691602001351661061e565b6004805460408051602060026001851615610100026000190190941693909304601f8101849004840282018401909252818152929183018282801561033f5780601f106103145761010080835404028352916020019161033f565b820191906000526020600020905b81548152906001019060200180831161032257829003601f168201915b505050505081565b60006001600160a01b03831661035c57600080fd5b3360008181526001602090815260408083206001600160a01b03881680855290835292819020869055805186815290519293927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a350600192915050565b60025490565b6001600160a01b03831660009081526001602090815260408083203384529091528120546103fd908363ffffffff61064916565b6001600160a01b038516600090815260016020908152604080832033845290915290205561042c84848461065e565b6001600160a01b0384166000818152600160209081526040808320338085529083529281902054815190815290519293927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35060019392505050565b60055460ff1681565b60006001600160a01b0383166104b057600080fd5b3360009081526001602090815260408083206001600160a01b03871684529091529020546104e4908363ffffffff61072916565b3360008181526001602090815260408083206001600160a01b0389168085529083529281902085905580519485525191937f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929081900390910190a350600192915050565b6001600160a01b031660009081526020819052604090205490565b6003805460408051602060026001851615610100026000190190941693909304601f8101849004840282018401909252818152929183018282801561033f5780601f106103145761010080835404028352916020019161033f565b60006001600160a01b0383166105d457600080fd5b3360009081526001602090815260408083206001600160a01b03871684529091529020546104e4908363ffffffff61064916565b600061061533848461065e565b50600192915050565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b60008282111561065857600080fd5b50900390565b6001600160a01b03821661067157600080fd5b6001600160a01b03831660009081526020819052604090205461069a908263ffffffff61064916565b6001600160a01b0380851660009081526020819052604080822093909355908416815220546106cf908263ffffffff61072916565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b60008282018381101561073b57600080fd5b939250505056fea165627a7a72305820c834b7d6a764ae5979774562c36b4eaecf33c95dc4111d810976a9d9798683010029
{"success": true, "error": null, "results": {}}
true
null
{}
13
0x0518a3c95f777b585dde38814331077c325565b1
pragma solidity 0.5.0; contract Context { constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal 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; 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; function totalSupply() public view returns (uint256) { return _totalSupply; } 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; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } 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; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 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, 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); } 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); } 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); } function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _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; 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; } } contract YFATM is ERC20, ERC20Detailed { address owner; using SafeMath for uint256; ERC20 public token; constructor () public ERC20Detailed("YFATOM", "YFATM", 18) { _mint(msg.sender, 15000 * (10 ** uint256(decimals()))); owner=msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } }
0x6080604052600436106100c5576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100ca578063095ea7b31461015a57806318160ddd146101cd57806323b872dd146101f8578063313ce5671461028b57806339509351146102bc57806370a082311461032f57806395d89b4114610394578063a457c2d714610424578063a9059cbb14610497578063dd62ed3e1461050a578063f2fde38b1461058f578063fc0c546a146105e0575b600080fd5b3480156100d657600080fd5b506100df610637565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561011f578082015181840152602081019050610104565b50505050905090810190601f16801561014c5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561016657600080fd5b506101b36004803603604081101561017d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506106d9565b604051808215151515815260200191505060405180910390f35b3480156101d957600080fd5b506101e26106f7565b6040518082815260200191505060405180910390f35b34801561020457600080fd5b506102716004803603606081101561021b57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610701565b604051808215151515815260200191505060405180910390f35b34801561029757600080fd5b506102a061081e565b604051808260ff1660ff16815260200191505060405180910390f35b3480156102c857600080fd5b50610315600480360360408110156102df57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610835565b604051808215151515815260200191505060405180910390f35b34801561033b57600080fd5b5061037e6004803603602081101561035257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506108e8565b6040518082815260200191505060405180910390f35b3480156103a057600080fd5b506103a9610930565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156103e95780820151818401526020810190506103ce565b50505050905090810190601f1680156104165780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561043057600080fd5b5061047d6004803603604081101561044757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506109d2565b604051808215151515815260200191505060405180910390f35b3480156104a357600080fd5b506104f0600480360360408110156104ba57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610ae3565b604051808215151515815260200191505060405180910390f35b34801561051657600080fd5b506105796004803603604081101561052d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610b01565b6040518082815260200191505060405180910390f35b34801561059b57600080fd5b506105de600480360360208110156105b257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610b88565b005b3480156105ec57600080fd5b506105f5610c64565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b606060038054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156106cf5780601f106106a4576101008083540402835291602001916106cf565b820191906000526020600020905b8154815290600101906020018083116106b257829003601f168201915b5050505050905090565b60006106ed6106e6610c8a565b8484610c92565b6001905092915050565b6000600254905090565b600061070e848484610f13565b6108138461071a610c8a565b61080e85606060405190810160405280602881526020017f45524332303a207472616e7366657220616d6f756e742065786365656473206181526020017f6c6c6f77616e6365000000000000000000000000000000000000000000000000815250600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006107c4610c8a565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546112979092919063ffffffff16565b610c92565b600190509392505050565b6000600560009054906101000a900460ff16905090565b60006108de610842610c8a565b846108d98560016000610853610c8a565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461135990919063ffffffff16565b610c92565b6001905092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b606060048054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156109c85780601f1061099d576101008083540402835291602001916109c8565b820191906000526020600020905b8154815290600101906020018083116109ab57829003601f168201915b5050505050905090565b6000610ad96109df610c8a565b84610ad485606060405190810160405280602581526020017f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f7781526020017f207a65726f00000000000000000000000000000000000000000000000000000081525060016000610a4d610c8a565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546112979092919063ffffffff16565b610c92565b6001905092915050565b6000610af7610af0610c8a565b8484610f13565b6001905092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600560019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515610be457600080fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614151515610c2057600080fd5b80600560016101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614151515610d5d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260248152602001807f45524332303a20617070726f76652066726f6d20746865207a65726f2061646481526020017f726573730000000000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614151515610e28576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001807f45524332303a20617070726f766520746f20746865207a65726f20616464726581526020017f737300000000000000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614151515610fde576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260258152602001807f45524332303a207472616e736665722066726f6d20746865207a65726f20616481526020017f647265737300000000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16141515156110a9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260238152602001807f45524332303a207472616e7366657220746f20746865207a65726f206164647281526020017f657373000000000000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b61115881606060405190810160405280602681526020017f45524332303a207472616e7366657220616d6f756e742065786365656473206281526020017f616c616e636500000000000000000000000000000000000000000000000000008152506000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546112979092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506111eb816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461135990919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b60008383111582901515611346576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561130b5780820151818401526020810190506112f0565b50505050905090810190601f1680156113385780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b60008082840190508381101515156113d9576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b809150509291505056fea165627a7a7230582048002817d86ee60870c383b8d7d67554c639832c6e9bf72103c42df2e6bb17400029
{"success": true, "error": null, "results": {}}
true
null
{}
14
0x053889176621886e8ca98F349C1DEeB3612D2960
pragma solidity 0.5.17; 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 = 12 hours + 2*60*15; // 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 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; } }
0x6080604052600436106100dd5760003560e01c80636fc1f57e1161007f578063c1a287e211610059578063c1a287e214610787578063e177246e146107b2578063f2b06537146107ed578063f851a44014610840576100dd565b80636fc1f57e146107025780637d645fab14610731578063b1b43ae51461075c576100dd565b80633a66f901116100bb5780633a66f9011461034c5780634dd18bf5146104f3578063591fcdfe146105445780636a42b8f8146106d7576100dd565b80630825f38f146100df5780630e18b681146102de57806326782247146102f5575b005b610263600480360360a08110156100f557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291908035906020019064010000000081111561013c57600080fd5b82018360208201111561014e57600080fd5b8035906020019184600183028401116401000000008311171561017057600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f820116905080830192505050505050509192919290803590602001906401000000008111156101d357600080fd5b8201836020820111156101e557600080fd5b8035906020019184600183028401116401000000008311171561020757600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f82011690508083019250505050505050919291929080359060200190929190505050610897565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156102a3578082015181840152602081019050610288565b50505050905090810190601f1680156102d05780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156102ea57600080fd5b506102f3610f2e565b005b34801561030157600080fd5b5061030a6110bc565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561035857600080fd5b506104dd600480360360a081101561036f57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190803590602001906401000000008111156103b657600080fd5b8201836020820111156103c857600080fd5b803590602001918460018302840111640100000000831117156103ea57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192908035906020019064010000000081111561044d57600080fd5b82018360208201111561045f57600080fd5b8035906020019184600183028401116401000000008311171561048157600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f820116905080830192505050505050509192919290803590602001909291905050506110e2565b6040518082815260200191505060405180910390f35b3480156104ff57600080fd5b506105426004803603602081101561051657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506114a8565b005b34801561055057600080fd5b506106d5600480360360a081101561056757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190803590602001906401000000008111156105ae57600080fd5b8201836020820111156105c057600080fd5b803590602001918460018302840111640100000000831117156105e257600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192908035906020019064010000000081111561064557600080fd5b82018360208201111561065757600080fd5b8035906020019184600183028401116401000000008311171561067957600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192908035906020019092919050505061160b565b005b3480156106e357600080fd5b506106ec611956565b6040518082815260200191505060405180910390f35b34801561070e57600080fd5b5061071761195c565b604051808215151515815260200191505060405180910390f35b34801561073d57600080fd5b5061074661196f565b6040518082815260200191505060405180910390f35b34801561076857600080fd5b50610771611976565b6040518082815260200191505060405180910390f35b34801561079357600080fd5b5061079c61197c565b6040518082815260200191505060405180910390f35b3480156107be57600080fd5b506107eb600480360360208110156107d557600080fd5b8101908080359060200190929190505050611983565b005b3480156107f957600080fd5b506108266004803603602081101561081057600080fd5b8101908080359060200190929190505050611af7565b604051808215151515815260200191505060405180910390f35b34801561084c57600080fd5b50610855611b17565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b60606000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161461093e576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526038815260200180611bcd6038913960400191505060405180910390fd5b60008686868686604051602001808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018581526020018060200180602001848152602001838103835286818151815260200191508051906020019080838360005b838110156109ca5780820151818401526020810190506109af565b50505050905090810190601f1680156109f75780820380516001836020036101000a031916815260200191505b50838103825285818151815260200191508051906020019080838360005b83811015610a30578082015181840152602081019050610a15565b50505050905090810190601f168015610a5d5780820380516001836020036101000a031916815260200191505b50975050505050505050604051602081830303815290604052805190602001209050600360009054906101000a900460ff1615610c0c576004600082815260200190815260200160002060009054906101000a900460ff16610b0a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252603d815260200180611d20603d913960400191505060405180910390fd5b82610b13611b3c565b1015610b6a576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526045815260200180611c6f6045913960600191505060405180910390fd5b610b806212750084611b4490919063ffffffff16565b610b88611b3c565b1115610bdf576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526033815260200180611c3c6033913960400191505060405180910390fd5b60006004600083815260200190815260200160002060006101000a81548160ff0219169083151502179055505b6060600086511415610c2057849050610cdb565b85805190602001208560405160200180837bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916815260040182805190602001908083835b60208310610ca35780518252602082019150602081019050602083039250610c80565b6001836020036101000a0380198251168184511680821785525050505050509050019250505060405160208183030381529060405290505b600060608973ffffffffffffffffffffffffffffffffffffffff1689846040518082805190602001908083835b60208310610d2b5780518252602082019150602081019050602083039250610d08565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d8060008114610d8d576040519150601f19603f3d011682016040523d82523d6000602084013e610d92565b606091505b509150915081610ded576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252603d815260200180611e03603d913960400191505060405180910390fd5b8973ffffffffffffffffffffffffffffffffffffffff16847fa560e3198060a2f10670c1ec5b403077ea6ae93ca8de1c32b451dc1a943cd6e78b8b8b8b604051808581526020018060200180602001848152602001838103835286818151815260200191508051906020019080838360005b83811015610e7a578082015181840152602081019050610e5f565b50505050905090810190601f168015610ea75780820380516001836020036101000a031916815260200191505b50838103825285818151815260200191508051906020019080838360005b83811015610ee0578082015181840152602081019050610ec5565b50505050905090810190601f168015610f0d5780820380516001836020036101000a031916815260200191505b50965050505050505060405180910390a38094505050505095945050505050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610fd4576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526038815260200180611d5d6038913960400191505060405180910390fd5b336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f71614071b88dee5e0b2ae578a9dd7b2ebbe9ae832ba419dc0242cd065a290b6c60405160405180910390a2565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614611189576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526036815260200180611dcd6036913960400191505060405180910390fd5b6111a5600254611197611b3c565b611b4490919063ffffffff16565b8210156111fd576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526049815260200180611e406049913960600191505060405180910390fd5b60008686868686604051602001808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018581526020018060200180602001848152602001838103835286818151815260200191508051906020019080838360005b8381101561128957808201518184015260208101905061126e565b50505050905090810190601f1680156112b65780820380516001836020036101000a031916815260200191505b50838103825285818151815260200191508051906020019080838360005b838110156112ef5780820151818401526020810190506112d4565b50505050905090810190601f16801561131c5780820380516001836020036101000a031916815260200191505b5097505050505050505060405160208183030381529060405280519060200120905060016004600083815260200190815260200160002060006101000a81548160ff0219169083151502179055508673ffffffffffffffffffffffffffffffffffffffff16817f76e2796dc3a81d57b0e8504b647febcbeeb5f4af818e164f11eef8131a6a763f88888888604051808581526020018060200180602001848152602001838103835286818151815260200191508051906020019080838360005b838110156113f75780820151818401526020810190506113dc565b50505050905090810190601f1680156114245780820380516001836020036101000a031916815260200191505b50838103825285818151815260200191508051906020019080838360005b8381101561145d578082015181840152602081019050611442565b50505050905090810190601f16801561148a5780820380516001836020036101000a031916815260200191505b50965050505050505060405180910390a38091505095945050505050565b600360009054906101000a900460ff1615611546573073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614611541576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526038815260200180611d956038913960400191505060405180910390fd5b611562565b6001600360006101000a81548160ff0219169083151502179055505b80600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f69d78e38a01985fbb1462961809b4b2d65531bc93b2b94037f3334b82ca4a75660405160405180910390a250565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146116b0576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526037815260200180611c056037913960400191505060405180910390fd5b60008585858585604051602001808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018581526020018060200180602001848152602001838103835286818151815260200191508051906020019080838360005b8381101561173c578082015181840152602081019050611721565b50505050905090810190601f1680156117695780820380516001836020036101000a031916815260200191505b50838103825285818151815260200191508051906020019080838360005b838110156117a2578082015181840152602081019050611787565b50505050905090810190601f1680156117cf5780820380516001836020036101000a031916815260200191505b5097505050505050505060405160208183030381529060405280519060200120905060006004600083815260200190815260200160002060006101000a81548160ff0219169083151502179055508573ffffffffffffffffffffffffffffffffffffffff16817f2fffc091a501fd91bfbff27141450d3acb40fb8e6d8382b243ec7a812a3aaf8787878787604051808581526020018060200180602001848152602001838103835286818151815260200191508051906020019080838360005b838110156118aa57808201518184015260208101905061188f565b50505050905090810190601f1680156118d75780820380516001836020036101000a031916815260200191505b50838103825285818151815260200191508051906020019080838360005b838110156119105780820151818401526020810190506118f5565b50505050905090810190601f16801561193d5780820380516001836020036101000a031916815260200191505b50965050505050505060405180910390a3505050505050565b60025481565b600360009054906101000a900460ff1681565b62278d0081565b61afc881565b6212750081565b3073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614611a07576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526031815260200180611e896031913960400191505060405180910390fd5b61afc8811015611a62576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526034815260200180611cb46034913960400191505060405180910390fd5b62278d00811115611abe576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526038815260200180611ce86038913960400191505060405180910390fd5b806002819055506002547f948b1f6a42ee138b7e34058ba85a37f716d55ff25ff05a763f15bed6a04c8d2c60405160405180910390a250565b60046020528060005260406000206000915054906101000a900460ff1681565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600042905090565b600080828401905083811015611bc2576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b809150509291505056fe54696d656c6f636b3a3a657865637574655472616e73616374696f6e3a2043616c6c206d75737420636f6d652066726f6d2061646d696e2e54696d656c6f636b3a3a63616e63656c5472616e73616374696f6e3a2043616c6c206d75737420636f6d652066726f6d2061646d696e2e54696d656c6f636b3a3a657865637574655472616e73616374696f6e3a205472616e73616374696f6e206973207374616c652e54696d656c6f636b3a3a657865637574655472616e73616374696f6e3a205472616e73616374696f6e206861736e2774207375727061737365642074696d65206c6f636b2e54696d656c6f636b3a3a73657444656c61793a2044656c6179206d75737420657863656564206d696e696d756d2064656c61792e54696d656c6f636b3a3a73657444656c61793a2044656c6179206d757374206e6f7420657863656564206d6178696d756d2064656c61792e54696d656c6f636b3a3a657865637574655472616e73616374696f6e3a205472616e73616374696f6e206861736e2774206265656e207175657565642e54696d656c6f636b3a3a61636365707441646d696e3a2043616c6c206d75737420636f6d652066726f6d2070656e64696e6741646d696e2e54696d656c6f636b3a3a73657450656e64696e6741646d696e3a2043616c6c206d75737420636f6d652066726f6d2054696d656c6f636b2e54696d656c6f636b3a3a71756575655472616e73616374696f6e3a2043616c6c206d75737420636f6d652066726f6d2061646d696e2e54696d656c6f636b3a3a657865637574655472616e73616374696f6e3a205472616e73616374696f6e20657865637574696f6e2072657665727465642e54696d656c6f636b3a3a71756575655472616e73616374696f6e3a20457374696d6174656420657865637574696f6e20626c6f636b206d75737420736174697366792064656c61792e54696d656c6f636b3a3a73657444656c61793a2043616c6c206d75737420636f6d652066726f6d2054696d656c6f636b2ea265627a7a72315820f36873c2bcfd8a3f1c8711f81ece6a410babb59adb0826ffe74f42a4c9416d9d64736f6c63430005110032
{"success": true, "error": null, "results": {}}
true
null
{}
15
0x05b5db99f390aba70b444d394be25f6074d7ac5a
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; } } 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 Seed 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) { _totalSupply = 1000000 * 1e18; _name = "Seed"; _symbol = "SEED"; _decimals = 18; _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 _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 mint(address account, uint256 amount) external onlyOwner { _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } 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 _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 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; } } abstract contract ReentrancyGuard { bool private _entered; modifier noReentrancy() { require(!_entered); _entered = true; _; _entered = false; } } interface ISeedStake is IOwnershipTransferrable { event StakeIncreased(address indexed staker, uint256 amount); event StakeDecreased(address indexed staker, uint256 amount); event Rewards(address indexed staker, uint256 mintage, uint256 developerFund); event MelodyAdded(address indexed melody); event MelodyRemoved(address indexed melody); function seed() external returns (address); function totalStaked() external returns (uint256); function staked(address staker) external returns (uint256); function lastClaim(address staker) external returns (uint256); function addMelody(address melody) external; function removeMelody(address melody) external; function upgrade(address owned, address upgraded) external; } contract SeedDAO is ReentrancyGuard { using SafeMath for uint256; // Proposal fee of 10 SEED. Used to prevent spam uint256 constant PROPOSAL_FEE = 10 * 1e18; event NewProposal(uint64 indexed proposal); event FundProposed(uint64 indexed proposal, address indexed destination, uint256 amount); event MelodyAdditionProposed(uint64 indexed proposal, address melody); event MelodyRemovalProposed(uint64 indexed proposal, address melody); event StakeUpgradeProposed(uint64 indexed proposal, address newStake); event DAOUpgradeProposed(uint64 indexed proposal, address newDAO); event ProposalVoteAdded(uint64 indexed proposal, address indexed staker); event ProposalVoteRemoved(uint64 indexed proposal, address indexed staker); event ProposalPassed(uint64 indexed proposal); event ProposalRemoved(uint64 indexed proposal); enum ProposalType { Null, Fund, MelodyAddition, MelodyRemoval, StakeUpgrade, DAOUpgrade } struct ProposalMetadata { ProposalType pType; // Allows the creator to withdraw the proposal address creator; // Used to mark proposals older than 30 days as invalid uint256 submitted; // Stakers who voted yes mapping(address => bool) stakers; // Whether or not the proposal is completed // Stops it from being acted on multiple times bool completed; } // The info string is intended for an URL to describe the proposal struct FundProposal { address destination; uint256 amount; string info; } struct MelodyAdditionProposal { address melody; string info; } struct MelodyRemovalProposal { address melody; string info; } struct StakeUpgradeProposal { address newStake; // List of addresses owned by the Stake contract address[] owned; string info; } struct DAOUpgradeProposal { address newDAO; string info; } mapping(uint64 => ProposalMetadata) public proposals; mapping(uint64 => mapping(address => bool)) public used; mapping(uint64 => FundProposal) public _fundProposals; mapping(uint64 => MelodyAdditionProposal) public _melodyAdditionProposals; mapping(uint64 => MelodyRemovalProposal) public _melodyRemovalProposals; mapping(uint64 => StakeUpgradeProposal) public _stakeUpgradeProposals; mapping(uint64 => DAOUpgradeProposal) public _daoUpgradeProposals; // Address of the DAO we upgraded to address _upgrade; // ID to use for the next proposal uint64 _nextProposalID; ISeedStake private _stake; Seed private _SEED; // Check the proposal is valid modifier pendingProposal(uint64 proposal) { require(proposals[proposal].pType != ProposalType.Null); require(!proposals[proposal].completed); // Don't allow old proposals to suddenly be claimed require(proposals[proposal].submitted + 30 days > block.timestamp); _; } // Check this contract hasn't been replaced modifier active() { require(_upgrade == address(0)); _; } constructor(address stake) { _stake = ISeedStake(stake); _SEED = Seed(_stake.seed()); } function upgraded() external view returns (bool) { return _upgrade != address(0); } function upgrade() external view returns (address) { return _upgrade; } function stake() external view returns (address) { return address(_stake); } function _createNewProposal(ProposalType pType) internal active returns (uint64) { // Make sure this isn't spam by transferring the proposal fee require(_SEED.transferFrom(msg.sender, address(this), PROPOSAL_FEE)); // Increment the next proposal ID now // Means we don't have to return a value we subtract one from later _nextProposalID += 1; emit NewProposal(_nextProposalID); // Set up the proposal's metadata ProposalMetadata storage meta = proposals[_nextProposalID]; meta.pType = pType; meta.creator = msg.sender; meta.submitted = block.timestamp; // Automatically vote for the proposal's creator meta.stakers[msg.sender] = true; emit ProposalVoteAdded(_nextProposalID, msg.sender); return _nextProposalID; } function proposeFund(address destination, uint256 amount, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.Fund); _fundProposals[proposalID] = FundProposal(destination, amount, info); emit FundProposed(proposalID, destination, amount); return proposalID; } function proposeMelodyAddition(address melody, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.MelodyAddition); _melodyAdditionProposals[proposalID] = MelodyAdditionProposal(melody, info); emit MelodyAdditionProposed(proposalID, melody); return proposalID; } function proposeMelodyRemoval(address melody, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.MelodyRemoval); _melodyRemovalProposals[proposalID] = MelodyRemovalProposal(melody, info); emit MelodyRemovalProposed(proposalID, melody); return proposalID; } function proposeStakeUpgrade(address newStake, address[] calldata owned, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.StakeUpgrade); // Ensure the SEED token was included as an owned contract for (uint i = 0; i < owned.length; i++) { if (owned[i] == address(_SEED)) { break; } require(i != owned.length - 1); } _stakeUpgradeProposals[proposalID] = StakeUpgradeProposal(newStake, owned, info); emit StakeUpgradeProposed(proposalID, newStake); return proposalID; } function proposeDAOUpgrade(address newDAO, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.DAOUpgrade); _daoUpgradeProposals[proposalID] = DAOUpgradeProposal(newDAO, info); emit DAOUpgradeProposed(proposalID, newDAO); return proposalID; } function addVote(uint64 proposalID) external active pendingProposal(proposalID) { proposals[proposalID].stakers[msg.sender] = true; emit ProposalVoteAdded(proposalID, msg.sender); } function removeVote(uint64 proposalID) external active pendingProposal(proposalID) { proposals[proposalID].stakers[msg.sender] = false; emit ProposalVoteRemoved(proposalID, msg.sender); } // Send the SEED held by this contract to what it upgraded to // Intended to enable a contract like the timelock, if transferred to this // Without this, it'd be trapped here, forever function forwardSEED() public { require(_upgrade != address(0)); require(_SEED.transfer(_upgrade, _SEED.balanceOf(address(this)))); } // Complete a proposal // Takes in a list of stakers so this contract doesn't have to track them all in an array // This would be extremely expensive as a stakers vote weight can drop to 0 // This selective process allows only counting meaningful votes function completeProposal(uint64 proposalID, address[] calldata stakers) external active pendingProposal(proposalID) noReentrancy { ProposalMetadata storage meta = proposals[proposalID]; uint256 requirement; // Only require a majority vote for a funding request/to remove a melody if ((meta.pType == ProposalType.Fund) || (meta.pType == ProposalType.MelodyRemoval)) { requirement = _stake.totalStaked().div(2).add(1); // Require >66% to add a new melody // Adding an insecure or malicious melody will cause the staking pool to be drained } else if (meta.pType == ProposalType.MelodyAddition) { requirement = _stake.totalStaked().div(3).mul(2).add(1); // Require >80% to upgrade the stake/DAO contract // Upgrading to an insecure or malicious contract risks unlimited minting } else if ((meta.pType == ProposalType.StakeUpgrade) || (meta.pType == ProposalType.DAOUpgrade)) { requirement = _stake.totalStaked().div(5).mul(4).add(1); // Panic in case the enum is expanded and not properly handled here } else { require(false); } // Make sure there's enough vote weight behind this proposal uint256 votes = 0; for (uint i = 0; i < stakers.length; i++) { // Don't allow people to vote with flash loans if (_stake.lastClaim(stakers[i]) == block.timestamp) { continue; } require(meta.stakers[stakers[i]]); require(!used[proposalID][stakers[i]]); used[proposalID][stakers[i]] = true; votes = votes.add(_stake.staked(stakers[i])); } require(votes >= requirement); meta.completed = true; emit ProposalPassed(proposalID); if (meta.pType == ProposalType.Fund) { FundProposal memory proposal = _fundProposals[proposalID]; require(_SEED.transfer(proposal.destination, proposal.amount)); } else if (meta.pType == ProposalType.MelodyAddition) { _stake.addMelody(_melodyAdditionProposals[proposalID].melody); } else if (meta.pType == ProposalType.MelodyRemoval) { _stake.removeMelody(_melodyRemovalProposals[proposalID].melody); } else if (meta.pType == ProposalType.StakeUpgrade) { StakeUpgradeProposal memory proposal = _stakeUpgradeProposals[proposalID]; for (uint i = 0; i < proposal.owned.length; i++) { _stake.upgrade(proposal.owned[i], proposal.newStake); } // Register the new staking contract as a melody so it can move the funds over _stake.addMelody(address(proposal.newStake)); _stake = ISeedStake(proposal.newStake); } else if (meta.pType == ProposalType.DAOUpgrade) { _upgrade = _daoUpgradeProposals[proposalID].newDAO; _stake.transferOwnership(_upgrade); forwardSEED(); } else { require(false); } } // Voluntarily withdraw a proposal function withdrawProposal(uint64 proposalID) external active pendingProposal(proposalID) { require(proposals[proposalID].creator == msg.sender); proposals[proposalID].completed = true; emit ProposalRemoved(proposalID); } }
0x608060405234801561001057600080fd5b506004361061012c5760003560e01c80637e8de02e116100ad578063d55ec69711610071578063d55ec697146106c2578063d979c4aa146106ca578063da6aaeab146106f0578063df7400cb14610716578063eb1ea9c6146107945761012c565b80637e8de02e146105b657806380a5bdfb146105dc578063a76cf56e14610602578063c28de2cd14610628578063d37b7fa6146106445761012c565b8063433a5a69116100f4578063433a5a69146103a25780634c01cb57146103aa5780636bda20341461045857806371fb7cf11461050d5780637586d6ce146105905761012c565b8063198743561461013157806319db3f2a146101cb5780631d6ec3561461024b57806331c5eec8146103195780633a4b66f11461037e575b600080fd5b6101af6004803603604081101561014757600080fd5b6001600160a01b038235169190810190604081016020820135600160201b81111561017157600080fd5b82018360208201111561018357600080fd5b803590602001918460018302840111600160201b831117156101a457600080fd5b5090925090506107c9565b604080516001600160401b039092168252519081900360200190f35b610249600480360360408110156101e157600080fd5b6001600160401b038235169190810190604081016020820135600160201b81111561020b57600080fd5b82018360208201111561021d57600080fd5b803590602001918460208302840111600160201b8311171561023e57600080fd5b5090925090506108ca565b005b6101af6004803603606081101561026157600080fd5b6001600160a01b038235169190810190604081016020820135600160201b81111561028b57600080fd5b82018360208201111561029d57600080fd5b803590602001918460208302840111600160201b831117156102be57600080fd5b919390929091602081019035600160201b8111156102db57600080fd5b8201836020820111156102ed57600080fd5b803590602001918460018302840111600160201b8311171561030e57600080fd5b509092509050611403565b61033f6004803603602081101561032f57600080fd5b50356001600160401b03166115bb565b6040518085600581111561034f57fe5b81526001600160a01b039094166020850152506040808401929092521515606083015251908190036080019150f35b6103866115f2565b604080516001600160a01b039092168252519081900360200190f35b610249611601565b6103d0600480360360208110156103c057600080fd5b50356001600160401b0316611720565b60405180836001600160a01b0316815260200180602001828103825283818151815260200191508051906020019080838360005b8381101561041c578181015183820152602001610404565b50505050905090810190601f1680156104495780820380516001836020036101000a031916815260200191505b50935050505060405180910390f35b61047e6004803603602081101561046e57600080fd5b50356001600160401b03166117d4565b60405180846001600160a01b0316815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b838110156104d05781810151838201526020016104b8565b50505050905090810190601f1680156104fd5780820380516001836020036101000a031916815260200191505b5094505050505060405180910390f35b6101af6004803603606081101561052357600080fd5b6001600160a01b0382351691602081013591810190606081016040820135600160201b81111561055257600080fd5b82018360208201111561056457600080fd5b803590602001918460018302840111600160201b8311171561058557600080fd5b50909250905061188a565b610249600480360360208110156105a657600080fd5b50356001600160401b03166119a1565b610249600480360360208110156105cc57600080fd5b50356001600160401b0316611ac9565b6103d0600480360360208110156105f257600080fd5b50356001600160401b0316611bc9565b6102496004803603602081101561061857600080fd5b50356001600160401b0316611c48565b610630611d4d565b604080519115158252519081900360200190f35b6101af6004803603604081101561065a57600080fd5b6001600160a01b038235169190810190604081016020820135600160201b81111561068457600080fd5b82018360208201111561069657600080fd5b803590602001918460018302840111600160201b831117156106b757600080fd5b509092509050611d5e565b610386611e5f565b6103d0600480360360208110156106e057600080fd5b50356001600160401b0316611e6e565b6103d06004803603602081101561070657600080fd5b50356001600160401b0316611ee9565b6101af6004803603604081101561072c57600080fd5b6001600160a01b038235169190810190604081016020820135600160201b81111561075657600080fd5b82018360208201111561076857600080fd5b803590602001918460018302840111600160201b8311171561078957600080fd5b509092509050611f68565b610630600480360360408110156107aa57600080fd5b5080356001600160401b031690602001356001600160a01b0316612069565b6000806107d66003612089565b90506040518060400160405280866001600160a01b0316815260200185858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250506001600160401b0384168152600560209081526040909120835181546001600160a01b0319166001600160a01b039091161781558382015180519193506108789260018501929101906122db565b5050604080516001600160a01b038816815290516001600160401b03841692507f339826f1c3d7b31c2395903a0738e18e4c9463f3d6749d47e35a9feb2344e8db9181900360200190a2949350505050565b6008546001600160a01b0316156108e057600080fd5b8260006001600160401b03821660009081526001602052604090205460ff16600581111561090a57fe5b141561091557600080fd5b6001600160401b03811660009081526001602052604090206003015460ff161561093e57600080fd5b6001600160401b038116600090815260016020819052604090912001544262278d009091011161096d57600080fd5b60005460ff161561097d57600080fd5b6000805460ff1916600190811782556001600160401b03861682526020819052604082209190825460ff1660058111156109b357fe5b14806109ce57506003825460ff1660058111156109cc57fe5b145b15610a6c57610a656001610a5f6002600960009054906101000a90046001600160a01b03166001600160a01b031663817b1cd26040518163ffffffff1660e01b8152600401602060405180830381600087803b158015610a2d57600080fd5b505af1158015610a41573d6000803e3d6000fd5b505050506040513d6020811015610a5757600080fd5b505190612277565b9061229b565b9050610b7a565b6002825460ff166005811115610a7e57fe5b1415610ae957610a656001610a5f6002610ae36003600960009054906101000a90046001600160a01b03166001600160a01b031663817b1cd26040518163ffffffff1660e01b8152600401602060405180830381600087803b158015610a2d57600080fd5b906122b4565b6004825460ff166005811115610afb57fe5b1480610b1657506005825460ff166005811115610b1457fe5b145b1561012c57610a656001610a5f6004610ae36005600960009054906101000a90046001600160a01b03166001600160a01b031663817b1cd26040518163ffffffff1660e01b8152600401602060405180830381600087803b158015610a2d57600080fd5b6000805b85811015610dc55760095442906001600160a01b0316635c16e15e898985818110610ba557fe5b905060200201356001600160a01b03166040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b158015610bf457600080fd5b505af1158015610c08573d6000803e3d6000fd5b505050506040513d6020811015610c1e57600080fd5b50511415610c2b57610dbd565b836002016000888884818110610c3d57fe5b602090810292909201356001600160a01b03168352508101919091526040016000205460ff16610c6c57600080fd5b6001600160401b038816600090815260026020526040812090888884818110610c9157fe5b602090810292909201356001600160a01b03168352508101919091526040016000205460ff1615610cc157600080fd5b6001600160401b0388166000908152600260205260408120600191898985818110610ce857fe5b6001600160a01b0360209182029390930135831684528301939093526040909101600020805493151560ff199094169390931790925550600954610dba91166398807d84898985818110610d3857fe5b905060200201356001600160a01b03166040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b158015610d8757600080fd5b505af1158015610d9b573d6000803e3d6000fd5b505050506040513d6020811015610db157600080fd5b5051839061229b565b91505b600101610b7e565b5081811015610dd357600080fd5b60038301805460ff191660011790556040516001600160401b038816907f6085cc60943f0b976690a6f940d11a998d1a616c9469dc9196e763e342ca583f90600090a26001835460ff166005811115610e2857fe5b1415610f9f57610e36612359565b6001600160401b038816600090815260036020908152604091829020825160608101845281546001600160a01b03168152600180830154828501526002808401805487516101009482161594909402600019011691909104601f81018690048602830186018752808352929593949386019391929091830182828015610efd5780601f10610ed257610100808354040283529160200191610efd565b820191906000526020600020905b815481529060010190602001808311610ee057829003601f168201915b505050919092525050600a5482516020808501516040805163a9059cbb60e01b81526001600160a01b039485166004820152602481019290925251959650919092169363a9059cbb9350604480830193928290030181600087803b158015610f6457600080fd5b505af1158015610f78573d6000803e3d6000fd5b505050506040513d6020811015610f8e57600080fd5b5051610f9957600080fd5b506113f0565b6002835460ff166005811115610fb157fe5b141561103a576009546001600160401b038816600090815260046020819052604080832054815163791cbf9f60e11b81526001600160a01b0391821693810193909352905193169263f2397f3e9260248084019391929182900301818387803b15801561101d57600080fd5b505af1158015611031573d6000803e3d6000fd5b505050506113f0565b6003835460ff16600581111561104c57fe5b14156110b4576009546001600160401b0388166000908152600560205260408082205481516316d4489b60e11b81526001600160a01b0391821660048201529151931692632da891369260248084019391929182900301818387803b15801561101d57600080fd5b6004835460ff1660058111156110c657fe5b1415611341576110d4612383565b6001600160401b038816600090815260066020908152604091829020825160608101845281546001600160a01b031681526001820180548551818602810186019096528086529194929385810193929083018282801561115d57602002820191906000526020600020905b81546001600160a01b0316815260019091019060200180831161113f575b5050509183525050600282810180546040805160206001841615610100026000190190931694909404601f810183900483028501830190915280845293810193908301828280156111ef5780601f106111c4576101008083540402835291602001916111ef565b820191906000526020600020905b8154815290600101906020018083116111d257829003601f168201915b505050505081525050905060005b8160200151518110156112b157600954602083015180516001600160a01b03909216916399a88ec491908490811061123157fe5b602002602001015184600001516040518363ffffffff1660e01b815260040180836001600160a01b03168152602001826001600160a01b0316815260200192505050600060405180830381600087803b15801561128d57600080fd5b505af11580156112a1573d6000803e3d6000fd5b5050600190920191506111fd9050565b5060095481516040805163791cbf9f60e11b81526001600160a01b0392831660048201529051919092169163f2397f3e91602480830192600092919082900301818387803b15801561130257600080fd5b505af1158015611316573d6000803e3d6000fd5b50509151600980546001600160a01b0319166001600160a01b03909216919091179055506113f09050565b6005835460ff16600581111561135357fe5b141561012c576001600160401b03871660009081526007602052604080822054600880546001600160a01b0319166001600160a01b039283161790819055600954835163f2fde38b60e01b815291831660048301529251929091169263f2fde38b9260248084019382900301818387803b1580156113d057600080fd5b505af11580156113e4573d6000803e3d6000fd5b505050506113f0611601565b50506000805460ff191690555050505050565b6000806114106004612089565b905060005b8581101561147257600a546001600160a01b031687878381811061143557fe5b905060200201356001600160a01b03166001600160a01b0316141561145957611472565b600019860181141561146a57600080fd5b600101611415565b506040518060600160405280886001600160a01b03168152602001878780806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250505090825250604080516020601f88018190048102820181019092528681529181019190879087908190840183828082843760009201829052509390945250506001600160401b0384168152600660209081526040909120835181546001600160a01b0319166001600160a01b0390911617815583820151805191935061154b9260018501929101906123ad565b50604082015180516115679160028401916020909101906122db565b5050604080516001600160a01b038a16815290516001600160401b03841692507ffd08ecdf1b11b329fffd11e68af1d1f874ca2e56aa45a1e13065e6cc26373b2c9181900360200190a29695505050505050565b600160208190526000918252604090912080549181015460039091015460ff8084169361010090046001600160a01b031692911684565b6009546001600160a01b031690565b6008546001600160a01b031661161657600080fd5b600a54600854604080516370a0823160e01b815230600482015290516001600160a01b039384169363a9059cbb93169184916370a0823191602480820192602092909190829003018186803b15801561166e57600080fd5b505afa158015611682573d6000803e3d6000fd5b505050506040513d602081101561169857600080fd5b5051604080516001600160e01b031960e086901b1681526001600160a01b03909316600484015260248301919091525160448083019260209291908290030181600087803b1580156116e957600080fd5b505af11580156116fd573d6000803e3d6000fd5b505050506040513d602081101561171357600080fd5b505161171e57600080fd5b565b6004602090815260009182526040918290208054600180830180548651600261010094831615949094026000190190911692909204601f81018690048602830186019096528582526001600160a01b039092169492939092908301828280156117ca5780601f1061179f576101008083540402835291602001916117ca565b820191906000526020600020905b8154815290600101906020018083116117ad57829003601f168201915b5050505050905082565b60036020908152600091825260409182902080546001808301546002808501805488516101009582161595909502600019011691909104601f81018790048702840187019097528683526001600160a01b039093169590949192918301828280156118805780601f1061185557610100808354040283529160200191611880565b820191906000526020600020905b81548152906001019060200180831161186357829003601f168201915b5050505050905083565b6000806118976001612089565b90506040518060600160405280876001600160a01b0316815260200186815260200185858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250506001600160401b038416815260036020908152604091829020845181546001600160a01b0319166001600160a01b0390911617815584820151600182015591840151805192935061194b92600285019291909101906122db565b50506040805187815290516001600160a01b03891692506001600160401b038416917fc6befa0284988cf06a62f33e703b26fa8fe104aff100ff179eb9b02174018530919081900360200190a395945050505050565b6008546001600160a01b0316156119b757600080fd5b8060006001600160401b03821660009081526001602052604090205460ff1660058111156119e157fe5b14156119ec57600080fd5b6001600160401b03811660009081526001602052604090206003015460ff1615611a1557600080fd5b6001600160401b038116600090815260016020819052604090912001544262278d0090910111611a4457600080fd5b6001600160401b03821660009081526001602052604090205461010090046001600160a01b03163314611a7657600080fd5b6001600160401b0382166000818152600160208190526040808320600301805460ff1916909217909155517f9253f303ac7bc301d8f26a3c594cf868be86bee4afd53c746f29cc0103a4274f9190a25050565b6008546001600160a01b031615611adf57600080fd5b8060006001600160401b03821660009081526001602052604090205460ff166005811115611b0957fe5b1415611b1457600080fd5b6001600160401b03811660009081526001602052604090206003015460ff1615611b3d57600080fd5b6001600160401b038116600090815260016020819052604090912001544262278d0090910111611b6c57600080fd5b6001600160401b0382166000818152600160209081526040808320338085526002909101909252808320805460ff19169055519092917f55b02b9855e513ee8f9281215332c8cf0f8304cadcdca4e1b3910609797103e691a35050565b6005602090815260009182526040918290208054600180830180548651600261010094831615949094026000190190911692909204601f81018690048602830186019096528582526001600160a01b039092169492939092908301828280156117ca5780601f1061179f576101008083540402835291602001916117ca565b6008546001600160a01b031615611c5e57600080fd5b8060006001600160401b03821660009081526001602052604090205460ff166005811115611c8857fe5b1415611c9357600080fd5b6001600160401b03811660009081526001602052604090206003015460ff1615611cbc57600080fd5b6001600160401b038116600090815260016020819052604090912001544262278d0090910111611ceb57600080fd5b6001600160401b0382166000818152600160208181526040808420338086526002909101909252808420805460ff191690931790925590519092917fc7442600edbdac0b51781946ea453c6ec64fba32dc76e7e711cbe79a15ec5fec91a35050565b6008546001600160a01b0316151590565b600080611d6b6002612089565b90506040518060400160405280866001600160a01b0316815260200185858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250506001600160401b0384168152600460209081526040909120835181546001600160a01b0319166001600160a01b03909116178155838201518051919350611e0d9260018501929101906122db565b5050604080516001600160a01b038816815290516001600160401b03841692507f29cd6c86b51064508c60d447e776b80d8c6f25603856be845b6a2abe192a00779181900360200190a2949350505050565b6008546001600160a01b031690565b60066020908152600091825260409182902080546002808301805486516101006001831615026000190190911692909204601f81018690048602830186019096528582526001600160a01b039092169492939092908301828280156117ca5780601f1061179f576101008083540402835291602001916117ca565b6007602090815260009182526040918290208054600180830180548651600261010094831615949094026000190190911692909204601f81018690048602830186019096528582526001600160a01b039092169492939092908301828280156117ca5780601f1061179f576101008083540402835291602001916117ca565b600080611f756005612089565b90506040518060400160405280866001600160a01b0316815260200185858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250506001600160401b0384168152600760209081526040909120835181546001600160a01b0319166001600160a01b039091161781558382015180519193506120179260018501929101906122db565b5050604080516001600160a01b038816815290516001600160401b03841692507f29ff7ec46662ba30200783e0d6cbe17047c2ab7058785f9d441e8b21a88e25749181900360200190a2949350505050565b600260209081526000928352604080842090915290825290205460ff1681565b6008546000906001600160a01b0316156120a257600080fd5b600a54604080516323b872dd60e01b8152336004820152306024820152678ac7230489e80000604482015290516001600160a01b03909216916323b872dd916064808201926020929091908290030181600087803b15801561210357600080fd5b505af1158015612117573d6000803e3d6000fd5b505050506040513d602081101561212d57600080fd5b505161213857600080fd5b600880546001600160401b03600160a01b80830482166001018216810267ffffffffffffffff60a01b19909316929092179283905560405191909204909116907fe1c41d4ba86fb17ee8e9f88a333876ca22e0d2940c46a544405bb18a6b932a5c90600090a2600854600160a01b90046001600160401b03166000908152600160208190526040909120805490918491839160ff19909116908360058111156121dd57fe5b02179055508054610100600160a81b031916336101008102919091178255426001808401919091556000828152600284016020526040808220805460ff19169093179092556008549151600160a01b9092046001600160401b0316917fc7442600edbdac0b51781946ea453c6ec64fba32dc76e7e711cbe79a15ec5fec9190a35050600854600160a01b90046001600160401b0316919050565b600080821161228557600080fd5b600082848161229057fe5b049150505b92915050565b6000828201838110156122ad57600080fd5b9392505050565b6000826122c357506000612295565b828202828482816122d057fe5b04146122ad57600080fd5b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061231c57805160ff1916838001178555612349565b82800160010185558215612349579182015b8281111561234957825182559160200191906001019061232e565b5061235592915061240e565b5090565b604051806060016040528060006001600160a01b0316815260200160008152602001606081525090565b604051806060016040528060006001600160a01b0316815260200160608152602001606081525090565b828054828255906000526020600020908101928215612402579160200282015b8281111561240257825182546001600160a01b0319166001600160a01b039091161782556020909201916001909101906123cd565b50612355929150612423565b5b80821115612355576000815560010161240f565b5b808211156123555780546001600160a01b031916815560010161242456fea26469706673582212203b1c0d178642e512cac49570aeb1cc34fd0c49b1f5798a5074df852c1c0d648364736f6c63430007000033
{"success": true, "error": null, "results": {"detectors": [{"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}]}
16
0x05Fcc72CFb4150AbAE415c885f7a433Ff523296F
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 YOK is CappedToken { string public name = "YOKcoin"; string public symbol = "YOK"; uint8 public decimals = 18; constructor( uint256 _cap ) public CappedToken( _cap ) { } }
0x6080604052600436106100fb5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166305d2035b811461010057806306fdde0314610129578063095ea7b3146101b357806318160ddd146101d757806323b872dd146101fe578063313ce56714610228578063355274ea1461025357806340c10f1914610268578063661884631461028c57806370a08231146102b0578063715018a6146102d15780637d64bcb4146102e85780638da5cb5b146102fd57806395d89b411461032e578063a9059cbb14610343578063d73dd62314610367578063dd62ed3e1461038b578063f2fde38b146103b2575b600080fd5b34801561010c57600080fd5b506101156103d3565b604080519115158252519081900360200190f35b34801561013557600080fd5b5061013e6103f4565b6040805160208082528351818301528351919283929083019185019080838360005b83811015610178578181015183820152602001610160565b50505050905090810190601f1680156101a55780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156101bf57600080fd5b50610115600160a060020a0360043516602435610482565b3480156101e357600080fd5b506101ec6104e8565b60408051918252519081900360200190f35b34801561020a57600080fd5b50610115600160a060020a03600435811690602435166044356104ee565b34801561023457600080fd5b5061023d610663565b6040805160ff9092168252519081900360200190f35b34801561025f57600080fd5b506101ec61066c565b34801561027457600080fd5b50610115600160a060020a0360043516602435610672565b34801561029857600080fd5b50610115600160a060020a03600435166024356106a8565b3480156102bc57600080fd5b506101ec600160a060020a0360043516610797565b3480156102dd57600080fd5b506102e66107b2565b005b3480156102f457600080fd5b50610115610820565b34801561030957600080fd5b506103126108c6565b60408051600160a060020a039092168252519081900360200190f35b34801561033a57600080fd5b5061013e6108d5565b34801561034f57600080fd5b50610115600160a060020a0360043516602435610930565b34801561037357600080fd5b50610115600160a060020a0360043516602435610a0f565b34801561039757600080fd5b506101ec600160a060020a0360043581169060243516610aa8565b3480156103be57600080fd5b506102e6600160a060020a0360043516610ad3565b60035474010000000000000000000000000000000000000000900460ff1681565b6005805460408051602060026001851615610100026000190190941693909304601f8101849004840282018401909252818152929183018282801561047a5780601f1061044f5761010080835404028352916020019161047a565b820191906000526020600020905b81548152906001019060200180831161045d57829003601f168201915b505050505081565b336000818152600260209081526040808320600160a060020a038716808552908352818420869055815186815291519394909390927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925928290030190a350600192915050565b60015490565b600160a060020a03831660009081526020819052604081205482111561051357600080fd5b600160a060020a038416600090815260026020908152604080832033845290915290205482111561054357600080fd5b600160a060020a038316151561055857600080fd5b600160a060020a038416600090815260208190526040902054610581908363ffffffff610af616565b600160a060020a0380861660009081526020819052604080822093909355908516815220546105b6908363ffffffff610b0816565b600160a060020a038085166000908152602081815260408083209490945591871681526002825282812033825290915220546105f8908363ffffffff610af616565b600160a060020a03808616600081815260026020908152604080832033845282529182902094909455805186815290519287169391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929181900390910190a35060019392505050565b60075460ff1681565b60045481565b600060045461068c83600154610b0890919063ffffffff16565b111561069757600080fd5b6106a18383610b1b565b9392505050565b336000908152600260209081526040808320600160a060020a03861684529091528120548083106106fc57336000908152600260209081526040808320600160a060020a0388168452909152812055610731565b61070c818463ffffffff610af616565b336000908152600260209081526040808320600160a060020a03891684529091529020555b336000818152600260209081526040808320600160a060020a0389168085529083529281902054815190815290519293927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35060019392505050565b600160a060020a031660009081526020819052604090205490565b600354600160a060020a031633146107c957600080fd5b600354604051600160a060020a03909116907ff8df31144d9c2f0f6b59d69b8b98abd5459d07f2742c4df920b25aae33c6482090600090a26003805473ffffffffffffffffffffffffffffffffffffffff19169055565b600354600090600160a060020a0316331461083a57600080fd5b60035474010000000000000000000000000000000000000000900460ff161561086257600080fd5b6003805474ff00000000000000000000000000000000000000001916740100000000000000000000000000000000000000001790556040517fae5184fba832cb2b1f702aca6117b8d265eaf03ad33eb133f19dde0f5920fa0890600090a150600190565b600354600160a060020a031681565b6006805460408051602060026001851615610100026000190190941693909304601f8101849004840282018401909252818152929183018282801561047a5780601f1061044f5761010080835404028352916020019161047a565b3360009081526020819052604081205482111561094c57600080fd5b600160a060020a038316151561096157600080fd5b33600090815260208190526040902054610981908363ffffffff610af616565b3360009081526020819052604080822092909255600160a060020a038516815220546109b3908363ffffffff610b0816565b600160a060020a038416600081815260208181526040918290209390935580518581529051919233927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a350600192915050565b336000908152600260209081526040808320600160a060020a0386168452909152812054610a43908363ffffffff610b0816565b336000818152600260209081526040808320600160a060020a0389168085529083529281902085905580519485525191937f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929081900390910190a350600192915050565b600160a060020a03918216600090815260026020908152604080832093909416825291909152205490565b600354600160a060020a03163314610aea57600080fd5b610af381610c36565b50565b600082821115610b0257fe5b50900390565b81810182811015610b1557fe5b92915050565b600354600090600160a060020a03163314610b3557600080fd5b60035474010000000000000000000000000000000000000000900460ff1615610b5d57600080fd5b600154610b70908363ffffffff610b0816565b600155600160a060020a038316600090815260208190526040902054610b9c908363ffffffff610b0816565b600160a060020a03841660008181526020818152604091829020939093558051858152905191927f0f6798a560793a54c3bcfe86a93cde1e73087d944c0ea20544137d412139688592918290030190a2604080518381529051600160a060020a038516916000917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a350600192915050565b600160a060020a0381161515610c4b57600080fd5b600354604051600160a060020a038084169216907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a36003805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a03929092169190911790555600a165627a7a723058209e2614877db18568276400ee173695b3e3edcdcae9592b208b7ebcd9ec9e95af0029
{"success": true, "error": null, "results": {}}
true
null
{}
17
0x0689aa2234d06Ac0d04cdac874331d287aFA4B43
pragma solidity 0.6.5; abstract contract Proxy { // /////////////////////// EVENTS /////////////////////////////////////////////////////////////////////////// event ProxyImplementationUpdated( address indexed previousImplementation, address indexed newImplementation ); // /////////////////////// CONSTRUCTOR ////////////////////////////////////////////////////////////////////// function _setImplementation(address newImplementation, bytes memory data) internal { address previousImplementation; // solhint-disable-next-line security/no-inline-assembly assembly { previousImplementation := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) } // solhint-disable-next-line security/no-inline-assembly assembly { sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, newImplementation ) } emit ProxyImplementationUpdated( previousImplementation, newImplementation ); if (data.length > 0) { (bool success, ) = newImplementation.delegatecall(data); if (!success) { assembly { // This assembly ensure the revert contains the exact string data let returnDataSize := returndatasize() returndatacopy(0, 0, returnDataSize) revert(0, returnDataSize) } } } } // ///////////////////// EXTERNAL /////////////////////////////////////////////////////////////////////////// receive() external payable { _fallback(); } fallback() external payable { _fallback(); } // ///////////////////////// INTERNAL ////////////////////////////////////////////////////////////////////// function _fallback() internal { // solhint-disable-next-line security/no-inline-assembly assembly { let implementationAddress := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( gas(), implementationAddress, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } contract TransparentProxy is Proxy { // /////////////////////// CONSTRUCTOR ////////////////////////////////////////////////////////////////////// constructor( address implementationAddress, bytes memory data, address adminAddress ) public { _setImplementation(implementationAddress, data); _setAdmin(adminAddress); } // ///////////////////// EXTERNAL /////////////////////////////////////////////////////////////////////////// function changeImplementation( address newImplementation, bytes calldata data ) external ifAdmin { _setImplementation(newImplementation, data); } function proxyAdmin() external ifAdmin returns (address) { return _admin(); } // Transfer of adminship on the other hand is only visible to the admin of the Proxy function changeProxyAdmin(address newAdmin) external ifAdmin { uint256 disabled; // solhint-disable-next-line security/no-inline-assembly assembly { disabled := sload( 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6102 ) } require(disabled == 0, "changeAdmin has been disabled"); _setAdmin(newAdmin); } // to be used if EIP-173 needs to be implemented in the implementation contract so that change of admin can be constrained // in a way that OwnershipTransfered is trigger all the time function disableChangeProxyAdmin() external ifAdmin { // solhint-disable-next-line security/no-inline-assembly assembly { sstore( 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6102, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ) } } // /////////////////////// MODIFIERS //////////////////////////////////////////////////////////////////////// modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } // ///////////////////////// INTERNAL ////////////////////////////////////////////////////////////////////// function _admin() internal view returns (address adminAddress) { // solhint-disable-next-line security/no-inline-assembly assembly { adminAddress := sload( 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103 ) } } function _setAdmin(address newAdmin) internal { // solhint-disable-next-line security/no-inline-assembly assembly { sstore( 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103, newAdmin ) } } }
0x6080604052600436106100435760003560e01c8063037998cc1461005a578063311241711461006f5780633e47158c146100fc5780639f712f2f1461012d57610052565b3661005257610050610160565b005b610050610160565b34801561006657600080fd5b506100506101ab565b34801561007b57600080fd5b506100506004803603604081101561009257600080fd5b6001600160a01b0382351691908101906040810160208201356401000000008111156100bd57600080fd5b8201836020820111156100cf57600080fd5b803590602001918460018302840111640100000000831117156100f157600080fd5b50909250905061021e565b34801561010857600080fd5b50610111610291565b604080516001600160a01b039092168252519081900360200190f35b34801561013957600080fd5b506100506004803603602081101561015057600080fd5b50356001600160a01b03166102ce565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5460003681823780813683855af43d92508282833e8080156101a1578383f35b8383fd5b50505050565b6101b3610398565b6001600160a01b0316336001600160a01b03161415610214577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61025561021c565b61021c610160565b565b610226610398565b6001600160a01b0316336001600160a01b031614156102845761027f8383838080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506103bd92505050565b61028c565b61028c610160565b505050565b600061029b610398565b6001600160a01b0316336001600160a01b031614156102c3576102bc610398565b90506102cb565b6102cb610160565b90565b6102d6610398565b6001600160a01b0316336001600160a01b0316141561038d577fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d610254801561037e57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f6368616e676541646d696e20686173206265656e2064697361626c6564000000604482015290519081900360640190fd5b610387826104f7565b50610395565b610395610160565b50565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc8054908390556040516001600160a01b0380851691908316907f5570d70a002632a7b0b3c9304cc89efb62d8da9eca0dbd7752c83b737906829690600090a381511561028c576000836001600160a01b0316836040518082805190602001908083835b6020831061047e57805182527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe09092019160209182019101610441565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d80600081146104de576040519150601f19603f3d011682016040523d82523d6000602084013e6104e3565b606091505b50509050806101a5573d806000803e806000fd5b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035556fea2646970667358221220f2becd045ded4fe5025cd5ba8ac214cc35de3919d80166a8938d0b546117f6e964736f6c63430006050033
{"success": true, "error": null, "results": {"detectors": [{"check": "controlled-delegatecall", "impact": "High", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'controlled-delegatecall', 'impact': 'High', 'confidence': 'Medium'}]}
18
0x06b7dbc16e445054386b01894eba31819b71d261
pragma solidity 0.4.19; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; // ��mapping����ÿ����ַ��Ӧ����� mapping (address => uint256) public balanceOf; // �洢���˺ŵĿ��� mapping (address => mapping (address => uint256)) public allowance; // �¼�������֪ͨ�ͻ��˽��׷��� event Transfer(address indexed from, address indexed to, uint256 value); // �¼�������֪ͨ�ͻ��˴��ұ����� event Burn(address indexed from, uint256 value); /* *��ʼ������ */ function TokenERC20(uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply * 10 ** uint256(decimals); // ��Ӧ�ķݶ�ݶ����С�Ĵ��ҵ�λ�йأ��ݶ� = �� balanceOf[msg.sender] = totalSupply; // ������ӵ�����еĴ��� name = tokenName; // �������� symbol = tokenSymbol; // ���ҷ��� } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; // ��mapping����ÿ����ַ��Ӧ����� mapping (address => uint256) public balanceOf; // �洢���˺ŵĿ��� mapping (address => mapping (address => uint256)) public allowance; // �¼�������֪ͨ�ͻ��˽��׷��� event Transfer(address indexed from, address indexed to, uint256 value); // �¼�������֪ͨ�ͻ��˴��ұ����� event Burn(address indexed from, uint256 value); /* *��ʼ������ */ function TokenERC20(uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply * 10 ** uint256(decimals); // ��Ӧ�ķݶ�ݶ����С�Ĵ��ҵ�λ�йأ��ݶ� = �� balanceOf[msg.sender] = totalSupply; // ������ӵ�����еĴ��� name = tokenName; // �������� symbol = tokenSymbol; // ���ҷ��� } //���ҽ���ת�Ƶ��ڲ�ʵ�� function _transfer(address _from, address _to, uint _value) internal { // ȷ��Ŀ���ַ��Ϊ0x0����Ϊ0x0��ַ�������� require(_to != 0x0); // ��鷢������� require(balanceOf[_from] >= _value); // ȷ��ת��Ϊ������ require(balanceOf[_to] + _value > balanceOf[_to]); // ����������齻�ף� uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // ��assert���������߼��� assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /***** **���ҽ���ת�� **���Լ������������ߣ��˺ŷ���`_value`�����ҵ� `_to`�˺� **@param _to �����ߵ�ַ **@param _value ת������ **/ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /***** **�˺�֮����ҽ���ת�� **@param _from �����ߵ�ַ **@param _to �����ߵ�ַ **@param _value ת������ **/ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /***** **����ij����ַ����Լ�����Դ������������廨�ѵĴ����� **���������`_spender` ���Ѳ����� `_value` ������ **@param _spender The address authorized to spend **@param _value the max amount they can spend **/ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /***** **��������һ����ַ����Լ�����ң����������ߣ����������໨�ѵĴ����� **@param _spender ����Ȩ�ĵ�ַ����Լ�� **@param _value ���ɻ��Ѵ����� **@param _extraData ���͸���Լ�ĸ������� **/ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { // ֪ͨ��Լ spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } ///�����ң����������ߣ��˻���ָ�������� function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /***** **�����û��˻���ָ�������� **Remove `_value` tokens from the system irreversibly on behalf of `_from **@param _from the address of the sender **@param _value the amount of money to burn **/ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } } pragma solidity ^0.4.19; contract Token { /// token������Ĭ�ϻ�Ϊpublic��������һ��getter�����ӿڣ�����ΪtotalSupply(). uint256 public totalSupply; /// ��ȡ�˻�_ownerӵ��token������ function balanceOf(address _owner) constant returns (uint256 balance); //����Ϣ�������˻�����_to�˻�ת����Ϊ_value��token function transfer(address _to, uint256 _value) returns (bool success); //���˻�_from�����˻�_toת����Ϊ_value��token����approve�������ʹ�� function transferFrom(address _from, address _to, uint256 _value) returns (bool success); //��Ϣ�����˻������˻�_spender�ܴӷ����˻���ת������Ϊ_value��token function approve(address _spender, uint256 _value) returns (bool success); //��ȡ�˻�_spender���Դ��˻�_owner��ת��token������ function allowance(address _owner, address _spender) constant returns (uint256 remaining); //����ת��ʱ����Ҫ�������¼� event Transfer(address indexed _from, address indexed _to, uint256 _value); alue)�ɹ�ִ��ʱ���봥�����¼� event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
0x6060604052600436106100ba576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100bf578063095ea7b31461014d57806318160ddd146101a757806323b872dd146101d0578063313ce5671461024957806342966c681461027857806370a08231146102b357806379cc67901461030057806395d89b411461035a578063a9059cbb146103e8578063cae9ca511461042a578063dd62ed3e146104c7575b600080fd5b34156100ca57600080fd5b6100d2610533565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101125780820151818401526020810190506100f7565b50505050905090810190601f16801561013f5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561015857600080fd5b61018d600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919080359060200190919050506105d1565b604051808215151515815260200191505060405180910390f35b34156101b257600080fd5b6101ba61065e565b6040518082815260200191505060405180910390f35b34156101db57600080fd5b61022f600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610664565b604051808215151515815260200191505060405180910390f35b341561025457600080fd5b61025c610791565b604051808260ff1660ff16815260200191505060405180910390f35b341561028357600080fd5b61029960048080359060200190919050506107a4565b604051808215151515815260200191505060405180910390f35b34156102be57600080fd5b6102ea600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108a8565b6040518082815260200191505060405180910390f35b341561030b57600080fd5b610340600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919080359060200190919050506108c0565b604051808215151515815260200191505060405180910390f35b341561036557600080fd5b61036d610ada565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156103ad578082015181840152602081019050610392565b50505050905090810190601f1680156103da5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34156103f357600080fd5b610428600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610b78565b005b341561043557600080fd5b6104ad600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091905050610b87565b604051808215151515815260200191505060405180910390f35b34156104d257600080fd5b61051d600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610d05565b6040518082815260200191505060405180910390f35b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156105c95780601f1061059e576101008083540402835291602001916105c9565b820191906000526020600020905b8154815290600101906020018083116105ac57829003601f168201915b505050505081565b600081600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506001905092915050565b60035481565b6000600560008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482111515156106f157600080fd5b81600560008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282540392505081905550610786848484610d2a565b600190509392505050565b600260009054906101000a900460ff1681565b600081600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054101515156107f457600080fd5b81600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282540392505081905550816003600082825403925050819055503373ffffffffffffffffffffffffffffffffffffffff167fcc16f5dbb4873280815c1ee09dbd06736cffcc184412cf7a71a0fdb75d397ca5836040518082815260200191505060405180910390a260019050919050565b60046020528060005260406000206000915090505481565b600081600460008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015151561091057600080fd5b600560008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054821115151561099b57600080fd5b81600460008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600560008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282540392505081905550816003600082825403925050819055508273ffffffffffffffffffffffffffffffffffffffff167fcc16f5dbb4873280815c1ee09dbd06736cffcc184412cf7a71a0fdb75d397ca5836040518082815260200191505060405180910390a26001905092915050565b60018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610b705780601f10610b4557610100808354040283529160200191610b70565b820191906000526020600020905b815481529060010190602001808311610b5357829003601f168201915b505050505081565b610b83338383610d2a565b5050565b600080849050610b9785856105d1565b15610cfc578073ffffffffffffffffffffffffffffffffffffffff16638f4ffcb1338630876040518563ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018481526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001828103825283818151815260200191508051906020019080838360005b83811015610c91578082015181840152602081019050610c76565b50505050905090810190601f168015610cbe5780820380516001836020036101000a031916815260200191505b5095505050505050600060405180830381600087803b1515610cdf57600080fd5b6102c65a03f11515610cf057600080fd5b50505060019150610cfd565b5b509392505050565b6005602052816000526040600020602052806000526040600020600091509150505481565b6000808373ffffffffffffffffffffffffffffffffffffffff1614151515610d5157600080fd5b81600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410151515610d9f57600080fd5b600460008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205401111515610e2d57600080fd5b600460008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205401905081600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600460008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a380600460008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054600460008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020540114151561103a57fe5b505050505600a165627a7a723058205afd85f9be3edb8cf6bbbd5b634538ffb32586e74b5870ed991c8fa8927695680029
{"success": true, "error": null, "results": {"detectors": [{"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "name-reused", "impact": "High", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'name-reused', 'impact': 'High', 'confidence': 'High'}]}
19
0x071911fA06AB97447D644eE4d5BCFdD63C1081a0
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 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; } interface IERC1820Implementer { /** * @dev Returns a special value (`ERC1820_ACCEPT_MAGIC`) if this contract * implements `interfaceHash` for `account`. * * See {IERC1820Registry-setInterfaceImplementer}. */ function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32); } 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 IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } interface PodInterface { function tokenToCollateralValue(uint256 tokens) external view returns (uint256); function balanceOfUnderlying(address user) external view returns (uint256); } 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 MigrateV2ToV3 is OwnableUpgradeSafe, IERC777Recipient, IERC1820Implementer { IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 constant private _ERC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC")); // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; event ReceivedTokens(address token, address from, uint256 amount); IERC777 public poolDaiToken; IERC777 public poolUsdcToken; MixedPodInterface public poolDaiPod; MixedPodInterface public poolUsdcPod; IERC20 public v3Token; constructor ( IERC777 _poolDaiToken, IERC777 _poolUsdcToken, MixedPodInterface _poolDaiPod, MixedPodInterface _poolUsdcPod, IERC20 _v3Token ) public { poolDaiToken = _poolDaiToken; poolUsdcToken = _poolUsdcToken; poolDaiPod = _poolDaiPod; poolUsdcPod = _poolUsdcPod; v3Token = _v3Token; // register interfaces ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); __Ownable_init(); } function tokensReceived( address, address from, address to, uint256 amount, bytes calldata, bytes calldata ) external override { require(to == address(this), "MigrateV2ToV3/only-tokens"); if (msg.sender == address(poolDaiToken)) { v3Token.transfer(from, amount); } else if (msg.sender == address(poolUsdcToken)) { v3Token.transfer(from, amount * 1e12); } else if (msg.sender == address(poolDaiPod)) { uint256 collateral = poolDaiPod.tokenToCollateralValue(amount); v3Token.transfer(from, collateral); } else if (msg.sender == address(poolUsdcPod)) { uint256 collateral = poolUsdcPod.tokenToCollateralValue(amount); v3Token.transfer(from, collateral * 1e12); } else { revert("MigrateV2ToV3/unknown-token"); } emit ReceivedTokens(msg.sender, from, amount); } function withdrawERC777(IERC777 token) external onlyOwner { uint256 amount = token.balanceOf(address(this)); token.send(msg.sender, amount, ""); } function withdrawERC20(IERC20 token) external onlyOwner { uint256 amount = token.balanceOf(address(this)); token.transfer(msg.sender, amount); } function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external override view returns (bytes32) { if (account == address(this) && interfaceHash == TOKENS_RECIPIENT_INTERFACE_HASH) { return _ERC1820_ACCEPT_MAGIC; } else { return bytes32(0x00); } } } interface MixedPodInterface is IERC777, PodInterface { }
0x608060405234801561001057600080fd5b50600436106100b35760003560e01c8063715018a611610071578063715018a61461023c5780638da5cb5b14610244578063bf5486f61461024c578063da52e52e14610254578063f2fde38b1461025c578063f4f3b20014610282576100b3565b806223de29146100b857806310b25362146101a45780631b771bd6146101c8578063249cb3fa146101d05780634761f9d81461020e57806363d190fa14610216575b600080fd5b6101a2600480360360c08110156100ce57600080fd5b6001600160a01b03823581169260208101358216926040820135909216916060820135919081019060a08101608082013564010000000081111561011157600080fd5b82018360208201111561012357600080fd5b8035906020019184600183028401116401000000008311171561014557600080fd5b91939092909160208101903564010000000081111561016357600080fd5b82018360208201111561017557600080fd5b8035906020019184600183028401116401000000008311171561019757600080fd5b5090925090506102a8565b005b6101ac6106ad565b604080516001600160a01b039092168252519081900360200190f35b6101ac6106bc565b6101fc600480360360408110156101e657600080fd5b50803590602001356001600160a01b03166106cb565b60408051918252519081900360200190f35b6101ac610758565b6101a26004803603602081101561022c57600080fd5b50356001600160a01b0316610767565b6101a26108b5565b6101ac610957565b6101ac610966565b6101ac610975565b6101a26004803603602081101561027257600080fd5b50356001600160a01b0316610984565b6101a26004803603602081101561029857600080fd5b50356001600160a01b0316610a7d565b6001600160a01b0386163014610305576040805162461bcd60e51b815260206004820152601960248201527f4d6967726174655632546f56332f6f6e6c792d746f6b656e7300000000000000604482015290519081900360640190fd5b6097546001600160a01b03163314156103a057609b546040805163a9059cbb60e01b81526001600160a01b038a81166004830152602482018990529151919092169163a9059cbb9160448083019260209291908290030181600087803b15801561036e57600080fd5b505af1158015610382573d6000803e3d6000fd5b505050506040513d602081101561039857600080fd5b5061065b9050565b6098546001600160a01b031633141561040f57609b546040805163a9059cbb60e01b81526001600160a01b038a8116600483015264e8d4a51000890260248301529151919092169163a9059cbb9160448083019260209291908290030181600087803b15801561036e57600080fd5b6099546001600160a01b0316331415610525576099546040805163d67d7a7d60e01b81526004810188905290516000926001600160a01b03169163d67d7a7d916024808301926020929190829003018186803b15801561046e57600080fd5b505afa158015610482573d6000803e3d6000fd5b505050506040513d602081101561049857600080fd5b5051609b546040805163a9059cbb60e01b81526001600160a01b038c8116600483015260248201859052915193945091169163a9059cbb916044808201926020929091908290030181600087803b1580156104f257600080fd5b505af1158015610506573d6000803e3d6000fd5b505050506040513d602081101561051c57600080fd5b5061065b915050565b609a546001600160a01b031633141561060e57609a546040805163d67d7a7d60e01b81526004810188905290516000926001600160a01b03169163d67d7a7d916024808301926020929190829003018186803b15801561058457600080fd5b505afa158015610598573d6000803e3d6000fd5b505050506040513d60208110156105ae57600080fd5b5051609b546040805163a9059cbb60e01b81526001600160a01b038c8116600483015264e8d4a5100085026024830152915193945091169163a9059cbb916044808201926020929091908290030181600087803b1580156104f257600080fd5b6040805162461bcd60e51b815260206004820152601b60248201527f4d6967726174655632546f56332f756e6b6e6f776e2d746f6b656e0000000000604482015290519081900360640190fd5b604080513381526001600160a01b038916602082015280820187905290517fbd878faa248cebecbb044cc9fd6294f16e5afe7fc344c69ffb1931f90f636fcd9181900360600190a15050505050505050565b6097546001600160a01b031681565b609a546001600160a01b031681565b60006001600160a01b0382163014801561070457507fb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b83145b1561074e57604051602001808073455243313832305f4143434550545f4d4147494360601b8152506014019050604051602081830303815290604052805190602001209050610752565b5060005b92915050565b609b546001600160a01b031681565b61076f610bd3565b6065546001600160a01b039081169116146107bf576040805162461bcd60e51b81526020600482018190526024820152600080516020610bfe833981519152604482015290519081900360640190fd5b6000816001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b15801561080e57600080fd5b505afa158015610822573d6000803e3d6000fd5b505050506040513d602081101561083857600080fd5b505160408051634decdde360e11b8152336004820152602481018390526060604482015260006064820181905291519293506001600160a01b03851692639bd9bbc69260a48084019391929182900301818387803b15801561089957600080fd5b505af11580156108ad573d6000803e3d6000fd5b505050505050565b6108bd610bd3565b6065546001600160a01b0390811691161461090d576040805162461bcd60e51b81526020600482018190526024820152600080516020610bfe833981519152604482015290519081900360640190fd5b6065546040516000916001600160a01b0316907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3606580546001600160a01b0319169055565b6065546001600160a01b031690565b6098546001600160a01b031681565b6099546001600160a01b031681565b61098c610bd3565b6065546001600160a01b039081169116146109dc576040805162461bcd60e51b81526020600482018190526024820152600080516020610bfe833981519152604482015290519081900360640190fd5b6001600160a01b038116610a215760405162461bcd60e51b8152600401808060200182810382526026815260200180610bd86026913960400191505060405180910390fd5b6065546040516001600160a01b038084169216907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a3606580546001600160a01b0319166001600160a01b0392909216919091179055565b610a85610bd3565b6065546001600160a01b03908116911614610ad5576040805162461bcd60e51b81526020600482018190526024820152600080516020610bfe833981519152604482015290519081900360640190fd5b6000816001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015610b2457600080fd5b505afa158015610b38573d6000803e3d6000fd5b505050506040513d6020811015610b4e57600080fd5b50516040805163a9059cbb60e01b81523360048201526024810183905290519192506001600160a01b0384169163a9059cbb916044808201926020929091908290030181600087803b158015610ba357600080fd5b505af1158015610bb7573d6000803e3d6000fd5b505050506040513d6020811015610bcd57600080fd5b50505050565b339056fe4f776e61626c653a206e6577206f776e657220697320746865207a65726f20616464726573734f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572a2646970667358221220c7cccafc59e48a20f65067a86095f0e11de34da347e27fe8c83fde59a25a221b64736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}]}
20
0x0728e0023699186D5693Bb8e7e762B9972B3852E
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)) ); } }
0x6080604052600436106100345760003560e01c80630b63fb62146100395780635ef010201461005b57806368cfb7231461006e575b600080fd5b34801561004557600080fd5b506100596100543660046107cb565b610081565b005b6100596100693660046106fe565b6100f3565b61005961007c3660046106a4565b610431565b6040516305b1fdb160e11b8152735ef30b9986345249bc32d8928b7ee64de9435e3990630b63fb62906100bc9086908690869060040161096d565b600060405180830381600087803b1580156100d657600080fd5b505af11580156100ea573d6000803e3d6000fd5b50505050505050565b3460021461011c5760405162461bcd60e51b8152600401610113906108d6565b60405180910390fd5b6040516323b872dd60e01b815273a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48906323b872dd9061015790339030908a90600401610882565b602060405180830381600087803b15801561017157600080fd5b505af1158015610185573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101a9919061078c565b6101c55760405162461bcd60e51b81526004016101139061092b565b85806101d6576101d3610608565b90505b6040516305b1fdb160e11b8152735ef30b9986345249bc32d8928b7ee64de9435e3990630b63fb62906102129084908e9060019060040161096d565b600060405180830381600087803b15801561022c57600080fd5b505af1158015610240573d6000803e3d6000fd5b505060405163095ea7b360e01b815273a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48925063095ea7b3915061027d908d908a906004016108a6565b602060405180830381600087803b15801561029757600080fd5b505af11580156102ab573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102cf919061078c565b6102eb5760405162461bcd60e51b8152600401610113906108f4565b604051636424576960e11b81526001600160a01b038b169063c848aed29034906103259033908e908e9088908e908e908e90600401610841565b6000604051808303818588803b15801561033e57600080fd5b505af1158015610352573d6000803e3d6000fd5b50506040516305b1fdb160e11b8152735ef30b9986345249bc32d8928b7ee64de9435e399350630b63fb629250610393915084908e9060009060040161096d565b600060405180830381600087803b1580156103ad57600080fd5b505af11580156103c1573d6000803e3d6000fd5b5050604051637c54448160e01b81526001600160a01b0386169250637c54448191506103f3908490869060040161098c565b600060405180830381600087803b15801561040d57600080fd5b505af1158015610421573d6000803e3d6000fd5b5050505050505050505050505050565b346002146104515760405162461bcd60e51b8152600401610113906108d6565b6040516305b1fdb160e11b8152735ef30b9986345249bc32d8928b7ee64de9435e3990630b63fb629061048d908590899060019060040161096d565b600060405180830381600087803b1580156104a757600080fd5b505af11580156104bb573d6000803e3d6000fd5b50506040516368cfb72360e01b81526001600160a01b03881692506368cfb723915034906104f5903390899089908990899060040161080d565b6000604051808303818588803b15801561050e57600080fd5b505af1158015610522573d6000803e3d6000fd5b50506040516305b1fdb160e11b8152735ef30b9986345249bc32d8928b7ee64de9435e399350630b63fb62925061056391508590899060009060040161096d565b600060405180830381600087803b15801561057d57600080fd5b505af1158015610591573d6000803e3d6000fd5b5050604051631f95f98d60e31b8152735ef30b9986345249bc32d8928b7ee64de9435e39925063fcafcc6891506105cf9085906001906004016108bf565b600060405180830381600087803b1580156105e957600080fd5b505af11580156105fd573d6000803e3d6000fd5b505050505050505050565b604051636090dec560e01b8152600090735ef30b9986345249bc32d8928b7ee64de9435e3990636090dec59061064d9065555344432d4160d01b9030906004016108bf565b602060405180830381600087803b15801561066757600080fd5b505af115801561067b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061069f91906107b3565b905090565b600080600080600060a086880312156106bb578081fd5b85356106c68161099a565b945060208601356106d68161099a565b935060408601356106e68161099a565b94979396509394606081013594506080013592915050565b60008060008060008060008060006101208a8c03121561071c578384fd5b89356107278161099a565b985060208a01356107378161099a565b975060408a01356107478161099a565b965060608a0135955060808a0135945060a08a0135935060c08a0135925060e08a01356107738161099a565b809250506101008a013590509295985092959850929598565b60006020828403121561079d578081fd5b815180151581146107ac578182fd5b9392505050565b6000602082840312156107c4578081fd5b5051919050565b6000806000606084860312156107df578283fd5b8335925060208401356001600160a01b03811681146107fc578283fd5b929592945050506040919091013590565b6001600160a01b03958616815293851660208501529190931660408301526060820192909252608081019190915260a00190565b6001600160a01b03978816815295871660208701529390951660408501526060840191909152608083015260a082019290925260c081019190915260e00190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b03929092168252602082015260400190565b9182526001600160a01b0316602082015260400190565b6020808252600490820152632166656560e01b604082015260600190565b6020808252601d908201527f696e697469616c2d6d617267696e2d617070726f76652d6661696c6564000000604082015260600190565b60208082526022908201527f696e697469616c2d6d617267696e2d7472616e7366657246726f6d2d6661696c604082015261195960f21b606082015260800190565b9283526001600160a01b03919091166020830152604082015260600190565b918252602082015260400190565b6001600160a01b03811681146109af57600080fd5b5056fea2646970667358221220430c8fb40cd3841ae9486025eac13abdaa121151d208ba0cafd6f62d80f8226064736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}]}
21
0x088e1CC70fc731FBEE06d1eA41890F481552Bd99
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 ExternalInitializer { event LogExternalInitialize(bytes data); function initialize(bytes calldata data) external; } 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 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 LibConstants { // Durations for time locked mechanisms (in seconds). // Note that it is known that miners can manipulate block timestamps // up to a deviation of a few seconds. // This mechanism should not be used for fine grained timing. // The time required to cancel a deposit, in the case the operator does not move the funds // to the off-chain storage. uint256 public constant DEPOSIT_CANCEL_DELAY = 1 days; // The time required to freeze the exchange, in the case the operator does not execute a // requested full withdrawal. uint256 public constant FREEZE_GRACE_PERIOD = 7 days; // The time after which the exchange may be unfrozen after it froze. This should be enough time // for users to perform escape hatches to get back their funds. uint256 public constant UNFREEZE_DELAY = 365 days; // Maximal number of verifiers which may co-exist. uint256 public constant MAX_VERIFIER_COUNT = uint256(64); // The time required to remove a verifier in case of a verifier upgrade. uint256 public constant VERIFIER_REMOVAL_DELAY = FREEZE_GRACE_PERIOD + (21 days); uint256 constant MAX_VAULT_ID = 2**31 - 1; uint256 constant MAX_QUANTUM = 2**128 - 1; address constant ZERO_ADDRESS = address(0x0); uint256 constant K_MODULUS = 0x800000000000011000000000000000000000000000000000000000000000001; uint256 constant K_BETA = 0x6f21413efbe40de150e596d72f7a8c5609ad26c15c915c1f4cdfcb99cee9e89; uint256 constant EXPIRATION_TIMESTAMP_BITS = 22; uint256 internal constant MASK_250 = 0x03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; uint256 internal constant MASK_240 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; uint256 internal constant MINTABLE_ASSET_ID_FLAG = 1<<250; } 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 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 ChangeVerifiersExternalInitializer is ExternalInitializer, MainStorage, LibConstants { using Addresses for address; uint256 constant ENTRY_NOT_FOUND = uint256(~0); /* The initiatialize function gets four parameters in the bytes array: 1. New verifier address, 2. Keccak256 of the expected verifier id. 3. New availability verifier address, 4. Keccak256 of the expected availability verifier id. */ function initialize(bytes calldata data) external { require(data.length == 128, "UNEXPECTED_DATA_SIZE"); address newVerifierAddress; bytes32 verifierIdHash; address newAvailabilityVerifierAddress; bytes32 availabilityVerifierIdHash; // Extract sub-contract address and hash of verifierId. ( newVerifierAddress, verifierIdHash, newAvailabilityVerifierAddress, availabilityVerifierIdHash ) = abi.decode(data, (address, bytes32, address, bytes32)); // Flush the entire verifiers list. delete verifiersChain.list; delete availabilityVerifiersChain.list; // ApprovalChain addEntry performs all the required checks for us. addEntry(verifiersChain, newVerifierAddress, MAX_VERIFIER_COUNT, verifierIdHash); addEntry( availabilityVerifiersChain, newAvailabilityVerifierAddress, MAX_VERIFIER_COUNT, availabilityVerifierIdHash); emit LogExternalInitialize(data); } /* The functions below are taken from ApprovalChain.sol, with minor changes: 1. No governance needed (we are under the context where proxy governance is granted). 2. The verifier ID is passed as hash, and not as string. */ function addEntry( StarkExTypes.ApprovalChainData storage chain, address entry, uint256 maxLength, bytes32 hashExpectedId) internal { address[] storage list = chain.list; require(entry.isContract(), "ADDRESS_NOT_CONTRACT"); bytes32 hashRealId = keccak256(abi.encodePacked(Identity(entry).identify())); require(hashRealId == hashExpectedId, "UNEXPECTED_CONTRACT_IDENTIFIER"); require(list.length < maxLength, "CHAIN_AT_MAX_CAPACITY"); require(findEntry(list, entry) == ENTRY_NOT_FOUND, "ENTRY_ALREADY_EXISTS"); chain.list.push(entry); chain.unlockedForRemovalTime[entry] = 0; } function findEntry(address[] storage list, address entry) internal view returns (uint256) { uint256 n_entries = list.length; for (uint256 i = 0; i < n_entries; i++) { if (list[i] == entry) { return i; } } return ENTRY_NOT_FOUND; } }
0x608060405234801561001057600080fd5b50600436106100615760003560e01c806271754214610066578063439fab911461008057806377e84e0d146100f0578063993f3639146100f8578063b766311214610100578063e6de628214610108575b600080fd5b61006e610110565b60408051918252519081900360200190f35b6100ee6004803603602081101561009657600080fd5b810190602081018135600160201b8111156100b057600080fd5b8201836020820111156100c257600080fd5b803590602001918460018302840111600160201b831117156100e357600080fd5b509092509050610117565b005b61006e610239565b61006e610240565b61006e610248565b61006e61024f565b62093a8081565b60808114610163576040805162461bcd60e51b8152602060048201526014602482015273554e45585045435445445f444154415f53495a4560601b604482015290519081900360640190fd5b6000806000808585608081101561017957600080fd5b506001600160a01b038135811695506020820135945060408201351692506060013590506101a9601960006105e7565b6101b5601b60006105e7565b6101c3601985604086610254565b6101d1601b83604084610254565b7fcd1400d214c673d845a60be61e4392df27be94360484e7da79f75c0222550615868660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a1505050505050565b6201518081565b6301e1338081565b6224ea0081565b604081565b836102676001600160a01b038516610582565b6102af576040805162461bcd60e51b8152602060048201526014602482015273105111149154d4d7d393d517d0d3d395149050d560621b604482015290519081900360640190fd5b6000846001600160a01b031663eeb728666040518163ffffffff1660e01b815260040160006040518083038186803b1580156102ea57600080fd5b505afa1580156102fe573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052602081101561032757600080fd5b8101908080516040519392919084600160201b82111561034657600080fd5b90830190602082018581111561035b57600080fd5b8251600160201b81118282018810171561037457600080fd5b82525081516020918201929091019080838360005b838110156103a1578181015183820152602001610389565b50505050905090810190601f1680156103ce5780820380516001836020036101000a031916815260200191505b506040525050506040516020018082805190602001908083835b602083106104075780518252601f1990920191602091820191016103e8565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051602081830303815290604052805190602001209050828114610498576040805162461bcd60e51b815260206004820152601e60248201527f554e45585045435445445f434f4e54524143545f4944454e5449464945520000604482015290519081900360640190fd5b815484116104e5576040805162461bcd60e51b8152602060048201526015602482015274434841494e5f41545f4d41585f434150414349545960581b604482015290519081900360640190fd5b6000196104f28387610588565b1461053b576040805162461bcd60e51b8152602060048201526014602482015273454e5452595f414c52454144595f45584953545360601b604482015290519081900360640190fd5b50508354600181810186556000868152602080822090930180546001600160a01b039097166001600160a01b03199097168717905594855290940190935250604081205550565b3b151590565b8154600090815b818110156105d957836001600160a01b03168582815481106105ad57fe5b6000918252602090912001546001600160a01b031614156105d15791506105e19050565b60010161058f565b506000199150505b92915050565b50805460008255906000526020600020908101906106059190610608565b50565b61062691905b80821115610622576000815560010161060e565b5090565b9056fea265627a7a72315820925885939d633a4e48d41346dac5c5ca2c4b9fb47143a9dc758a0d21d9a2f58464736f6c634300050f0032
{"success": true, "error": null, "results": {"detectors": [{"check": "controlled-array-length", "impact": "High", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'controlled-array-length', 'impact': 'High', 'confidence': 'Medium'}]}
22
0x089f0be0354f47d005e3871299cddfdfffdbe5e6
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); } contract TokenSetsV2Adapter is ProtocolAdapter { string public constant override adapterType = "Asset"; string public constant override tokenType = "SetToken V2"; /** * @return Amount of SetTokens held by the given account. * @param token Address of the SetToken contract. * @dev Implementation of ProtocolAdapter interface function. */ function getBalance(address token, address account) external view override returns (uint256) { return ERC20(token).balanceOf(account); } }
0x608060405234801561001057600080fd5b50600436106100415760003560e01c806330fa738c14610046578063d4fac45d14610064578063f72c079114610084575b600080fd5b61004e61008c565b60405161005b919061023d565b60405180910390f35b6100776100723660046101d0565b6100c5565b60405161005b91906102ae565b61004e610173565b6040518060400160405280600b81526020017f536574546f6b656e20563200000000000000000000000000000000000000000081525081565b6040517f70a0823100000000000000000000000000000000000000000000000000000000815260009073ffffffffffffffffffffffffffffffffffffffff8416906370a082319061011a90859060040161021c565b60206040518083038186803b15801561013257600080fd5b505afa158015610146573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061016a9190610204565b90505b92915050565b6040518060400160405280600581526020017f417373657400000000000000000000000000000000000000000000000000000081525081565b803573ffffffffffffffffffffffffffffffffffffffff8116811461016d57600080fd5b600080604083850312156101e2578182fd5b6101ec84846101ac565b91506101fb84602085016101ac565b90509250929050565b600060208284031215610215578081fd5b5051919050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b6000602080835283518082850152825b818110156102695785810183015185820160400152820161024d565b8181111561027a5783604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b9081526020019056fea2646970667358221220775d5b211466359bfcaae24bf21fc0d85ad51ae2ac6e6a1d6426a593ffa1396b64736f6c63430006050033
{"success": true, "error": null, "results": {}}
true
null
{}
23
0x08ca538F87668521472e805b4642681ee297ee2b
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; // service fee divider address user; // user to check special fee 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 DFSPrices 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( DFSExchangeData.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); } bytes memory packedData = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); 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, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_createData, _exchangeData); } } 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); uint256 globalBorrowAmount = 0; { // avoid stack too deep // 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)); globalBorrowAmount = borrowAmount; } // payback on behalf of user if (borrowToken != ETH_ADDR) { ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } else { DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(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 = 0x7b856af5753a9f80968EA002641E69AdF1d795aB; 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); exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // 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.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 DFSExchangeCore, 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 { (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData)); CloseData memory closeData = CloseData({ cdpId: closeDataSent.cdpId, collAmount: closeDataSent.collAmount, daiAmount: closeDataSent.daiAmount, minAccepted: closeDataSent.minAccepted, joinAddr: closeDataSent.joinAddr, proxy: proxy, flFee: _fee, toDai: closeDataSent.toDai, reserve: _reserve, amount: _amount }); address user = DSProxy(payable(closeData.proxy)).owner(); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = user; 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; if (_closeData.toDai) { _exchangeData.srcAmount = drawnAmount; (, daiSwaped) = _sell(_exchangeData); } else { _exchangeData.destAmount = _closeData.daiAmount; (, daiSwaped) = _buy(_exchangeData); } 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 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, DFSExchangeCore) 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( DFSExchangeData.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); bytes memory packedData = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); 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, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_closeData, _exchangeData); } } contract MCDCreateFlashLoan is DFSExchangeCore, 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"); (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData)); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxy(payable(proxy)).owner(); openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, 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 { (, 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 ); } } /// @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, DFSExchangeCore) payable {} } contract MCDSaverProxy is DFSExchangeCore, 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( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address user = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(_cdpId, ilk, daiAmount, user); // 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, user, _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( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address user = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, 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, user, _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 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); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); uint balance = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (feeAmount > _amount / 10) { feeAmount = _amount / 10; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); return feeAmount; } return 0; } } contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0xD0eB57ff3eA4Def2b74dc29681fd529D1611880f; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( 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( 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); } } } 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 DFSExchangeCore, CompBalance { 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 COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; 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.dfsFeeDivider = 400; // 0.25% exchangeData.srcAmount = compBalance; (, depositAmount) = _sell(exchangeData); // if we have no deposit after, send back tokens to the user if (_cDepositAddr == address(0)) { if (exchangeData.destAddr != ETH_ADDRESS) { ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount); } else { msg.sender.transfer(address(this).balance); } } } // 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 deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } 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); // Swap _exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, 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, user, _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); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint paybackAmount) = _sell(_exchangeData); paybackAmount -= takeFee(_saverData.gasCost, paybackAmount); 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, user, _exchangeData.srcAmount, paybackAmount)); } /// @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, DFSExchangeCore) 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); } } }
0x6080604052600436106100e85760003560e01c8063481c6a751161008a578063c759d07011610059578063c759d07014610211578063cf786f8f1461017a578063ed20210914610226578063f24ccbfe1461018f576100e8565b8063481c6a75146101d2578063520e9e85146101e75780636738929f14610118578063a59a9973146101fc576100e8565b806331d98b3f116100c657806331d98b3f1461014d57806336569e771461017a57806339df18781461018f5780634115fe6b146101a4576100e8565b80632a4c0a1a146100ed5780632e77468d146101185780632f634a901461012d575b600080fd5b3480156100f957600080fd5b50610102610246565b60405161010f919061164d565b60405180910390f35b34801561012457600080fd5b5061010261025e565b34801561013957600080fd5b5061010261014836600461133f565b610276565b34801561015957600080fd5b5061016d61016836600461130f565b610372565b60405161010f9190611717565b34801561018657600080fd5b50610102610530565b34801561019b57600080fd5b50610102610548565b3480156101b057600080fd5b506101c46101bf36600461136a565b610560565b60405161010f929190611872565b3480156101de57600080fd5b5061010261077c565b6101fa6101f53660046113cb565b610794565b005b34801561020857600080fd5b50610102610c92565b34801561021d57600080fd5b50610102610caa565b34801561023257600080fd5b5061016d610241366004611523565b610cc2565b736b175474e89094c44da98b954eedeac495271d0f81565b7365c79fcb50ca1594b025960e539ed7a9a6d434a381565b600080836001600160a01b0316638161b120846040518263ffffffff1660e01b81526004016102a59190611717565b60206040518083038186803b1580156102bd57600080fd5b505afa1580156102d1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102f591906112ec565b9050806001600160a01b0316638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b15801561033057600080fd5b505afa158015610344573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061036891906112ec565b9150505b92915050565b604051636cb1c69b60e11b815260009081907365c79fcb50ca1594b025960e539ed7a9a6d434a39063d9638d36906103ae908690600401611717565b604080518083038186803b1580156103c557600080fd5b505afa1580156103d9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103fd919061139e565b604051636cb1c69b60e11b8152909250600091507335d1b3f3d7966a1dfe207aa4514c12a259a0492b9063d9638d369061043b908790600401611717565b60a06040518083038186803b15801561045357600080fd5b505afa158015610467573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061048b9190611567565b505092505050610528610522827365c79fcb50ca1594b025960e539ed7a9a6d434a36001600160a01b031663495d32cb6040518163ffffffff1660e01b815260040160206040518083038186803b1580156104e557600080fd5b505afa1580156104f9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061051d9190611327565b610daa565b83610daa565b949350505050565b7335d1b3f3d7966a1dfe207aa4514c12a259a0492b81565b735c55b921f590a89c1ebe84df170e655a82b6212681565b6000806000856001600160a01b03166336569e776040518163ffffffff1660e01b815260040160206040518083038186803b15801561059e57600080fd5b505afa1580156105b2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105d691906112ec565b90506000866001600160a01b0316632726b073876040518263ffffffff1660e01b81526004016106069190611717565b60206040518083038186803b15801561061e57600080fd5b505afa158015610632573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061065691906112ec565b9050600080836001600160a01b0316632424be5c88856040518363ffffffff1660e01b8152600401610689929190611720565b604080518083038186803b1580156106a057600080fd5b505afa1580156106b4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106d89190611544565b915091506000846001600160a01b031663d9638d36896040518263ffffffff1660e01b815260040161070a9190611717565b60a06040518083038186803b15801561072257600080fd5b505afa158015610736573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061075a9190611567565b5050509150508261076b8383610daa565b965096505050505050935093915050565b735ef30b9986345249bc32d8928b7ee64de9435e3981565b6040516001600160a01b038216903480156108fc02916000818181858888f193505050501580156107c9573d6000803e3d6000fd5b508160a0015115610a26578151604051632726b07360e01b815261098b917335d1b3f3d7966a1dfe207aa4514c12a259a0492b91735ef30b9986345249bc32d8928b7ee64de9435e3991632726b073916108269190600401611717565b60206040518083038186803b15801561083e57600080fd5b505afa158015610852573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061087691906112ec565b8451604051632726b07360e01b8152735ef30b9986345249bc32d8928b7ee64de9435e3991632726b073916108ae9190600401611717565b60206040518083038186803b1580156108c657600080fd5b505afa1580156108da573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108fe91906112ec565b8551604051632c2cb9fd60e01b8152735ef30b9986345249bc32d8928b7ee64de9435e3991632c2cb9fd916109369190600401611717565b60206040518083038186803b15801561094e57600080fd5b505afa158015610962573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109869190611327565b610deb565b60608301528151604051632c2cb9fd60e01b8152610a1f91735ef30b9986345249bc32d8928b7ee64de9435e39918290632c2cb9fd906109cf908490600401611717565b60206040518083038186803b1580156109e757600080fd5b505afa1580156109fb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101bf9190611327565b5060408301525b81516040516305b1fdb160e11b8152735ef30b9986345249bc32d8928b7ee64de9435e3991630b63fb6291610a6391908590600190600401611853565b600060405180830381600087803b158015610a7d57600080fd5b505af1158015610a91573d6000803e3d6000fd5b505050506060610aa18385610fce565b905060603082604051602001610ab89291906116f3565b60408051601f19818403018152908290526060860151632e7ff4ef60e11b835290925073398ec7346dcd622edc5ae82352f02be94c62d11991635cffe9de91610b1d918791736b175474e89094c44da98b954eedeac495271d0f918790600401611661565b600060405180830381600087803b158015610b3757600080fd5b505af1158015610b4b573d6000803e3d6000fd5b505085516040516305b1fdb160e11b8152735ef30b9986345249bc32d8928b7ee64de9435e399350630b63fb629250610b8c91908790600090600401611853565b600060405180830381600087803b158015610ba657600080fd5b505af1158015610bba573d6000803e3d6000fd5b50505050610be073c45d4f6b6bf41b6edaa58b01c4298b8d9078269a8560000151610ffa565b735c55b921f590a89c1ebe84df170e655a82b621266001600160a01b031663d061ce5030338760000151886040015189606001518a60c00151604051602001610c2c9493929190611880565b6040516020818303038152906040526040518463ffffffff1660e01b8152600401610c599392919061169e565b600060405180830381600087803b158015610c7357600080fd5b505af1158015610c87573d6000803e3d6000fd5b505050505050505050565b73398ec7346dcd622edc5ae82352f02be94c62d11981565b73c45d4f6b6bf41b6edaa58b01c4298b8d9078269a81565b600080610cce83610372565b604051636cb1c69b60e11b81529091506000907365c79fcb50ca1594b025960e539ed7a9a6d434a39063d9638d3690610d0b908790600401611717565b604080518083038186803b158015610d2257600080fd5b505afa158015610d36573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d5a919061139e565b915050600080610d7f735ef30b9986345249bc32d8928b7ee64de9435e398888610560565b91509150610d9f610d99610d9384876110e7565b8561110f565b8261112f565b979650505050505050565b60006b033b2e3c9fd0803ce8000000610ddc610dc6858561113f565b60026b033b2e3c9fd0803ce80000005b04611163565b81610de357fe5b049392505050565b600080856001600160a01b031663d9638d36846040518263ffffffff1660e01b8152600401610e1a9190611717565b60a06040518083038186803b158015610e3257600080fd5b505afa158015610e46573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e6a9190611567565b5050509150506000866001600160a01b0316632424be5c85876040518363ffffffff1660e01b8152600401610ea0929190611720565b604080518083038186803b158015610eb757600080fd5b505afa158015610ecb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610eef9190611544565b9150506000876001600160a01b0316636c25b346886040518263ffffffff1660e01b8152600401610f20919061164d565b60206040518083038186803b158015610f3857600080fd5b505afa158015610f4c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f709190611327565b90506000610f87610f81848661113f565b8361112f565b90506b033b2e3c9fd0803ce80000008104945080610fb1866b033b2e3c9fd0803ce800000061113f565b10610fbc5784610fc1565b846001015b9998505050505050505050565b60608282604051602001610fe3929190611737565b604051602081830303815290604052905092915050565b604051633783408560e11b81526000906001600160a01b03841690636f06810a90611029908590600401611717565b6040805180830381600087803b15801561104257600080fd5b505af1158015611056573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061107a91906114f4565b91505080156110e25760405163ad0b27fb60e01b81526001600160a01b0384169063ad0b27fb906110af908590600401611717565b600060405180830381600087803b1580156110c957600080fd5b505af11580156110dd573d6000803e3d6000fd5b505050505b505050565b6000670de0b6b3a7640000610ddc6110ff858561113f565b6002670de0b6b3a7640000610dd6565b600081610ddc61112785670de0b6b3a764000061113f565b600285610dd6565b8082038281111561036c57600080fd5b600081158061115a5750508082028282828161115757fe5b04145b61036c57600080fd5b8082018281101561036c57600080fd5b803561036c816118c4565b600082601f83011261118e578081fd5b813567ffffffffffffffff8111156111a4578182fd5b6111b7601f8201601f191660200161189d565b91508082528360208285010111156111ce57600080fd5b8060208401602084013760009082016020015292915050565b600060e082840312156111f8578081fd5b61120260e061189d565b9050813581526020820135611216816118c4565b8060208301525060408201356040820152606082013560608201526080820135608082015260a0820135611249816118dc565b60a082015260c082013561125c816118dc565b60c082015292915050565b600060a08284031215611278578081fd5b61128260a061189d565b9050813561128f816118c4565b8152602082013561129f816118c4565b806020830152506040820135604082015260608201356060820152608082013567ffffffffffffffff8111156112d457600080fd5b6112e08482850161117e565b60808301525092915050565b6000602082840312156112fd578081fd5b8151611308816118c4565b9392505050565b600060208284031215611320578081fd5b5035919050565b600060208284031215611338578081fd5b5051919050565b60008060408385031215611351578081fd5b823561135c816118c4565b946020939093013593505050565b60008060006060848603121561137e578081fd5b8335611389816118c4565b95602085013595506040909401359392505050565b600080604083850312156113b0578182fd5b82516113bb816118c4565b6020939093015192949293505050565b60008060006101208085870312156113e1578384fd5b843567ffffffffffffffff808211156113f8578586fd5b818701915061014080838a03121561140e578687fd5b6114178161189d565b90506114238984611173565b81526114328960208501611173565b602082015260408301356040820152606083013560608201526080830135608082015260a083013560a082015261146c8960c08501611173565b60c082015261147e8960e08501611173565b60e08201526101008084013583811115611496578889fd5b6114a28b82870161117e565b828401525084840135838111156114b7578889fd5b6114c38b828701611267565b86840152508197506114d88a60208b016111e7565b96506114e68a828b01611173565b955050505050509250925092565b60008060408385031215611506578182fd5b825191506020830151611518816118dc565b809150509250929050565b60008060408385031215611535578182fd5b50508035926020909101359150565b60008060408385031215611556578182fd5b505080516020909101519092909150565b600080600080600060a0868803121561157e578283fd5b5050835160208501516040860151606087015160809097015192989197509594509092509050565b6001600160a01b03169052565b15159052565b60008151808452815b818110156115de576020818501810151868301820152016115c2565b818111156115ef5782602083870101525b50601f01601f19169290920160200192915050565b600060018060a01b03808351168452806020840151166020850152506040820151604084015260608201516060840152608082015160a0608085015261036860a08501826115b9565b6001600160a01b0391909116815260200190565b6001600160a01b0385811682528416602082015260408101839052608060608201819052600090611694908301846115b9565b9695505050505050565b6001600160a01b03848116825283166020820152608060408201819052600890820152674d4344436c6f736560c01b60a082015260c0606082018190526000906116ea908301846115b9565b95945050505050565b6001600160a01b0383168152604060208201819052600090610528908301846115b9565b90815260200190565b9182526001600160a01b0316602082015260400190565b600061010084518352602085015161175260208501826115a6565b5060408501516040840152606085015160608401526080850151608084015260a085015161178360a08501826115b3565b5060c085015161179660c08501826115b3565b508060e08401526117aa81840185516115a6565b60208401516101206117be818601836115a6565b6040860151915061014082818701526060870151610160870152608087015161018087015260a08701516101a087015260c087015192506118036101c08701846115a6565b60e087015192506118186101e08701846115a6565b928601516102008601939093526118336102408601846115b9565b9086015185820360ff190161022087015290925090506116948282611604565b9283526001600160a01b03919091166020830152604082015260600190565b918252602082015260400190565b938452602084019290925260408301521515606082015260800190565b60405181810167ffffffffffffffff811182821017156118bc57600080fd5b604052919050565b6001600160a01b03811681146118d957600080fd5b50565b80151581146118d957600080fdfea264697066735822122016e8859e6b1e324b39b6202cfd4c0fe3b6dca1bac39a4d8aa2bb1930451350cf64736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "tx-origin", "impact": "Medium", "confidence": "Medium"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "name-reused", "impact": "High", "confidence": "High"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-lowlevel", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'tx-origin', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'name-reused', 'impact': 'High', 'confidence': 'High'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-lowlevel', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
24
0x091d57812a7D26405Da9b74C85d23A5a24d63f83
pragma solidity 0.5.16; contract AufStaking2 { string public name = "Auf Staking phase 2"; address public owner; AufToken public aufToken; address[] public stakers; mapping(address => uint) public stakingBalance; mapping(address => bool) public hasStaked; mapping(address => bool) public isStaking; constructor(AufToken _aufToken) public { aufToken = _aufToken; owner = msg.sender; } function stakeTokens(uint _amount) public { // Require amount greater than 0 require(_amount > 0, "amount cannot be 0"); // Trasnfer Auf tokens to this contract for staking aufToken.transferFrom(msg.sender, address(this), _amount); // Update staking balance stakingBalance[msg.sender] = stakingBalance[msg.sender] + _amount; // Add user to stakers array *only* if they haven't staked already if(!hasStaked[msg.sender]) { stakers.push(msg.sender); } // Update staking status isStaking[msg.sender] = true; hasStaked[msg.sender] = true; } // Unstaking Tokens (Withdraw) function unstakeTokens() public { // Fetch staking balance uint balance = stakingBalance[msg.sender]; // Require amount greater than 0 require(balance > 0, "staking balance cannot be 0"); // Transfer Auf tokens to this contract for staking aufToken.transfer(msg.sender, balance); // Reset staking balance stakingBalance[msg.sender] = 0; // Update staking status isStaking[msg.sender] = false; } // Issuing Tokens function issueTokens() public { // Only owner can call this function require(msg.sender == owner, "caller must be the owner"); // Issue tokens to all stakers for (uint i=0; i<stakers.length; i++) { address recipient = stakers[i]; uint balance = stakingBalance[recipient]; if(balance > 0) { aufToken.transfer(recipient, balance * 10 / 100); } } } } contract AufToken { string public name = "AmongUs.Finance"; string public symbol = "AUF"; uint256 public totalSupply = 10000000000000000000000; // 10000 tokens uint8 public decimals = 18; event Transfer( address indexed _from, address indexed _to, uint256 _value ); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; constructor() public { balanceOf[msg.sender] = totalSupply; } function transfer(address _to, uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= balanceOf[_from]); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } }
0x608060405234801561001057600080fd5b506004361061009e5760003560e01c80637547c7a3116100665780637547c7a31461022e5780638da5cb5b1461025c578063a5ce413b146102a6578063c93c8f34146102b0578063fd5e6dd11461030c5761009e565b806306fdde03146100a35780633a58103e1461012657806345bc78ab1461017057806360ab5852146101c85780636f49712b146101d2575b600080fd5b6100ab61037a565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100eb5780820151818401526020810190506100d0565b50505050905090810190601f1680156101185780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61012e610418565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6101b26004803603602081101561018657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061043e565b6040518082815260200191505060405180910390f35b6101d0610456565b005b610214600480360360208110156101e857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506106ba565b604051808215151515815260200191505060405180910390f35b61025a6004803603602081101561024457600080fd5b81019080803590602001909291905050506106da565b005b610264610a59565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6102ae610a7f565b005b6102f2600480360360208110156102c657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610cbe565b604051808215151515815260200191505060405180910390f35b6103386004803603602081101561032257600080fd5b8101908080359060200190929190505050610cde565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156104105780601f106103e557610100808354040283529160200191610410565b820191906000526020600020905b8154815290600101906020018083116103f357829003601f168201915b505050505081565b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60046020528060005260406000206000915090505481565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610519576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260188152602001807f63616c6c6572206d75737420626520746865206f776e6572000000000000000081525060200191505060405180910390fd5b60008090505b6003805490508110156106b75760006003828154811061053b57fe5b9060005260206000200160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690506000600460008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905060008111156106a857600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb836064600a85028161060157fe5b046040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b15801561066b57600080fd5b505af115801561067f573d6000803e3d6000fd5b505050506040513d602081101561069557600080fd5b8101908080519060200190929190505050505b5050808060010191505061051f565b50565b60066020528060005260406000206000915054906101000a900460ff1681565b60008111610750576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260128152602001807f616d6f756e742063616e6e6f742062652030000000000000000000000000000081525060200191505060405180910390fd5b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166323b872dd3330846040518463ffffffff1660e01b8152600401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019350505050602060405180830381600087803b15801561082d57600080fd5b505af1158015610841573d6000803e3d6000fd5b505050506040513d602081101561085757600080fd5b81019080805190602001909291905050505080600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205401600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff166109a65760033390806001815401808255809150509060018203906000526020600020016000909192909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550505b6001600660003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055506001600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff02191690831515021790555050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905060008111610b39576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f7374616b696e672062616c616e63652063616e6e6f742062652030000000000081525060200191505060405180910390fd5b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb33836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b158015610be257600080fd5b505af1158015610bf6573d6000803e3d6000fd5b505050506040513d6020811015610c0c57600080fd5b8101908080519060200190929190505050506000600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506000600660003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff02191690831515021790555050565b60056020528060005260406000206000915054906101000a900460ff1681565b60038181548110610ceb57fe5b906000526020600020016000915054906101000a900473ffffffffffffffffffffffffffffffffffffffff168156fea265627a7a72315820b4fa482bd05e008250a887bb06a3b21acde4d2e590660de89b97b3093a09229364736f6c63430005100032
{"success": true, "error": null, "results": {"detectors": [{"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "controlled-array-length", "impact": "High", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'controlled-array-length', 'impact': 'High', 'confidence': 'Medium'}]}
25
0x099540ceA8919D103ba1954AF970B9753D9f0Bf1
pragma solidity 0.4.24; contract ERC1132 { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct lockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => lockToken)) public locked; /** * @dev Records data of all the tokens Locked */ event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity ); /** * @dev Records data of all the tokens unlocked */ event Unlocked( address indexed _of, bytes32 indexed _reason, uint256 _amount ); /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool); /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount); /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount); /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public returns (bool); /** * @dev Increase number of tokens locked for a specified reason * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public returns (bool); /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public returns (uint256 unlockableTokens); /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens); } library AddressUtils { /** * Returns whether the target address is a contract * dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0), "Recipient address is zero address(0). Check the address again."); require(_value <= balances[msg.sender], "The balance of account is insufficient."); 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(_to != address(0), "Recipient address is zero address(0). Check the address again."); require(_value <= balances[_from], "The balance of account is insufficient."); require(_value <= allowed[_from][msg.sender], "Insufficient tokens approved from account owner."); 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; } } sing SafeMath for uint256; address public root; // 혹시 몰라 준비해둔 superOwner 의 백업. 하드웨어 월렛 주소로 세팅할 예정. address public superOwner; mapping (address => bool) public owners; address[] public ownerList; event ChangedRoot(address newRoot); event ChangedSuperOwner(address newSuperOwner); event AddedNewOwner(address newOwner); event DeletedOwner(address deletedOwner); constructor() public { root = msg.sender; superOwner = msg.sender; owners[root] = true; ownerList.push(msg.sender); } modifier onlyRoot() { require(msg.sender == root, "Root privilege is required."); _; } modifier onlySuperOwner() { require(msg.sender == superOwner, "SuperOwner priviledge is required."); _; } modifier onlyOwner() { require(owners[msg.sender], "Owner priviledge is required."); _; } /** * @dev root 교체 (root 는 root 와 superOwner 를 교체할 수 있는 권리가 있다.) * @dev 기존 루트가 관리자에서 지워지지 않고, 새 루트가 자동으로 관리자에 등록되지 않음을 유의! */ function changeRoot(address newRoot) onlyRoot public returns (bool) { require(newRoot != address(0), "This address to be set is zero address(0). Check the input address."); root = newRoot; emit ChangedRoot(newRoot); return true; } /** * @dev superOwner 교체 (root 는 root 와 superOwner 를 교체할 수 있는 권리가 있다.) * @dev 기존 superOwner 가 관리자에서 지워지지 않고, 새 superOwner 가 자동으로 관리자에 등록되지 않음을 유의! */ function changeSuperOwner(address newSuperOwner) onlyRoot public returns (bool) { require(newSuperOwner != address(0), "This address to be set is zero address(0). Check the input address."); superOwner = newSuperOwner; emit ChangedSuperOwner(newSuperOwner); return true; } function newOwner(address owner) onlySuperOwner public returns (bool) { require(owner != address(0), "This address to be set is zero address(0). Check the input address."); require(!owners[owner], "This address is already registered."); owners[owner] = true; ownerList.push(owner); emit AddedNewOwner(owner); return true; } function deleteOwner(address owner) onlySuperOwner public returns (bool) { require(owners[owner], "This input address is not an owner."); delete owners[owner]; for (uint256 i = 0; i < ownerList.length; i++) { if (ownerList[i] == owner) { ownerList[i] = ownerList[ownerList.length.sub(1)]; ownerList.length = ownerList.length.sub(1); break; } } emit DeletedOwner(owner); return true; } } /** * @title Lockable token */ contract LockableToken is StandardToken, MultiOwnable { bool public locked = true; uint256 public constant LOCK_MAX = uint256(-1); /** * @dev 락 상태에서도 거래 가능한 언락 계정 */ mapping(address => bool) public unlockAddrs; e 만큼 잔고가 잠김 * @dev - 값이 0 일 때 : 잔고가 0 이어도 되므로 제한이 없는 것임. * @dev - 값이 LOCK_MAX 일 때 : 잔고가 uint256 의 최대값이므로 아예 잠긴 것임. */ mapping(address => uint256) public lockValues; event Locked(bool locked, string note); event LockedTo(address indexed addr, bool locked, string note); event SetLockValue(address indexed addr, uint256 value, string note); constructor() public { unlockTo(msg.sender, "Default Unlock To Root"); } modifier checkUnlock (address addr, uint256 value) { require(!locked || unlockAddrs[addr], "The account is currently locked."); require(balances[addr].sub(value) >= lockValues[addr], "Transferable limit exceeded. Check the status of the lock value."); _; } function lock(string note) onlyOwner public { locked = true; emit Locked(locked, note); } function unlock(string note) onlyOwner public { locked = false; emit Locked(locked, note); } function lockTo(address addr, string note) onlyOwner public { setLockValue(addr, LOCK_MAX, note); unlockAddrs[addr] = false; emit LockedTo(addr, true, note); } function unlockTo(address addr, string note) onlyOwner public { if (lockValues[addr] == LOCK_MAX) setLockValue(addr, 0, note); unlockAddrs[addr] = true; emit LockedTo(addr, false, note); } function setLockValue(address addr, uint256 value, string note) onlyOwner public { lockValues[addr] = value; emit SetLockValue(addr, value, note); } /** * @dev 이체 가능 금액을 조회한다. */ function getMyUnlockValue() public view returns (uint256) { address addr = msg.sender; if ((!locked || unlockAddrs[addr]) && balances[addr] > lockValues[addr]) return balances[addr].sub(lockValues[addr]); else return 0; } function transfer(address to, uint256 value) checkUnlock(msg.sender, value) public returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) checkUnlock(from, value) public returns (bool) { return super.transferFrom(from, to, value); } } /** * @title SobloTokenReceiver Receiver */ contract SobloTokenReceiver { enum SobloTokenReceiveType { TOKEN_TRANSFER, TOKEN_MINT } function onSobloTokenReceived(address owner, address spender, uint256 value, SobloTokenReceiveType receiveType) public returns (bool); } /** * @title SobloToken */ contract SobloToken is LockableToken { using AddressUtils for address; enum SobloTransferType NER, TRANSFER_TO_ECOSYSTEM, TRANSFER_TO_BOUNTY, TRANSFER_TO_RESERVE, TRANSFER_TO_ETC } event SobloTransferred(address indexed from, address indexed to, uint256 value, uint256 fro te); event SobloTransferredFrom(address indexed owner, address indexed spender, address indexed to, uint256 value, uint256 fromBalance, uint256 toBalance, string note); event SobloApproval(address indexed owner, address indexed spender, uint256 value, string note); event SobloMultiTransferred(address indexed owner, address indexed spender, address indexed to, uint256 value, SobloTransferType purpose, uint256 fromBalance, uint256 toBalance, string note); event TransferredToSobloDapp( address indexed owner, address indexed spender, address indexed to, uint256 value, string note, SobloTokenReceiver.SobloTokenReceiveType receiveType ); constructor() public { } // ERC20 함수들을 오버라이딩하여 super 로 올라가지 않고 무조건 soblo~ 함수로 지나가게 한다. function transfer(address to, uint256 value) public returns (bool ret) { return sobloTransfer(to, value, "called by transfer()"); } function sobloTransfer(address to, uint256 value, string note) public returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of Soblo Token. You cannot send money to this address."); ret = super.transfer(to, value); postTransfer(msg.sender, msg.sender, to, value, note, SobloTokenReceiver.SobloTokenReceiveType.TOKEN_TRANSFER); emit SobloTransferred(msg.sender, to, value, balanceOf(msg.sender), balanceOf(to), note); } function transferFrom(address from, address to, uint256 value) public returns (bool) { return sobloTransferFrom(from, to, value, "called by transferFrom()"); } function sobloTransferFrom(address from, address to, uint256 value, string note) public returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of Soblo Token. You cannot send money to this address."); ret = super.transferFrom(from, to, value); postTransfer(from, msg.sender, to, value, note, SobloTokenReceiver.SobloTokenReceiveType.TOKEN_TRANSFER); emit SobloTransferredFrom(from, msg.sender, to, value, balanceOf(from), balanceOf(to), note); } function approve(address spender, uint256 value) public returns (bool) { return sobloApprove(spender, value, "called by approve()"); } function sobloApprove(address spender, uint256 value, string note) public returns (bool ret) { ret = super.approve(spender, value); emit SobloApproval(msg.sender, spender, value, note); } function increaseApproval(address spender, uint256 addedValue) public returns (bool) { return sobloIncreaseApproval(spender, addedValue, "called by increaseApproval()"); } function sobloIncreaseApproval(address spender, uint256 addedValue, string note) public returns (bool ret) { ret = super.increaseApproval(spender, addedValue); emit SobloApproval(msg.sender, spender, allowed[msg.sender][spender], note); } function decreaseApproval(address spender, uint256 subtractedValue) public returns (bool) { return sobloDecreaseApproval(spender, subtractedValue, "called by decreaseApproval()"); } function sobloDecreaseApproval(address spender, uint256 subtractedValue, string note) public returns (bool ret) { ret = super.decreaseApproval(spender, subtractedValue); emit SobloApproval(msg.sender, spender, allowed[msg.sender][spender], note); } function postTransfer( address owner, address spender, address to, uint256 value, string note, SobloTokenReceiver.SobloTokenReceiveType receiveType ) internal returns (bool) { if (to.isContract()) { bool callOk = address(to).call( bytes4(keccak256("onSobloTokenReceived(address,address,uint256,uint8)")), owner, spender, value, receiveType ); if (callOk) { emit TransferredToSobloDapp(owner, spender, to, value, note, receiveType); return true; } } return false; } /** * @dev 다계좌 전송 (postTransfer 를 호출하지 않음에 유의!) * * @param from 보낼 토큰의 주인 (내부적으로 transferFrom 을 이용함) * @param to 토큰을 받을 주소 * @param purpose 팀에게 보내기, 파트너에게 보내기, 바운티 참여자에게 보내기 등의 목적을 선택 * @param note 일반적인 메모 */ function sobloMultiTransfer( address from, address[] to, uint256[] values, SobloTransferType purpose, string note ) onlyOwner public returns (bool ret) { uint256 length = to.length; require(length == values.length, "The size of \'to\' and \'values\' array is different."); require(uint8(purpose) < 6); ret = true; for (uint256 i = 0; i < length; i++) { require(to[i] != address(this), "The receive address is the Contact Address of Soblo Token. You cannot send money to this address."); ret = ret && super.transferFrom(from, to[i], values[i]); // 관리자 기능으로 post 프로세스(댑의 onReceived 를 일깨움)를 타지 않기 위해 super.transferFrom 를 호출한다. emit SobloMultiTransferred(from, msg.sender, to[i], values[i], purpose, balanceOf(from), balanceOf(to[i]), note); } } function destroy() onlyRoot public { selfdestruct(root); } } /** * @title SobloTokenDappBase */ contract SobloTokenDappBase is SobloTokenReceiver { address internal _sobloToken; event LogOnReceivedSobloToken(address indexed owner, address indexed spender, uint256 value, SobloTokenReceiveType receiveType); constructor(address sobloToken) public { _sobloToken = sobloToken; } modifier onlySobloToken() { require(msg.sender == _sobloToken, "msg.sender must be the registered token contract"); _; } // Override this function function onSobloTokenReceived(address owner, address spender, uint256 value, SobloTokenReceiveType receiveType) public onlySobloToken returns en(owner, spender, value, receiveType); } } contract HINTToken is SobloToken { string public constant name = "WHint Token"; string public constant symbol = "WHINT"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1e9 * (10 ** uint256(decimals)); constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } }
0x6080604052600436106101cc576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680623078b0146101d1578063022914a71461025a57806306fdde03146102b5578063095ea7b3146103455780630c870a6b146103aa5780631044c66b1461045557806318160ddd146104b05780631d07b1ec146104db57806323b872dd146105865780632ff2e9dc1461060b578063313ce56714610636578063320a98fd146106675780633d8731ac146106d05780634a7902d2146106fb5780634aa678c314610756578063505450d4146107815780635a791156146107dc57806366188463146108875780636bd5e26a146108ec57806370a08231146109755780637b5ac141146109cc57806383197ef014610a775780638595245414610a8e57806387dcd2b614610ae957806395d89b4114610b40578063a9059cbb14610bd0578063a96ce7aa14610c35578063cb619a3314610c9e578063cd5c4c7014610cf5578063cf30901214610d50578063d712800f14610d7f578063d73dd62314610e12578063dd62ed3e14610e77578063def79ab514610eee578063e22ca81914610f5b578063ebf0c7171461108f578063f913042b146110e6575b600080fd5b3480156101dd57600080fd5b50610258600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506111b1565b005b34801561026657600080fd5b5061029b600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611402565b604051808215151515815260200191505060405180910390f35b3480156102c157600080fd5b506102ca611422565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561030a5780820151818401526020810190506102ef565b50505050905090810190601f1680156103375780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561035157600080fd5b50610390600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061145b565b604051808215151515815260200191505060405180910390f35b3480156103b657600080fd5b5061043b600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506114a5565b604051808215151515815260200191505060405180910390f35b34801561046157600080fd5b50610496600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611608565b604051808215151515815260200191505060405180910390f35b3480156104bc57600080fd5b506104c561186d565b6040518082815260200191505060405180910390f35b3480156104e757600080fd5b5061056c600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050611877565b604051808215151515815260200191505060405180910390f35b34801561059257600080fd5b506105f1600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611aa4565b604051808215151515815260200191505060405180910390f35b34801561061757600080fd5b50610620611af0565b6040518082815260200191505060405180910390f35b34801561064257600080fd5b5061064b611b01565b604051808260ff1660ff16815260200191505060405180910390f35b34801561067357600080fd5b506106ce600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050611b06565b005b3480156106dc57600080fd5b506106e5611c9c565b6040518082815260200191505060405180910390f35b34801561070757600080fd5b5061073c600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611cc0565b604051808215151515815260200191505060405180910390f35b34801561076257600080fd5b5061076b611f25565b6040518082815260200191505060405180910390f35b34801561078d57600080fd5b506107c2600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506120bd565b604051808215151515815260200191505060405180910390f35b3480156107e857600080fd5b5061086d600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506120dd565b604051808215151515815260200191505060405180910390f35b34801561089357600080fd5b506108d2600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506121c4565b604051808215151515815260200191505060405180910390f35b3480156108f857600080fd5b50610973600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929050505061220e565b005b34801561098157600080fd5b506109b6600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612416565b6040518082815260200191505060405180910390f35b3480156109d857600080fd5b50610a5d600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929050505061245e565b604051808215151515815260200191505060405180910390f35b348015610a8357600080fd5b50610a8c6125c1565b005b348015610a9a57600080fd5b50610acf600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506126c1565b604051808215151515815260200191505060405180910390f35b348015610af557600080fd5b50610afe612ab1565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b348015610b4c57600080fd5b50610b55612ad7565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610b95578082015181840152602081019050610b7a565b50505050905090810190601f168015610bc25780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b348015610bdc57600080fd5b50610c1b600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050612b10565b604051808215151515815260200191505060405180910390f35b348015610c4157600080fd5b50610c9c600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050612b5a565b005b348015610caa57600080fd5b50610cdf600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612cf0565b6040518082815260200191505060405180910390f35b348015610d0157600080fd5b50610d36600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612d08565b604051808215151515815260200191505060405180910390f35b348015610d5c57600080fd5b50610d656130fa565b604051808215151515815260200191505060405180910390f35b348015610d8b57600080fd5b50610e10600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929050505061310d565b005b348015610e1e57600080fd5b50610e5d600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506132d2565b604051808215151515815260200191505060405180910390f35b348015610e8357600080fd5b50610ed8600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061331c565b6040518082815260200191505060405180910390f35b348015610efa57600080fd5b50610f19600480360381019080803590602001909291905050506133a3565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b348015610f6757600080fd5b50611075600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019082018035906020019080806020026020016040519081016040528093929190818152602001838360200280828437820191505050505050919291929080359060200190820180359060200190808060200260200160405190810160405280939291908181526020018383602002808284378201915050505050509192919290803560ff169060200190929190803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506133e1565b604051808215151515815260200191505060405180910390f35b34801561109b57600080fd5b506110a4613864565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b3480156110f257600080fd5b50611197600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929050505061388a565b604051808215151515815260200191505060405180910390f35b600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff161515611272576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f4f776e65722070726976696c656467652069732072657175697265642e00000081525060200191505060405180910390fd5b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff600960008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205414156112e6576112e58260008361310d565b5b6001600860008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055508173ffffffffffffffffffffffffffffffffffffffff167f4bf46282901af80a4309ce07c36d841184ce98297f8735f7769d169497ac7a4c600083604051808315151515815260200180602001828103825283818151815260200191508051906020019080838360005b838110156113c35780820151818401526020810190506113a8565b50505050905090810190601f1680156113f05780820380516001836020036101000a031916815260200191505b50935050505060405180910390a25050565b60056020528060005260406000206000915054906101000a900460ff1681565b6040805190810160405280600b81526020017f5748696e7420546f6b656e00000000000000000000000000000000000000000081525081565b600061149d83836040805190810160405280601381526020017f63616c6c656420627920617070726f76652829000000000000000000000000008152506120dd565b905092915050565b60006114b18484613ad0565b90508373ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f873a5dfdc9d3efb66def120ac20495bf0dc772d6e19c1b8bd78f43da51787e8a600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054856040518083815260200180602001828103825283818151815260200191508051906020019080838360005b838110156115c65780820151818401526020810190506115ab565b50505050905090810190601f1680156115f35780820380516001836020036101000a031916815260200191505b50935050505060405180910390a39392505050565b6000600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415156116cf576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f526f6f742070726976696c6567652069732072657175697265642e000000000081525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16141515156117c0576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260438152602001807f54686973206164647265737320746f20626520736574206973207a65726f206181526020017f6464726573732830292e20436865636b2074686520696e70757420616464726581526020017f73732e000000000000000000000000000000000000000000000000000000000081525060600191505060405180910390fd5b81600460006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055507f94b17f1a4844062cbed00809347b0f8149fc88c5a3ea720c7aed42c559eed46d82604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a160019050919050565b6000600154905090565b60003073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff161415151561198f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260618152602001807f546865207265636569766520616464726573732069732074686520436f6e746181526020017f63742041646472657373206f6620536f626c6f20546f6b656e2e20596f75206381526020017f616e6e6f742073656e64206d6f6e657920746f2074686973206164647265737381526020017f2e0000000000000000000000000000000000000000000000000000000000000081525060800191505060405180910390fd5b6119998484613ccc565b90506119aa33338686866000613eea565b508373ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fa609c322062a32354cef4c3627f131b25e0a79ca1c09649756e6b790ddf7697485611a0433612416565b611a0d89612416565b876040518085815260200184815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b83811015611a60578082015181840152602081019050611a45565b50505050905090810190601f168015611a8d5780820380516001836020036101000a031916815260200191505b509550505050505060405180910390a39392505050565b6000611ae78484846040805190810160405280601881526020017f63616c6c6564206279207472616e7366657246726f6d2829000000000000000081525061388a565b90509392505050565b601260ff16600a0a633b9aca000281565b601281565b600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff161515611bc7576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f4f776e65722070726976696c656467652069732072657175697265642e00000081525060200191505060405180910390fd5b6001600760006101000a81548160ff0219169083151502179055507fc1086893b0a3f1d991fd25e26cd28cad11de174842b04a55cc2423ed178e4382600760009054906101000a900460ff1682604051808315151515815260200180602001828103825283818151815260200191508051906020019080838360005b83811015611c5e578082015181840152602081019050611c43565b50505050905090810190601f168015611c8b5780820380516001836020036101000a031916815260200191505b50935050505060405180910390a150565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81565b6000600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515611d87576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f526f6f742070726976696c6567652069732072657175697265642e000000000081525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614151515611e78576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260438152602001807f54686973206164647265737320746f20626520736574206973207a65726f206181526020017f6464726573732830292e20436865636b2074686520696e70757420616464726581526020017f73732e000000000000000000000000000000000000000000000000000000000081525060600191505060405180910390fd5b81600360006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055507f43ddeae7116ae634a7d05c2d1c588bca11b7bbc8cb96fbb2cb9c5b1afdf9ce1282604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a160019050919050565b600080339050600760009054906101000a900460ff161580611f905750600860008273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff165b80156120185750600960008273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546000808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054115b156120b4576120ad600960008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461418e90919063ffffffff16565b91506120b9565b600091505b5090565b60086020528060005260406000206000915054906101000a900460ff1681565b60006120e98484614218565b90508373ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f873a5dfdc9d3efb66def120ac20495bf0dc772d6e19c1b8bd78f43da51787e8a85856040518083815260200180602001828103825283818151815260200191508051906020019080838360005b83811015612182578082015181840152602081019050612167565b50505050905090810190601f1680156121af5780820380516001836020036101000a031916815260200191505b50935050505060405180910390a39392505050565b600061220683836040805190810160405280601c81526020017f63616c6c6564206279206465637265617365417070726f76616c28290000000081525061245e565b905092915050565b600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff1615156122cf576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f4f776e65722070726976696c656467652069732072657175697265642e00000081525060200191505060405180910390fd5b6122fa827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8361310d565b6000600860008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055508173ffffffffffffffffffffffffffffffffffffffff167f4bf46282901af80a4309ce07c36d841184ce98297f8735f7769d169497ac7a4c600183604051808315151515815260200180602001828103825283818151815260200191508051906020019080838360005b838110156123d75780820151818401526020810190506123bc565b50505050905090810190601f1680156124045780820380516001836020036101000a031916815260200191505b50935050505060405180910390a25050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b600061246a848461430a565b90508373ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f873a5dfdc9d3efb66def120ac20495bf0dc772d6e19c1b8bd78f43da51787e8a600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054856040518083815260200180602001828103825283818151815260200191508051906020019080838360005b8381101561257f578082015181840152602081019050612564565b50505050905090810190601f1680156125ac5780820380516001836020036101000a031916815260200191505b50935050505060405180910390a39392505050565b600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515612686576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f526f6f742070726976696c6567652069732072657175697265642e000000000081525060200191505060405180910390fd5b600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16ff5b6000600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415156127ae576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001807f53757065724f776e65722070726976696c65646765206973207265717569726581526020017f642e00000000000000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415151561289f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260438152602001807f54686973206164647265737320746f20626520736574206973207a65726f206181526020017f6464726573732830292e20436865636b2074686520696e70757420616464726581526020017f73732e000000000000000000000000000000000000000000000000000000000081525060600191505060405180910390fd5b600560008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16151515612987576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260238152602001807f54686973206164647265737320697320616c726561647920726567697374657281526020017f65642e000000000000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b6001600560008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff02191690831515021790555060068290806001815401808255809150509060018203906000526020600020016000909192909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550507f5446d64d957daf41eca8227aa8fa5eb7f92c617adf03fbd9df64e8eb564d824e82604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a160019050919050565b600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6040805190810160405280600581526020017f5748494e5400000000000000000000000000000000000000000000000000000081525081565b6000612b5283836040805190810160405280601481526020017f63616c6c6564206279207472616e736665722829000000000000000000000000815250611877565b905092915050565b600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff161515612c1b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f4f776e65722070726976696c656467652069732072657175697265642e00000081525060200191505060405180910390fd5b6000600760006101000a81548160ff0219169083151502179055507fc1086893b0a3f1d991fd25e26cd28cad11de174842b04a55cc2423ed178e4382600760009054906101000a900460ff1682604051808315151515815260200180602001828103825283818151815260200191508051906020019080838360005b83811015612cb2578082015181840152602081019050612c97565b50505050905090810190601f168015612cdf5780820380516001836020036101000a031916815260200191505b50935050505060405180910390a150565b60096020528060005260406000206000915090505481565b600080600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515612df6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001807f53757065724f776e65722070726976696c65646765206973207265717569726581526020017f642e00000000000000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b600560008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff161515612edd576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260238152602001807f5468697320696e7075742061646472657373206973206e6f7420616e206f776e81526020017f65722e000000000000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b600560008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81549060ff0219169055600090505b60068054905081101561308d578273ffffffffffffffffffffffffffffffffffffffff16600682815481101515612f6457fe5b9060005260206000200160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161415613080576006612fc6600160068054905061418e90919063ffffffff16565b815481101515612fd257fe5b9060005260206000200160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1660068281548110151561300c57fe5b9060005260206000200160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555061306d600160068054905061418e90919063ffffffff16565b60068161307a91906150fc565b5061308d565b8080600101915050612f31565b7f1e64d9a491033a9731fa82493f0ab60e9f74294eca27edd93629f1fbaa15d28783604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a16001915050919050565b600760009054906101000a900460ff1681565b600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff1615156131ce576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f4f776e65722070726976696c656467652069732072657175697265642e00000081525060200191505060405180910390fd5b81600960008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff167fb19425af6288c6bb0d88f64d6d1cfe5eb7e2d31ee92f1012798df97a9b6b011a83836040518083815260200180602001828103825283818151815260200191508051906020019080838360005b83811015613292578082015181840152602081019050613277565b50505050905090810190601f1680156132bf5780820380516001836020036101000a031916815260200191505b50935050505060405180910390a2505050565b600061331483836040805190810160405280601c81526020017f63616c6c656420627920696e637265617365417070726f76616c2829000000008152506114a5565b905092915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b6006818154811015156133b257fe5b906000526020600020016000915054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000806000600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff1615156134a7576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f4f776e65722070726976696c656467652069732072657175697265642e00000081525060200191505060405180910390fd5b86519150855182141515613549576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260318152602001807f5468652073697a65206f662027746f2720616e64202776616c7565732720617281526020017f72617920697320646966666572656e742e00000000000000000000000000000081525060400191505060405180910390fd5b600685600581111561355757fe5b60ff1610151561356657600080fd5b60019250600090505b81811015613859573073ffffffffffffffffffffffffffffffffffffffff16878281518110151561359c57fe5b9060200190602002015173ffffffffffffffffffffffffffffffffffffffff16141515156136a4576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260618152602001807f546865207265636569766520616464726573732069732074686520436f6e746181526020017f63742041646472657373206f6620536f626c6f20546f6b656e2e20596f75206381526020017f616e6e6f742073656e64206d6f6e657920746f2074686973206164647265737381526020017f2e0000000000000000000000000000000000000000000000000000000000000081525060800191505060405180910390fd5b8280156136e657506136e58888838151811015156136be57fe5b9060200190602002015188848151811015156136d657fe5b9060200190602002015161459b565b5b925086818151811015156136f657fe5b9060200190602002015173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff168973ffffffffffffffffffffffffffffffffffffffff167f88098165ed6db5b0cb36499c27d46197630154717a26b48aede92bd7cd6ee12b898581518110151561377357fe5b90602001906020020151896137878e612416565b6137a78e8981518110151561379857fe5b90602001906020020151612416565b8b604051808681526020018560058111156137be57fe5b60ff16815260200184815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b8381101561380e5780820151818401526020810190506137f3565b50505050905090810190601f16801561383b5780820380516001836020036101000a031916815260200191505b50965050505050505060405180910390a4808060010191505061356f565b505095945050505050565b600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60003073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16141515156139a2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260618152602001807f546865207265636569766520616464726573732069732074686520436f6e746181526020017f63742041646472657373206f6620536f626c6f20546f6b656e2e20596f75206381526020017f616e6e6f742073656e64206d6f6e657920746f2074686973206164647265737381526020017f2e0000000000000000000000000000000000000000000000000000000000000081525060800191505060405180910390fd5b6139ad85858561459b565b90506139be85338686866000613eea565b508373ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff167f98885723734242dd9facd4a9d474af4699a809ba2f59ecf9c30a223b905007ee86613a2f8a612416565b613a388a612416565b886040518085815260200184815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b83811015613a8b578082015181840152602081019050613a70565b50505050905090810190601f168015613ab85780820380516001836020036101000a031916815260200191505b509550505050505060405180910390a4949350505050565b6000613b6182600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546147bb90919063ffffffff16565b600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a36001905092915050565b60003382600760009054906101000a900460ff161580613d355750600860008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff165b1515613da9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f546865206163636f756e742069732063757272656e746c79206c6f636b65642e81525060200191505060405180910390fd5b600960008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054613e3a826000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461418e90919063ffffffff16565b10151515613ed6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260408152602001807f5472616e7366657261626c65206c696d69742065786365656465642e2043686581526020017f636b2074686520737461747573206f6620746865206c6f636b2076616c75652e81525060400191505060405180910390fd5b613ee08585614845565b9250505092915050565b600080613f0c8673ffffffffffffffffffffffffffffffffffffffff16614b82565b1561417e578573ffffffffffffffffffffffffffffffffffffffff1660405180807f6f6e536f626c6f546f6b656e526563656976656428616464726573732c61646481526020017f726573732c75696e743235362c75696e74382900000000000000000000000000815250603301905060405180910390207c01000000000000000000000000000000000000000000000000000000009004898988876040518563ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200183815260200182600181111561404d57fe5b60ff1681526020019450505050506000604051808303816000875af1925050509050801561417d578573ffffffffffffffffffffffffffffffffffffffff168773ffffffffffffffffffffffffffffffffffffffff168973ffffffffffffffffffffffffffffffffffffffff167f52bcea5f2b1d4e11b2c554106feef51ce4146f2b5fe97e8b026576e10793339388888860405180848152602001806020018360018111156140f857fe5b60ff168152602001828103825284818151815260200191508051906020019080838360005b8381101561413857808201518184015260208101905061411d565b50505050905090810190601f1680156141655780820380516001836020036101000a031916815260200191505b5094505050505060405180910390a460019150614183565b5b600091505b509695505050505050565b600080838311151515614209576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601e8152602001807f536166654d6174683a207375627472616374696f6e206f766572666c6f77000081525060200191505060405180910390fd5b82840390508091505092915050565b600081600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b600080600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490508083111561441b576000600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506144af565b61442e838261418e90919063ffffffff16565b600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b8373ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a3600191505092915050565b60008382600760009054906101000a900460ff1615806146045750600860008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff165b1515614678576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f546865206163636f756e742069732063757272656e746c79206c6f636b65642e81525060200191505060405180910390fd5b600960008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054614709826000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461418e90919063ffffffff16565b101515156147a5576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260408152602001807f5472616e7366657261626c65206c696d69742065786365656465642e2043686581526020017f636b2074686520737461747573206f6620746865206c6f636b2076616c75652e81525060400191505060405180910390fd5b6147b0868686614b95565b925050509392505050565b600080828401905083811015151561483b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614151515614911576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252603e8152602001807f526563697069656e742061646472657373206973207a65726f2061646472657381526020017f732830292e20436865636b20746865206164647265737320616761696e2e000081525060400191505060405180910390fd5b6000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482111515156149ed576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260278152602001807f5468652062616c616e6365206f66206163636f756e7420697320696e7375666681526020017f696369656e742e0000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b614a3e826000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461418e90919063ffffffff16565b6000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550614ad1826000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546147bb90919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b600080823b905060008111915050919050565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614151515614c61576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252603e8152602001807f526563697069656e742061646472657373206973207a65726f2061646472657381526020017f732830292e20436865636b20746865206164647265737320616761696e2e000081525060400191505060405180910390fd5b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020548211151515614d3d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260278152602001807f5468652062616c616e6365206f66206163636f756e7420697320696e7375666681526020017f696369656e742e0000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b600260008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020548211151515614e57576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260308152602001807f496e73756666696369656e7420746f6b656e7320617070726f7665642066726f81526020017f6d206163636f756e74206f776e65722e0000000000000000000000000000000081525060400191505060405180910390fd5b614ea8826000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461418e90919063ffffffff16565b6000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550614f3b826000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546147bb90919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061500c82600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461418e90919063ffffffff16565b600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190509392505050565b815481835581811115615123578183600052602060002091820191016151229190615128565b5b505050565b61514a91905b8082111561514657600081600090555060010161512e565b5090565b905600a165627a7a72305820a1d8fa0ee0acac4df746aa903e38529923a5c9c5f96c4ea6a1c5b4ab918a31f40029
{"success": true, "error": null, "results": {"detectors": [{"check": "constant-function-asm", "impact": "Medium", "confidence": "Medium"}, {"check": "controlled-array-length", "impact": "High", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'constant-function-asm', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'controlled-array-length', 'impact': 'High', 'confidence': 'Medium'}]}
26
0x0A8347c3E5a363613b46dcBC5CE560A3bc9BC2FA
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 = 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(); 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); } /// @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); 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); 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] && _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; } 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; } } 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, 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 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 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; } 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) * (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 = 0x0e49911C937357EAA5a56984483b4B8918D0493b; 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 = 0x2f8ADA783E0696F610e5637CF873B967f47dF2E3; 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 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(swapedTokens >= 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)); 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(DAI_JOIN_ADDRESS); 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 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(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); 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(); (,,,,,,,,,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); 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 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 = 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) { (, 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 = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB; /// @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])); } } }
0x608060405234801561001057600080fd5b50600436106100935760003560e01c806382dfc5f71161006657806382dfc5f7146100e65780638823151b146100ee578063d36b907d146100f6578063e074bb47146100fe578063ef9486df1461011157610093565b8063329b8f591461009857806339df1878146100ad5780633d391f70146100cb5780634d9fb18f146100de575b600080fd5b6100ab6100a63660046109f2565b610119565b005b6100b5610478565b6040516100c29190610b1f565b60405180910390f35b6100ab6100d93660046109d6565b610490565b6100b5610670565b6100b5610688565b6100b56106a0565b6100b56106b8565b6100ab61010c3660046109d6565b6106d0565b6100b561077e565b731e0447b19bb6ecfdae1e4ae1694b0c3659614e4e600061014d73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2610796565b9050600061015a8461079e565b60405163095ea7b360e01b815290915073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc29063095ea7b3906101aa90731e0447b19bb6ecfdae1e4ae1694b0c3659614e4e908590600401610c03565b602060405180830381600087803b1580156101c457600080fd5b505af11580156101d8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101fc9190610a32565b5060408051600380825260808201909252606091816020015b61021d610944565b8152602001906001900390816102155790505090506102518386732f8ada783e0696f610e5637cf873b967f47df2e36107b7565b8160008151811061025e57fe5b60200260200101819052506102ae8787873330604051602001610285959493929190610bd1565b604051602081830303815290604052732f8ada783e0696f610e5637cf873b967f47df2e3610842565b816001815181106102bb57fe5b60200260200101819052506102d18383306108b4565b816002815181106102de57fe5b6020908102919091010152604080516001808252818301909252606091816020015b610308610996565b8152602001906001900390816103005790505090506103256108ef565b8160008151811061033257fe5b602002602001018190525061035a732f8ada783e0696f610e5637cf873b967f47df2e3610490565b60405163a67a6a4560e01b81526001600160a01b0386169063a67a6a45906103889084908690600401610c1c565b600060405180830381600087803b1580156103a257600080fd5b505af11580156103b6573d6000803e3d6000fd5b505050506103d7732f8ada783e0696f610e5637cf873b967f47df2e36106d0565b735c55b921f590a89c1ebe84df170e655a82b621266001600160a01b031663d061ce5030338b8b60405160200161040f929190610b33565b6040516020818303038152906040526040518463ffffffff1660e01b815260040161043c93929190610b4d565b600060405180830381600087803b15801561045657600080fd5b505af115801561046a573d6000803e3d6000fd5b505050505050505050505050565b735c55b921f590a89c1ebe84df170e655a82b6212681565b6000306001600160a01b031663bf7e214f6040518163ffffffff1660e01b815260040160206040518083038186803b1580156104cb57600080fd5b505afa1580156104df573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105039190610a52565b9050806001600160a01b0381166105f457735a15566417e6c1c9546523066500bddbc53f88c76001600160a01b03166365688cc96040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561056357600080fd5b505af1158015610577573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061059b9190610a52565b604051637a9e5e4b60e01b81529091503090637a9e5e4b906105c1908490600401610b1f565b600060405180830381600087803b1580156105db57600080fd5b505af11580156105ef573d6000803e3d6000fd5b505050505b806001600160a01b031663cbeea68c843060405161061190610afd565b6040519081900381206001600160e01b031960e086901b168252610639939291600401610ba4565b600060405180830381600087803b15801561065357600080fd5b505af1158015610667573d6000803e3d6000fd5b50505050505050565b732f8ada783e0696f610e5637cf873b967f47df2e381565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b735a15566417e6c1c9546523066500bddbc53f88c781565b731e0447b19bb6ecfdae1e4ae1694b0c3659614e4e81565b6000306001600160a01b031663bf7e214f6040518163ffffffff1660e01b815260040160206040518083038186803b15801561070b57600080fd5b505afa15801561071f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107439190610a52565b90506001600160a01b038116610759575061077b565b6000819050806001600160a01b0316632bc3217d843060405161061190610afd565b50565b734678f0a6958e4d2bc4f1baf7bc52e8f3564f3fe481565b60005b919050565b60006107b182600263ffffffff61090f16565b92915050565b6107bf610944565b604080516101008101825260018152600060208083018290528351608081018552828152929384019291908201905b81526020016000815260200186815250815260200185815260200160008152602001836001600160a01b03168152602001600081526020016040518060200160405280600081525081525090509392505050565b61084a610944565b50604080516101008101825260088152600060208083018290528351608080820186528382529181018390528085018390526060808201849052948401529282018190529181018290526001600160a01b0390921660a083015260c082015260e081019190915290565b6108bc610944565b604080516101008101825260008082526020808301829052835160808101855260018152929384019291908201906107ee565b6108f7610996565b50604080518082019091523081526001602082015290565b60008282018381101561093d5760405162461bcd60e51b815260040161093490610d39565b60405180910390fd5b9392505050565b6040805161010081018252600080825260208201529081016109646109ad565b8152602001600081526020016000815260200160006001600160a01b0316815260200160008152602001606081525090565b604080518082019091526000808252602082015290565b604080516080810190915260008082526020820190815260200160008152602001600081525090565b6000602082840312156109e7578081fd5b813561093d81610d91565b600080600060608486031215610a06578182fd5b8335610a1181610d91565b92506020840135610a2181610d91565b929592945050506040919091013590565b600060208284031215610a43578081fd5b8151801515811461093d578182fd5b600060208284031215610a63578081fd5b815161093d81610d91565b6001600160a01b03169052565b60008151808452815b81811015610aa057602081850181015186830182015201610a84565b81811115610ab15782602083870101525b50601f01601f19169290920160200192915050565b8051151582526020810151610ada81610d87565b60208301526040810151610aed81610d87565b6040830152606090810151910152565b756578656375746528616464726573732c62797465732960501b815260160190565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b03848116825283166020820152608060408201819052600a908201526910585d99525b5c1bdc9d60b21b60a082015260c060608201819052600090610b9b90830184610a7b565b95945050505050565b6001600160a01b0393841681529190921660208201526001600160e01b0319909116604082015260600190565b6001600160a01b0395861681529385166020850152604084019290925283166060830152909116608082015260a00190565b6001600160a01b03929092168252602082015260400190565b6040808252835182820181905260009190606090818501906020808901865b83811015610c68578151610c4f8151610d70565b8652830151838601529386019390820190600101610c3b565b5050868303818801528751808452818401925080820284018201898301885b83811015610d2857601f198784030186528151610160610ca78251610d7c565b855286820151878601528a820151610cc18c870182610ac6565b508982015160c081818801526080840151915060e0828189015260a08501519250610cf0610100890184610a6e565b9084015161012088015283015161014087018390529050610d1382870182610a7b565b98880198955050509185019150600101610c87565b50909b9a5050505050505050505050565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b6001600160a01b031690565b806009811061079957fe5b6002811061077b57fe5b6001600160a01b038116811461077b57600080fdfea2646970667358221220efb8845e780cca879fd520efade645b9b31416008f323b536e3de8b6e98c397564736f6c63430006060033
{"success": true, "error": null, "results": {"detectors": [{"check": "tx-origin", "impact": "Medium", "confidence": "Medium"}, {"check": "name-reused", "impact": "High", "confidence": "High"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-lowlevel", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'tx-origin', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'name-reused', 'impact': 'High', 'confidence': 'High'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-lowlevel', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
27
0x0a98ad316dfbcdaef91e382348a0c3639ec8f9d3
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); } interface IStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewards(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; // Events 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); } interface IStakingRewards2 is IStakingRewards { function totalMinted() external view returns (uint); function weightOfGauge(address gauge) external view returns (uint); function stakingPerLPT(address gauge) external view returns (uint); function stakeTimeOf(address account) external view returns (uint); function stakeAgeOf(address account) external view returns (uint); function factorOf(address account) external view returns (uint); function spendTimeOf(address account) external view returns (uint); function spendAgeOf(address account) external view returns (uint); function coinAgeOf(address account) external view returns (uint); function spendCoinAge(address account, uint coinAge) external returns (uint); event SpentCoinAge(address indexed gauge, address indexed account, uint coinAge); } 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 virtual 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)).sub(LiquidityGauge(reward_contract).claimed_rewards_for(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'); } } contract TurboGauge is SExactGauge { address public staking; mapping(address => uint) public lastTurboOf; uint public lastTurboSupply; function initialize(address governor, address _minter, address _lp_token, address _staking) virtual public initializer { super.initialize(governor, _minter, _lp_token); staking = _staking; } function ratioStaking(address addr) public view returns (uint r) { r = IStakingRewards2(staking).balanceOf(addr); r = r.mul(1 ether).div(IStakingRewards2(staking).stakingPerLPT(address(this))); r = r.mul(1 ether).div(balanceOf[addr]); if(now > lasttime) r = r.mul(IStakingRewards2(staking).spendAgeOf(addr)).div(now.sub(lasttime)); } function factorOf(address addr) public view returns (uint f) { f = IStakingRewards2(staking).factorOf(addr); uint r = ratioStaking(addr); if(r < 1 ether) f = f.sub(1 ether).mul(r).div(1 ether).add(1 ether); } function virtualBalanceOf(address addr) virtual public view returns (uint) { if(span == 0 || totalSupply == 0) return balanceOf[addr]; if(now == lasttime) return balanceOf[addr].add(lastTurboOf[addr]); return balanceOf[addr].mul(factorOf(addr)).div(1 ether); } function virtualTotalSupply() virtual public view returns (uint) { return totalSupply.add(lastTurboSupply); } function _virtualTotalSupply(address addr, uint vbo) virtual internal view returns (uint) { return virtualTotalSupply().add(vbo).sub(balanceOf[addr].add(lastTurboOf[addr])); } function _virtual_claimable_last(uint delta, uint sumPer, uint lastSumPer, uint vbo, uint _vts) 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(_vts)); amount = amount.mul(vbo).div(1 ether); } function _checkpoint(address addr, bool _claim_rewards) virtual override internal { if(span == 0 || totalSupply == 0) return; uint vbo = virtualBalanceOf(addr); uint _vts = _virtualTotalSupply(addr, vbo); uint delta = claimableDelta(); uint amount = _virtual_claimable_last(delta, sumMiningPer, sumMiningPerOf[addr], vbo, _vts); if(delta != amount) bufReward = bufReward.add(delta).sub(amount); if(delta > 0) sumMiningPer = sumMiningPer.add(delta.mul(1 ether).div(_vts)); if(sumMiningPerOf[addr] != sumMiningPer) sumMiningPerOf[addr] = sumMiningPer; if(lastTurboOf[addr] != vbo.sub(balanceOf[addr])) lastTurboOf[addr] = vbo.sub(balanceOf[addr]); if(lastTurboSupply != _vts.sub(totalSupply)) lastTurboSupply = _vts.sub(totalSupply); lasttime = now; _checkpoint(addr, amount); _checkpoint_rewards(addr, _claim_rewards); } }
0x608060405234801561001057600080fd5b50600436106103f15760003560e01c806381c0c26311610215578063c0c53b8b11610125578063e1522536116100b8578063f77c479111610087578063f77c479114610ac0578063f8c8765e14610ac8578063fd96044b14610b06578063fe06566c14610b2c578063fec8ee0c14610b52576103f1565b8063e152253614610a63578063e6f1daf214610a91578063ef78d4fd14610a99578063efbe1c1c14610ab8576103f1565b8063d31f3f6d116100f4578063d31f3f6d14610a04578063ddf2be3f14610a0c578063de263bfa14610a35578063dfe0503114610a5b576103f1565b8063c0c53b8b1461095a578063c4d66de814610992578063cb742358146109b8578063d2797b59146109de576103f1565b80639df4ed56116101a8578063b6aa515b11610177578063b6aa515b146108e1578063b6b55f2514610907578063bce998f414610924578063be5d1be91461094a578063bf88a6ff14610952576103f1565b80639df4ed5614610879578063aaa626b61461089f578063b21544f3146108a7578063b6a1912d146108d9576103f1565b80638ec872e3116101e45780638ec872e3146107dc57806396c55175146107ff578063972656a3146108255780639bd324f214610853576103f1565b806381c0c2631461078157806382c630661461078957806384e9bd7e1461079157806387564d84146107b7576103f1565b80632e1a7d4d116103105780634d3ced19116102a35780636dd5b69d116102725780636dd5b69d146106ed5780636e553f651461070a57806370a08231146107365780637598108c1461075c57806376d8b11714610779576103f1565b80634d3ced191461066557806352665f471461069357806361aac4da146106bf57806365fe9451146106e5576103f1565b806343d7f86f116102df57806343d7f86f146105ed5780634b820093146105f55780634c87a0a51461062f5780634cf088d91461065d576103f1565b80632e1a7d4d1461057d578063331345831461059a57806338d07436146105c05780633ccfd60b146105e5576103f1565b806317e28089116103885780631d2747d4116103575780631d2747d41461051957806323a58292146105475780632585581f1461054f578063267716d214610557576103f1565b806317e28089146104db578063180692d0146104e357806318160ddd146104eb5780631b9f546f146104f3576103f1565b806313ecb1ca116103c457806313ecb1ca1461046257806313fa13681461048857806315fe96dc146104ae57806316fa50b1146104d3576103f1565b806307546172146103f6578063094007071461041a5780630c340a241461045257806313aecab11461045a575b600080fd5b6103fe610b6f565b604080516001600160a01b039092168252519081900360200190f35b6104406004803603602081101561043057600080fd5b50356001600160a01b0316610b7e565b60408051918252519081900360200190f35b6103fe610b9c565b610440610bab565b6104406004803603602081101561047857600080fd5b50356001600160a01b0316610bd6565b6104406004803603602081101561049e57600080fd5b50356001600160a01b0316610be8565b6104d1600480360360408110156104c457600080fd5b5080359060200135610c2f565b005b6103fe610c54565b610440610c6f565b610440610c75565b610440610c87565b6104406004803603602081101561050957600080fd5b50356001600160a01b0316610c8d565b6104d16004803603604081101561052f57600080fd5b506001600160a01b0381351690602001351515610cab565b610440610ce1565b610440610cf3565b6104406004803603602081101561056d57600080fd5b50356001600160a01b0316610d05565b6104d16004803603602081101561059357600080fd5b5035610d23565b610440600480360360208110156105b057600080fd5b50356001600160a01b0316610d7b565b6104d1600480360360408110156105d657600080fd5b50803590602001351515610e80565b6104d1610f0b565b610440610f26565b61061b6004803603602081101561060b57600080fd5b50356001600160a01b0316610f38565b604080519115158252519081900360200190f35b6104406004803603604081101561064557600080fd5b506001600160a01b0381358116916020013516610f97565b6103fe610fc0565b6104406004803603604081101561067b57600080fd5b506001600160a01b0381358116916020013516610fdb565b610440600480360360408110156106a957600080fd5b50803590602001356001600160a01b0316611004565b610440600480360360208110156106d557600080fd5b50356001600160a01b0316611020565b610440611101565b6104406004803603602081101561070357600080fd5b5035611113565b6104d16004803603604081101561072057600080fd5b50803590602001356001600160a01b0316611125565b6104406004803603602081101561074c57600080fd5b50356001600160a01b031661126a565b6104406004803603602081101561077257600080fd5b503561127c565b6103fe61129c565b6104d16112ab565b6103fe61130c565b6104d1600480360360208110156107a757600080fd5b50356001600160a01b0316610d78565b6104d1600480360360408110156107cd57600080fd5b5080359060200135151561131b565b610440600480360360408110156107f257600080fd5b5080359060200135611399565b6104d16004803603602081101561081557600080fd5b50356001600160a01b03166113ac565b6104406004803603604081101561083b57600080fd5b506001600160a01b03813581169160200135166113b7565b6104406004803603602081101561086957600080fd5b50356001600160a01b03166113e0565b6104406004803603602081101561088f57600080fd5b50356001600160a01b03166113fe565b610440611442565b6104d1600480360360608110156108bd57600080fd5b508035906001600160a01b036020820135169060400135611478565b6104406114a9565b6104d1600480360360208110156108f757600080fd5b50356001600160a01b03166114bb565b6104d16004803603602081101561091d57600080fd5b50356114db565b6104406004803603602081101561093a57600080fd5b50356001600160a01b03166114e5565b610440611709565b6103fe61170f565b6104d16004803603606081101561097057600080fd5b506001600160a01b03813581169160208101358216916040909101351661172a565b6104d1600480360360208110156109a857600080fd5b50356001600160a01b03166118ec565b610440600480360360208110156109ce57600080fd5b50356001600160a01b03166119dd565b610440600480360360208110156109f457600080fd5b50356001600160a01b0316611aae565b610440611ab4565b6104d160048036036060811015610a2257600080fd5b5080359060208101359060400135611ac6565b61044060048036036020811015610a4b57600080fd5b50356001600160a01b0316611ae9565b6103fe611b07565b61061b60048036036040811015610a7957600080fd5b506001600160a01b0381358116916020013516611b16565b6104d1611b36565b610aa1611b3f565b60408051600f9290920b8252519081900360200190f35b610440611b48565b6103fe611b5a565b6104d160048036036080811015610ade57600080fd5b506001600160a01b038135811691602081013582169160408201358116916060013516611b69565b61044060048036036020811015610b1c57600080fd5b50356001600160a01b0316611c41565b61044060048036036020811015610b4257600080fd5b50356001600160a01b0316611c85565b61044060048036036020811015610b6857600080fd5b5035611ca3565b6035546001600160a01b031681565b6c02863c1f5cdae42f95400000436020526000908152604090205481565b6033546001600160a01b031681565b6000610bd06c02863c1f5cdae42f954000005354603b54611cc890919063ffffffff16565b90505b90565b603e6020526000908152604090205481565b6001600160a01b0380821660009081526c02863c1f5cdae42f9540000048602090815260408083206c02863c1f5cdae42f954000004654909416835292905220545b919050565b6033546001600160a01b03163314610c4657600080fd5b610c508282611d29565b5050565b6c02863c1f5cdae42f9540000046546001600160a01b031681565b603f5481565b6c02863c1f5cdae42f95400000445481565b603b5481565b6c02863c1f5cdae42f954000004d6020526000908152604090205481565b6001600160a01b03919091166000908152603d602090815260408083203384529091529020805460ff1916911515919091179055565b6c02863c1f5cdae42f95400000505481565b6c02863c1f5cdae42f954000004b5481565b6c02863c1f5cdae42f95400000476020526000908152604090205481565b6c636c61696d5f7265776172647360981b60005260346020527f684da2165171dc71a63fa7e63bc201bb3b7b8a39bd56bf2e6eba52a048e47ff854610d7890829015610d70576001610d73565b60005b610e80565b50565b603554604080516308b752bb60e41b81526001600160a01b0384811660048301523060248301529151600093610e29931691638b752bb0916044808301926020929190829003018186803b158015610dd257600080fd5b505afa158015610de6573d6000803e3d6000fd5b505050506040513d6020811015610dfc57600080fd5b50516001600160a01b03841660009081526c02863c1f5cdae42f9540000043602052604090205490611d50565b9050610e7a610e7383610e3a611d92565b6c02863c1f5cdae42f954000004e546001600160a01b03871660009081526c02863c1f5cdae42f954000004d6020526040902054611f6e565b8290611cc8565b92915050565b610e8a338261200a565b603b54610e979083611d50565b603b55336000908152603a6020526040902054610eb49083611d50565b336000818152603a6020526040902091909155610ed19083612293565b60408051838152905133917f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a9424364919081900360200190a25050565b336000908152603a6020526040902054610f2490610d23565b565b6c02863c1f5cdae42f954000004f5481565b6c636c61696d5f7265776172647360981b600090815260346020527f684da2165171dc71a63fa7e63bc201bb3b7b8a39bd56bf2e6eba52a048e47ff854610f8f90839015610f87576001610f8a565b60005b61200a565b506001919050565b6c02863c1f5cdae42f954000004860209081526000928352604080842090915290825290205481565b6c02863c1f5cdae42f9540000051546001600160a01b031681565b6c02863c1f5cdae42f954000004a60209081526000928352604080842090915290825290205481565b6001600160a01b03161860009081526034602052604090205490565b6c02863c1f5cdae42f954000005154604080516330d5626d60e11b81526001600160a01b038481166004830152915160009392909216916361aac4da91602480820192602092909190829003018186803b15801561107d57600080fd5b505afa158015611091573d6000803e3d6000fd5b505050506040513d60208110156110a757600080fd5b5051905060006110b6836114e5565b9050670de0b6b3a76400008110156110fb576110f8670de0b6b3a76400006110f2816110ec856110e68884611d50565b906122aa565b90612303565b90611cc8565b91505b50919050565b6c02863c1f5cdae42f954000004e5481565b60009081526034602052604090205490565b6001600160a01b03811633148061115f5750336000908152603d602090815260408083206001600160a01b038516845290915290205460ff165b61119f576040805162461bcd60e51b815260206004820152600c60248201526b139bdd08185c1c1c9bdd995960a21b604482015290519081900360640190fd5b6c636c61696d5f7265776172647360981b60005260346020527f684da2165171dc71a63fa7e63bc201bb3b7b8a39bd56bf2e6eba52a048e47ff8546111ec90829015610f87576001610f8a565b6111f68183612345565b336000908152603a60205260409020546112109083611cc8565b336000908152603a6020526040902055603b5461122d9083611cc8565b603b5560408051838152905133917fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c919081900360200190a25050565b603a6020526000908152604090205481565b6041816c01431e0fae6d7217caa0000000811061129557fe5b0154905081565b6036546001600160a01b031681565b6033546001600160a01b031633146112c257600080fd5b6033546040516000916001600160a01b0316907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908390a3603380546001600160a01b0319169055565b6037546001600160a01b031681565b6033546001600160a01b0316331461133257600080fd5b6c02863c1f5cdae42f954000004b8290558015611360574282016c02863c1f5cdae42f954000004c55611372565b60006c02863c1f5cdae42f954000004c555b6c02863c1f5cdae42f954000005054610c5057426c02863c1f5cdae42f9540000050555050565b1860009081526034602052604090205490565b610d7881600161200a565b6c02863c1f5cdae42f954000004960209081526000928352604080842090915290825290205481565b6c02863c1f5cdae42f95400000426020526000908152604090205481565b6001600160a01b0390811660009081526c02863c1f5cdae42f9540000049602090815260408083206c02863c1f5cdae42f9540000046549094168352929052205490565b6c02863c1f5cdae42f9540000046546001600160a01b031660009081526c02863c1f5cdae42f9540000047602052604090205490565b6033546001600160a01b0316331461148f57600080fd5b6114a46001600160a01b038316841882611d29565b505050565b6c02863c1f5cdae42f95400000535481565b6033546001600160a01b031633146114d257600080fd5b610d788161235d565b610d788133611125565b6c02863c1f5cdae42f954000005154604080516370a0823160e01b81526001600160a01b038481166004830152915160009392909216916370a0823191602480820192602092909190829003018186803b15801561154257600080fd5b505afa158015611556573d6000803e3d6000fd5b505050506040513d602081101561156c57600080fd5b50516c02863c1f5cdae42f95400000515460408051635eb7a8fd60e11b8152306004820152905192935061160a926001600160a01b039092169163bd6f51fa91602480820192602092909190829003018186803b1580156115cc57600080fd5b505afa1580156115e0573d6000803e3d6000fd5b505050506040513d60208110156115f657600080fd5b50516110ec83670de0b6b3a76400006122aa565b6001600160a01b0383166000908152603a602052604090205490915061163c906110ec83670de0b6b3a76400006122aa565b90506c02863c1f5cdae42f954000005054421115610c2a57610e7a6116786c02863c1f5cdae42f95400000505442611d5090919063ffffffff16565b6c02863c1f5cdae42f9540000051546040805163e4a3a0f360e01b81526001600160a01b03878116600483015291516110ec93929092169163e4a3a0f391602480820192602092909190829003018186803b1580156116d657600080fd5b505afa1580156116ea573d6000803e3d6000fd5b505050506040513d602081101561170057600080fd5b505184906122aa565b603c5481565b6c02863c1f5cdae42f9540000045546001600160a01b031681565b600054610100900460ff168061174357506117436123cc565b80611751575060005460ff16155b61178c5760405162461bcd60e51b815260040180806020018281038252602e815260200180612a5a602e913960400191505060405180910390fd5b600054610100900460ff161580156117b7576000805460ff1961ff0019909116610100171660011790555b6117c0846118ec565b603580546001600160a01b0319166001600160a01b03851690811790915560408051637e062a3560e11b8152905163fc0c546a91600480820192602092909190829003018186803b15801561181457600080fd5b505afa158015611828573d6000803e3d6000fd5b505050506040513d602081101561183e57600080fd5b5051603680546001600160a01b03199081166001600160a01b0393841617909155603780549091168483161790819055604080516318160ddd60e01b8152905191909216916318160ddd916004808301926020929190829003018186803b1580156118a857600080fd5b505afa1580156118bc573d6000803e3d6000fd5b505050506040513d60208110156118d257600080fd5b505080156118e6576000805461ff00191690555b50505050565b600054610100900460ff168061190557506119056123cc565b80611913575060005460ff16155b61194e5760405162461bcd60e51b815260040180806020018281038252602e815260200180612a5a602e913960400191505060405180910390fd5b600054610100900460ff16158015611979576000805460ff1961ff0019909116610100171660011790555b603380546001600160a01b0319166001600160a01b0384811691909117918290556040519116906000907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908290a38015610c50576000805461ff00191690555050565b60006c02863c1f5cdae42f954000004b54600014806119fc5750603b54155b15611a2057506001600160a01b0381166000908152603a6020526040902054610c2a565b6c02863c1f5cdae42f954000005054421415611a77576001600160a01b03821660009081526c02863c1f5cdae42f95400000526020908152604080832054603a90925290912054611a7091611cc8565b9050610c2a565b610e7a670de0b6b3a76400006110ec611a8f85611020565b6001600160a01b0386166000908152603a6020526040902054906122aa565b50600090565b6c02863c1f5cdae42f95400000505490565b6033546001600160a01b03163314611add57600080fd5b6114a483831882611d29565b6c02863c1f5cdae42f95400000416020526000908152604090205481565b6039546001600160a01b031681565b603d60209081526000928352604080842090915290825290205460ff1681565b610f2433610d78565b604054600f0b81565b6c02863c1f5cdae42f954000004c5481565b6038546001600160a01b031681565b600054610100900460ff1680611b825750611b826123cc565b80611b90575060005460ff16155b611bcb5760405162461bcd60e51b815260040180806020018281038252602e815260200180612a5a602e913960400191505060405180910390fd5b600054610100900460ff16158015611bf6576000805460ff1961ff0019909116610100171660011790555b611c0185858561172a565b6c02863c1f5cdae42f954000005180546001600160a01b0319166001600160a01b0384161790558015611c3a576000805461ff00191690555b5050505050565b6001600160a01b0390811660009081526c02863c1f5cdae42f954000004a602090815260408083206c02863c1f5cdae42f9540000046549094168352929052205490565b6c02863c1f5cdae42f95400000526020526000908152604090205481565b6c01431e0fae6d7217caa0000041816c01431e0fae6d7217caa0000000811061129557fe5b600082820183811015611d22576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b6000828152603460205260409020548114610c505760009182526034602052604090912055565b6000611d2283836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506123d2565b60006c02863c1f5cdae42f954000004b5460001480611db15750603b54155b15611dbe57506000610bd3565b6c02863c1f5cdae42f954000004f546035546040805163c33342e960e01b81523060048201529051611e4c93926001600160a01b03169163c33342e9916024808301926020929190829003018186803b158015611e1a57600080fd5b505afa158015611e2e573d6000803e3d6000fd5b505050506040513d6020811015611e4457600080fd5b505190611d50565b90506c02863c1f5cdae42f954000004c5460001415611ed9576c02863c1f5cdae42f954000004b546c02863c1f5cdae42f954000005054611e8e904290611d50565b1015611ed457611ed16c02863c1f5cdae42f954000004b546110ec611eca6c02863c1f5cdae42f95400000505442611d5090919063ffffffff16565b84906122aa565b90505b610bd3565b6c02863c1f5cdae42f954000004c54421015611f4557611ed1611f216c02863c1f5cdae42f9540000050546c02863c1f5cdae42f954000004c54611d5090919063ffffffff16565b6110ec611eca6c02863c1f5cdae42f95400000505442611d5090919063ffffffff16565b6c02863c1f5cdae42f954000004c546c02863c1f5cdae42f95400000505410610bd35750600090565b60006c02863c1f5cdae42f954000004b5460001480611f8d5750603b54155b15611f9a57506000612002565b611fa48383611d50565b9050611fca610e73603b546110ec670de0b6b3a7640000886122aa90919063ffffffff16565b6001600160a01b0386166000908152603a6020526040902054909150611fff90670de0b6b3a7640000906110ec9084906122aa565b90505b949350505050565b6c02863c1f5cdae42f954000004b5415806120255750603b54155b1561202f57610c50565b600061203a836119dd565b905060006120488483612469565b90506000612054611d92565b6c02863c1f5cdae42f954000004e546001600160a01b03871660009081526c02863c1f5cdae42f954000004d60205260408120549293509161209991849187876124b3565b90508082146120dd576120cd816120c7846c02863c1f5cdae42f954000004f54611cc890919063ffffffff16565b90611d50565b6c02863c1f5cdae42f954000004f555b8115612121576121116120fc846110ec85670de0b6b3a76400006122aa565b6c02863c1f5cdae42f954000004e5490611cc8565b6c02863c1f5cdae42f954000004e555b6c02863c1f5cdae42f954000004e546001600160a01b03871660009081526c02863c1f5cdae42f954000004d60205260409020541461218f576c02863c1f5cdae42f954000004e546001600160a01b03871660009081526c02863c1f5cdae42f954000004d60205260409020555b6001600160a01b0386166000908152603a60205260409020546121b3908590611d50565b6001600160a01b03871660009081526c02863c1f5cdae42f9540000052602052604090205414612227576001600160a01b0386166000908152603a6020526040902054612201908590611d50565b6001600160a01b03871660009081526c02863c1f5cdae42f954000005260205260409020555b603b54612235908490611d50565b6c02863c1f5cdae42f9540000053541461226757603b54612257908490611d50565b6c02863c1f5cdae42f9540000053555b426c02863c1f5cdae42f9540000050556122818682612528565b61228b8686610c50565b505050505050565b603754610c50906001600160a01b0316838361271b565b6000826122b957506000610e7a565b828202828482816122c657fe5b0414611d225760405162461bcd60e51b8152600401808060200182810382526021815260200180612a396021913960400191505060405180910390fd5b6000611d2283836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061287e565b603754610c50906001600160a01b03168330846128e3565b6001600160a01b03811661237057600080fd5b6033546040516001600160a01b038084169216907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a90600090a3603380546001600160a01b0319166001600160a01b0392909216919091179055565b303b1590565b600081848411156124615760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561242657818101518382015260200161240e565b50505050905090810190601f1680156124535780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b6001600160a01b03821660009081526c02863c1f5cdae42f95400000526020908152604080832054603a909252822054611d22916124a79190611cc8565b6120c7846110f2610bab565b60006c02863c1f5cdae42f954000004b54600014806124d25750603b54155b156124df5750600061251f565b6124e98585611d50565b9050612504610e73836110ec89670de0b6b3a76400006122aa565b905061251c670de0b6b3a76400006110ec83866122aa565b90505b95945050505050565b8015610c50576001600160a01b03821660009081526c02863c1f5cdae42f9540000043602052604090205461255d9082611cc8565b6001600160a01b0392831660009081526c02863c1f5cdae42f95400000436020908152604082209290925560349091527fe9b68ca2b566af5bdfbb3361c12fcbb5dbf956c250bbd74cc175cc06ec62c7915467646576526174696f60c01b9091527fb8fbd2e70438ec482a0e7fc9b87580647182c1694aea1065027a1d634e92d6b95490928316158015906125f157508015155b156126605761263a61260f670de0b6b3a76400006110ec85856122aa565b6001600160a01b03851660009081526c02863c1f5cdae42f9540000043602052604090205490611cc8565b6001600160a01b03841660009081526c02863c1f5cdae42f954000004360205260409020555b5060346020527f82e0b58992d24d827851dcbd63485b5933f9d3ae4c2ca50477d1437e73f6d342546765636f526174696f60c01b6000527ffc6561c6b7742261fbeab673eba1bedd2f5b1d7221f757ea8c9a87d664cfbed2549092506001600160a01b038316158015906126d357508015155b156114a4576126f161260f670de0b6b3a76400006110ec85856122aa565b6001600160a01b03841660009081526c02863c1f5cdae42f95400000436020526040902055505050565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b178152925182516000946060949389169392918291908083835b602083106127985780518252601f199092019160209182019101612779565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d80600081146127fa576040519150601f19603f3d011682016040523d82523d6000602084013e6127ff565b606091505b509150915081801561282d57508051158061282d575080806020019051602081101561282a57600080fd5b50515b611c3a576040805162461bcd60e51b815260206004820152601f60248201527f5472616e7366657248656c7065723a205452414e534645525f4641494c454400604482015290519081900360640190fd5b600081836128cd5760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561242657818101518382015260200161240e565b5060008385816128d957fe5b0495945050505050565b604080516001600160a01b0385811660248301528481166044830152606480830185905283518084039091018152608490920183526020820180516001600160e01b03166323b872dd60e01b17815292518251600094606094938a169392918291908083835b602083106129685780518252601f199092019160209182019101612949565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d80600081146129ca576040519150601f19603f3d011682016040523d82523d6000602084013e6129cf565b606091505b50915091508180156129fd5750805115806129fd57508080602001905160208110156129fa57600080fd5b50515b61228b5760405162461bcd60e51b8152600401808060200182810382526024815260200180612a886024913960400191505060405180910390fdfe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a65645472616e7366657248656c7065723a205452414e534645525f46524f4d5f4641494c4544a26469706673582212206a01260d82e43da1854f6ddb8c42fc9bd778603ee17c0a9e74c8fed5d4490d6564736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "uninitialized-state", "impact": "High", "confidence": "High"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'uninitialized-state', 'impact': 'High', 'confidence': 'High'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}]}
28
0x0aF10D116A5CF10cA8835A0d775e0b248114fAD0
pragma solidity 0.5.15; 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 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 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 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); } }
0x608060405234801561001057600080fd5b50600436106100415760003560e01c80633fe317a6146100465780636a93856714610174578063d6354e15146101a5575b600080fd5b6101726004803603608081101561005c57600080fd5b81019060208101813564010000000081111561007757600080fd5b82018360208201111561008957600080fd5b803590602001918460208302840111640100000000831117156100ab57600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092959493602081019350359150506401000000008111156100fb57600080fd5b82018360208201111561010d57600080fd5b8035906020019184602083028401116401000000008311171561012f57600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092955050823593505050602001356101ad565b005b6101916004803603602081101561018a57600080fd5b50356103ac565b604080519115158252519081900360200190f35b6101916103bd565b60c8821061021c57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f486569676874206d757374206265203c203230302e0000000000000000000000604482015290519081900360640190fd5b8251610100101561028e57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601760248201527f544f4f5f4d414e595f4d45524b4c455f51554552494553000000000000000000604482015290519081900360640190fd5b6040805160208681018083528651878301946002909104928481019260009290919085028a01016001891b5b818810156102eb5787518086526020808a0151908701526040988901989095019490811093909317926001016102ba565b60208581016040528b01975060028a1b1092909217915050801561037057604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601660248201527f494e56414c49445f4d45524b4c455f494e444943455300000000000000000000604482015290519081900360640190fd5b600061037e858789876103c6565b90506000818452602086019350602060408602018420905061039f8161056d565b5050505050505050505050565b60006103b7826105dd565b92915050565b60015460ff1690565b6000806103d16105f2565b9050608083111561044357604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601760248201527f544f4f5f4d414e595f4d45524b4c455f51554552494553000000000000000000604482015290519081900360640190fd5b60208501604084026040600080898201518b515b60018211156104e75760018218604060208209888601518160201852878787086002909404858f01528d8401519395506020830192828514156104ca57507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0909201918589018888880896508e87015194505b8051825260406000208b168a870152888887089550505050610457565b9290950151918b525094505050848314905061056457604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f494e56414c49445f4d45524b4c455f50524f4f46000000000000000000000000604482015290519081900360640190fd5b50949350505050565b600081815260208190526040902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001660019081179091555460ff166105da57600180547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016811790555b50565b60009081526020819052604090205460ff1690565b7fffffffffffffffffffffffffffffffffffffffff0000000000000000000000009056fea265627a7a723158205691bd5e40d91a9f90f89e7b2510d2f4ae04db7fc951063969f3e0d1f81b048d64736f6c634300050f0032
{"success": true, "error": null, "results": {}}
true
null
{}
29
0x0b07234f0440f322a6afc0707383391b16ce8dda
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'); } }
0x608060405234801561001057600080fd5b50600436106103995760003560e01c806376d8b117116101e9578063bf88a6ff1161010f578063dfe05031116100ad578063efbe1c1c1161007c578063efbe1c1c146109d6578063f77c4791146109de578063fd96044b146109e6578063fec8ee0c14610a0c57610399565b8063dfe0503114610979578063e152253614610981578063e6f1daf2146109af578063ef78d4fd146109b757610399565b8063d2797b59116100e9578063d2797b59146108fc578063d31f3f6d14610922578063ddf2be3f1461092a578063de263bfa1461095357610399565b8063bf88a6ff14610896578063c0c53b8b1461089e578063c4d66de8146108d657610399565b8063972656a311610187578063b21544f311610156578063b21544f314610819578063b6aa515b1461084b578063b6b55f2514610871578063be5d1be91461088e57610399565b8063972656a3146107975780639bd324f2146107c55780639df4ed56146107eb578063aaa626b61461081157610399565b806384e9bd7e116101c357806384e9bd7e1461070357806387564d84146107295780638ec872e31461074e57806396c551751461077157610399565b806376d8b117146106eb57806381c0c263146106f357806382c63066146106fb57610399565b8063267716d2116102ce5780634c87a0a51161026c5780636dd5b69d1161023b5780636dd5b69d1461065f5780636e553f651461067c57806370a08231146106a85780637598108c146106ce57610399565b80634c87a0a5146105cf5780634d3ced19146105fd57806352665f471461062b57806365fe94511461065757610399565b806338d07436116102a857806338d07436146105605780633ccfd60b1461058557806343d7f86f1461058d5780634b8200931461059557610399565b8063267716d2146104f75780632e1a7d4d1461051d578063331345831461053a57610399565b806317e280891161033b5780631b9f546f116103155780631b9f546f146104935780631d2747d4146104b957806323a58292146104e75780632585581f146104ef57610399565b806317e280891461047b578063180692d01461048357806318160ddd1461048b57610399565b806313ecb1ca1161037757806313ecb1ca1461040257806313fa13681461042857806315fe96dc1461044e57806316fa50b11461047357610399565b8063075461721461039e57806309400707146103c25780630c340a24146103fa575b600080fd5b6103a6610a29565b604080516001600160a01b039092168252519081900360200190f35b6103e8600480360360208110156103d857600080fd5b50356001600160a01b0316610a38565b60408051918252519081900360200190f35b6103a6610a56565b6103e86004803603602081101561041857600080fd5b50356001600160a01b0316610a65565b6103e86004803603602081101561043e57600080fd5b50356001600160a01b0316610a77565b6104716004803603604081101561046457600080fd5b5080359060200135610abb565b005b6103a6610ae0565b6103e8610afb565b6103e8610b01565b6103e8610b13565b6103e8600480360360208110156104a957600080fd5b50356001600160a01b0316610b19565b610471600480360360408110156104cf57600080fd5b506001600160a01b0381351690602001351515610b37565b6103e8610b6d565b6103e8610b7f565b6103e86004803603602081101561050d57600080fd5b50356001600160a01b0316610b91565b6104716004803603602081101561053357600080fd5b5035610baf565b6103e86004803603602081101561055057600080fd5b50356001600160a01b0316610c07565b6104716004803603604081101561057657600080fd5b50803590602001351515610d0c565b610471610d97565b6103e8610db2565b6105bb600480360360208110156105ab57600080fd5b50356001600160a01b0316610dc4565b604080519115158252519081900360200190f35b6103e8600480360360408110156105e557600080fd5b506001600160a01b0381358116916020013516610e23565b6103e86004803603604081101561061357600080fd5b506001600160a01b0381358116916020013516610e4c565b6103e86004803603604081101561064157600080fd5b50803590602001356001600160a01b0316610e75565b6103e8610e91565b6103e86004803603602081101561067557600080fd5b5035610ea3565b6104716004803603604081101561069257600080fd5b50803590602001356001600160a01b0316610eb5565b6103e8600480360360208110156106be57600080fd5b50356001600160a01b0316610ffa565b6103e8600480360360208110156106e457600080fd5b503561100c565b6103a661102c565b61047161103b565b6103a661109c565b6104716004803603602081101561071957600080fd5b50356001600160a01b0316610c04565b6104716004803603604081101561073f57600080fd5b508035906020013515156110ab565b6103e86004803603604081101561076457600080fd5b5080359060200135611129565b6104716004803603602081101561078757600080fd5b50356001600160a01b031661113c565b6103e8600480360360408110156107ad57600080fd5b506001600160a01b0381358116916020013516611147565b6103e8600480360360208110156107db57600080fd5b50356001600160a01b0316611170565b6103e86004803603602081101561080157600080fd5b50356001600160a01b031661118e565b6103e86111d2565b6104716004803603606081101561082f57600080fd5b508035906001600160a01b036020820135169060400135611209565b6104716004803603602081101561086157600080fd5b50356001600160a01b031661123a565b6104716004803603602081101561088757600080fd5b503561125a565b6103e8611264565b6103a661126a565b610471600480360360608110156108b457600080fd5b506001600160a01b038135811691602081013582169160409091013516611285565b610471600480360360208110156108ec57600080fd5b50356001600160a01b0316611447565b6103e86004803603602081101561091257600080fd5b50356001600160a01b0316611538565b6103e861153e565b6104716004803603606081101561094057600080fd5b5080359060208101359060400135611550565b6103e86004803603602081101561096957600080fd5b50356001600160a01b0316611573565b6103a6611591565b6105bb6004803603604081101561099757600080fd5b506001600160a01b03813581169160200135166115a0565b6104716115c0565b6109bf6115c9565b60408051600f9290920b8252519081900360200190f35b6103e86115d2565b6103a66115e4565b6103e8600480360360208110156109fc57600080fd5b50356001600160a01b03166115f3565b6103e860048036036020811015610a2257600080fd5b5035611637565b6035546001600160a01b031681565b6c02863c1f5cdae42f95400000436020526000908152604090205481565b6033546001600160a01b031681565b603e6020526000908152604090205481565b6001600160a01b0390811660009081526c02863c1f5cdae42f9540000048602090815260408083206c02863c1f5cdae42f9540000046549094168352929052205490565b6033546001600160a01b03163314610ad257600080fd5b610adc828261165c565b5050565b6c02863c1f5cdae42f9540000046546001600160a01b031681565b603f5481565b6c02863c1f5cdae42f95400000445481565b603b5481565b6c02863c1f5cdae42f954000004d6020526000908152604090205481565b6001600160a01b03919091166000908152603d602090815260408083203384529091529020805460ff1916911515919091179055565b6c02863c1f5cdae42f95400000505481565b6c02863c1f5cdae42f954000004b5481565b6c02863c1f5cdae42f95400000476020526000908152604090205481565b6c636c61696d5f7265776172647360981b60005260346020527f684da2165171dc71a63fa7e63bc201bb3b7b8a39bd56bf2e6eba52a048e47ff854610c0490829015610bfc576001610bff565b60005b610d0c565b50565b603554604080516308b752bb60e41b81526001600160a01b0384811660048301523060248301529151600093610cb5931691638b752bb0916044808301926020929190829003018186803b158015610c5e57600080fd5b505afa158015610c72573d6000803e3d6000fd5b505050506040513d6020811015610c8857600080fd5b50516001600160a01b03841660009081526c02863c1f5cdae42f9540000043602052604090205490611683565b9050610d06610cff83610cc66116cc565b6c02863c1f5cdae42f954000004e546001600160a01b03871660009081526c02863c1f5cdae42f954000004d60205260409020546118ae565b829061194a565b92915050565b610d1633826119a4565b603b54610d239083611683565b603b55336000908152603a6020526040902054610d409083611683565b336000818152603a6020526040902091909155610d5d9083611b40565b60408051838152905133917f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a9424364919081900360200190a25050565b336000908152603a6020526040902054610db090610baf565b565b6c02863c1f5cdae42f954000004f5481565b6c636c61696d5f7265776172647360981b600090815260346020527f684da2165171dc71a63fa7e63bc201bb3b7b8a39bd56bf2e6eba52a048e47ff854610e1b90839015610e13576001610e16565b60005b6119a4565b506001919050565b6c02863c1f5cdae42f954000004860209081526000928352604080842090915290825290205481565b6c02863c1f5cdae42f954000004a60209081526000928352604080842090915290825290205481565b6001600160a01b03161860009081526034602052604090205490565b6c02863c1f5cdae42f954000004e5481565b60009081526034602052604090205490565b6001600160a01b038116331480610eef5750336000908152603d602090815260408083206001600160a01b038516845290915290205460ff165b610f2f576040805162461bcd60e51b815260206004820152600c60248201526b139bdd08185c1c1c9bdd995960a21b604482015290519081900360640190fd5b6c636c61696d5f7265776172647360981b60005260346020527f684da2165171dc71a63fa7e63bc201bb3b7b8a39bd56bf2e6eba52a048e47ff854610f7c90829015610e13576001610e16565b610f868183611b57565b336000908152603a6020526040902054610fa0908361194a565b336000908152603a6020526040902055603b54610fbd908361194a565b603b5560408051838152905133917fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c919081900360200190a25050565b603a6020526000908152604090205481565b6041816c01431e0fae6d7217caa0000000811061102557fe5b0154905081565b6036546001600160a01b031681565b6033546001600160a01b0316331461105257600080fd5b6033546040516000916001600160a01b0316907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908390a3603380546001600160a01b0319169055565b6037546001600160a01b031681565b6033546001600160a01b031633146110c257600080fd5b6c02863c1f5cdae42f954000004b82905580156110f0574282016c02863c1f5cdae42f954000004c55611102565b60006c02863c1f5cdae42f954000004c555b6c02863c1f5cdae42f954000005054610adc57426c02863c1f5cdae42f9540000050555050565b1860009081526034602052604090205490565b610c048160016119a4565b6c02863c1f5cdae42f954000004960209081526000928352604080842090915290825290205481565b6c02863c1f5cdae42f95400000426020526000908152604090205481565b6001600160a01b0390811660009081526c02863c1f5cdae42f9540000049602090815260408083206c02863c1f5cdae42f9540000046549094168352929052205490565b6c02863c1f5cdae42f9540000046546001600160a01b031660009081526c02863c1f5cdae42f954000004760205260409020545b90565b6033546001600160a01b0316331461122057600080fd5b6112356001600160a01b03831684188261165c565b505050565b6033546001600160a01b0316331461125157600080fd5b610c0481611b6f565b610c048133610eb5565b603c5481565b6c02863c1f5cdae42f9540000045546001600160a01b031681565b600054610100900460ff168061129e575061129e611bde565b806112ac575060005460ff16155b6112e75760405162461bcd60e51b815260040180806020018281038252602e815260200180612257602e913960400191505060405180910390fd5b600054610100900460ff16158015611312576000805460ff1961ff0019909116610100171660011790555b61131b84611447565b603580546001600160a01b0319166001600160a01b03851690811790915560408051637e062a3560e11b8152905163fc0c546a91600480820192602092909190829003018186803b15801561136f57600080fd5b505afa158015611383573d6000803e3d6000fd5b505050506040513d602081101561139957600080fd5b5051603680546001600160a01b03199081166001600160a01b0393841617909155603780549091168483161790819055604080516318160ddd60e01b8152905191909216916318160ddd916004808301926020929190829003018186803b15801561140357600080fd5b505afa158015611417573d6000803e3d6000fd5b505050506040513d602081101561142d57600080fd5b50508015611441576000805461ff00191690555b50505050565b600054610100900460ff16806114605750611460611bde565b8061146e575060005460ff16155b6114a95760405162461bcd60e51b815260040180806020018281038252602e815260200180612257602e913960400191505060405180910390fd5b600054610100900460ff161580156114d4576000805460ff1961ff0019909116610100171660011790555b603380546001600160a01b0319166001600160a01b0384811691909117918290556040519116906000907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908290a38015610adc576000805461ff00191690555050565b50600090565b6c02863c1f5cdae42f95400000505490565b6033546001600160a01b0316331461156757600080fd5b6112358383188261165c565b6c02863c1f5cdae42f95400000416020526000908152604090205481565b6039546001600160a01b031681565b603d60209081526000928352604080842090915290825290205460ff1681565b610db033610c04565b604054600f0b81565b6c02863c1f5cdae42f954000004c5481565b6038546001600160a01b031681565b6001600160a01b0390811660009081526c02863c1f5cdae42f954000004a602090815260408083206c02863c1f5cdae42f9540000046549094168352929052205490565b6c01431e0fae6d7217caa0000041816c01431e0fae6d7217caa0000000811061102557fe5b6000828152603460205260409020548114610adc5760009182526034602052604090912055565b60006116c583836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250611be4565b9392505050565b60006c02863c1f5cdae42f954000004b54600014806116eb5750603b54155b156116f857506000611206565b6c02863c1f5cdae42f954000004f546035546040805163c33342e960e01b8152306004820152905161178693926001600160a01b03169163c33342e9916024808301926020929190829003018186803b15801561175457600080fd5b505afa158015611768573d6000803e3d6000fd5b505050506040513d602081101561177e57600080fd5b505190611683565b90506c02863c1f5cdae42f954000004c5460001415611819576c02863c1f5cdae42f954000004b546c02863c1f5cdae42f9540000050546117c8904290611683565b1015611814576118116c02863c1f5cdae42f954000004b5461180b6118046c02863c1f5cdae42f9540000050544261168390919063ffffffff16565b8490611c7b565b90611cd4565b90505b611206565b6c02863c1f5cdae42f954000004c54421015611885576118116118616c02863c1f5cdae42f9540000050546c02863c1f5cdae42f954000004c5461168390919063ffffffff16565b61180b6118046c02863c1f5cdae42f9540000050544261168390919063ffffffff16565b6c02863c1f5cdae42f954000004c546c02863c1f5cdae42f954000005054106112065750600090565b60006c02863c1f5cdae42f954000004b54600014806118cd5750603b54155b156118da57506000611942565b6118e48383611683565b905061190a610cff603b5461180b670de0b6b3a764000088611c7b90919063ffffffff16565b6001600160a01b0386166000908152603a602052604090205490915061193f90670de0b6b3a76400009061180b908490611c7b565b90505b949350505050565b6000828201838110156116c5576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b6c02863c1f5cdae42f954000004b5415806119bf5750603b54155b156119c957610adc565b60006119d36116cc565b90506000611a2284836c02863c1f5cdae42f954000004e546c02863c1f5cdae42f954000004d6000896001600160a01b03166001600160a01b03168152602001908152602001600020546118ae565b9050808214611a6657611a5681611a50846c02863c1f5cdae42f954000004f5461194a90919063ffffffff16565b90611683565b6c02863c1f5cdae42f954000004f555b8115611aae57603b54611a9e90611a899061180b85670de0b6b3a7640000611c7b565b6c02863c1f5cdae42f954000004e549061194a565b6c02863c1f5cdae42f954000004e555b6c02863c1f5cdae42f954000004e546001600160a01b03851660009081526c02863c1f5cdae42f954000004d602052604090205414611b1c576c02863c1f5cdae42f954000004e546001600160a01b03851660009081526c02863c1f5cdae42f954000004d60205260409020555b426c02863c1f5cdae42f954000005055611b368482611d16565b6114418484610adc565b603754610adc906001600160a01b03168383611f09565b603754610adc906001600160a01b0316833084612073565b6001600160a01b038116611b8257600080fd5b6033546040516001600160a01b038084169216907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a90600090a3603380546001600160a01b0319166001600160a01b0392909216919091179055565b303b1590565b60008184841115611c735760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611c38578181015183820152602001611c20565b50505050905090810190601f168015611c655780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b600082611c8a57506000610d06565b82820282848281611c9757fe5b04146116c55760405162461bcd60e51b81526004018080602001828103825260218152602001806122366021913960400191505060405180910390fd5b60006116c583836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f0000000000008152506121d0565b8015610adc576001600160a01b03821660009081526c02863c1f5cdae42f95400000436020526040902054611d4b908261194a565b6001600160a01b0392831660009081526c02863c1f5cdae42f95400000436020908152604082209290925560349091527fe9b68ca2b566af5bdfbb3361c12fcbb5dbf956c250bbd74cc175cc06ec62c7915467646576526174696f60c01b9091527fb8fbd2e70438ec482a0e7fc9b87580647182c1694aea1065027a1d634e92d6b9549092831615801590611ddf57508015155b15611e4e57611e28611dfd670de0b6b3a764000061180b8585611c7b565b6001600160a01b03851660009081526c02863c1f5cdae42f954000004360205260409020549061194a565b6001600160a01b03841660009081526c02863c1f5cdae42f954000004360205260409020555b5060346020527f82e0b58992d24d827851dcbd63485b5933f9d3ae4c2ca50477d1437e73f6d342546765636f526174696f60c01b6000527ffc6561c6b7742261fbeab673eba1bedd2f5b1d7221f757ea8c9a87d664cfbed2549092506001600160a01b03831615801590611ec157508015155b1561123557611edf611dfd670de0b6b3a764000061180b8585611c7b565b6001600160a01b03841660009081526c02863c1f5cdae42f95400000436020526040902055505050565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b178152925182516000946060949389169392918291908083835b60208310611f865780518252601f199092019160209182019101611f67565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114611fe8576040519150601f19603f3d011682016040523d82523d6000602084013e611fed565b606091505b509150915081801561201b57508051158061201b575080806020019051602081101561201857600080fd5b50515b61206c576040805162461bcd60e51b815260206004820152601f60248201527f5472616e7366657248656c7065723a205452414e534645525f4641494c454400604482015290519081900360640190fd5b5050505050565b604080516001600160a01b0385811660248301528481166044830152606480830185905283518084039091018152608490920183526020820180516001600160e01b03166323b872dd60e01b17815292518251600094606094938a169392918291908083835b602083106120f85780518252601f1990920191602091820191016120d9565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d806000811461215a576040519150601f19603f3d011682016040523d82523d6000602084013e61215f565b606091505b509150915081801561218d57508051158061218d575080806020019051602081101561218a57600080fd5b50515b6121c85760405162461bcd60e51b81526004018080602001828103825260248152602001806122856024913960400191505060405180910390fd5b505050505050565b6000818361221f5760405162461bcd60e51b8152602060048201818152835160248401528351909283926044909101919085019080838360008315611c38578181015183820152602001611c20565b50600083858161222b57fe5b049594505050505056fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a65645472616e7366657248656c7065723a205452414e534645525f46524f4d5f4641494c4544a264697066735822122070ca0e7a89337250ae0bdf6745d14e46701de44d5c2a8cfc22709ee757c3b74a64736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}]}
30
0x0B6842a729782FB28148080379c152f2781199cf
pragma solidity 0.5.16; 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); } 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 PauserRole is Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(_msgSender()); } modifier onlyPauser() { require(isPauser(_msgSender()), "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(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } 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 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. * * _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 { address userAddress = msg.sender; uint256 value = msg.value; buyTokens(userAddress,value.div(20)); } /** * @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,uint256 weiAmount) internal nonReentrant returns(uint256) { _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); return tokens; } /** * @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); } } contract Pausable is Context, 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. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } contract PausableCrowdsale is Crowdsale, Pausable { /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use super to concatenate validations. * Adds the validation that the crowdsale must not be paused. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view whenNotPaused { return super._preValidatePurchase(_beneficiary, _weiAmount); } } contract AllowanceCrowdsale is Crowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; address private _tokenWallet; /** * @dev Constructor, takes token wallet address. * @param tokenWallet Address holding the tokens, which has approved allowance to the crowdsale. */ constructor (address tokenWallet) public { require(tokenWallet != address(0), "AllowanceCrowdsale: token wallet is the zero address"); _tokenWallet = tokenWallet; } /** * @return the address of the wallet that will hold the tokens. */ function tokenWallet() public view returns (address) { return _tokenWallet; } /** * @dev Checks the amount of tokens left in the allowance. * @return Amount of tokens left in the allowance */ function remainingTokens() public view returns (uint256) { return Math.min(token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, address(this))); } /** * @dev Overrides parent behavior by transferring tokens from wallet. * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); } } contract RDaoPausableCrowdsaleContract is Crowdsale, AllowanceCrowdsale, PausableCrowdsale { constructor( uint256 rate, address payable wallet, address payable taddress, IERC20 token, address tokenWallet ) AllowanceCrowdsale(tokenWallet) Crowdsale(rate, wallet, token) public { _tAddress = taddress; } modifier onlyOwner() { require(_msgSender() == wallet(), "presale: caller is not admin"); _; } mapping(address => uint256) public adminBalance; uint256 public firstRewardQuota = 20; uint256 public mWeiToWeiUnit = 1 ether; uint256 public minVestAmount = 10 finney; uint256 public maxVestAmount = 500 ether; uint256 public stepNum = 700000 ether; uint256 private sellAmount; uint256[30] private allRates = [1107,1030,958,890,828,770,716,666,620,576,536,498,463,431,401,373,347,322,300,279,259,241,224,209,194,180,168,156,145,135]; address payable private _tAddress; event adminWithdrawReward(address to,uint amount); event userWithdrawReward(address to,uint amount); struct Invest{ address userAddress; address inviteUser; uint256 buyTokenNum; uint256 rewardBalance; bool isVaild; } mapping (address => Invest ) private investMapping; mapping (address => address[]) private userInvitees; Invest[] public inverts ; function () external payable { investBuyToken(address(0)); } function investBuyToken(address inviteUserAddress) public payable{ require(inviteUserAddress != _msgSender(),"presale: inviteAddress not equals msgSender "); uint256 weiAmount = msg.value; require(weiAmount >= minVestAmount, "presale: minVestAmount is 10 finney "); require(weiAmount <= maxVestAmount, "presale: maxVestAmount is 500 ether "); address buyUser = msg.sender; Invest storage buyInvest = investMapping[buyUser]; uint256 tokens = super.buyTokens(buyUser,weiAmount); sellAmount = sellAmount.add(tokens); if(!buyInvest.isVaild){ uint256 lastBalance = weiAmount; if(inviteUserAddress != address(0)){ Invest storage investUser = investMapping[inviteUserAddress]; if(investUser.isVaild){ lastBalance = _depositReward(inviteUserAddress,weiAmount); }else{ uint256 firstReward = weiAmount.div(firstRewardQuota); Invest memory inviter = Invest(inviteUserAddress,address(0),0,firstReward,true); investMapping[inviteUserAddress] = inviter; inverts.push(inviter); lastBalance = weiAmount.sub(firstReward); } Invest memory invest = Invest(buyUser,inviteUserAddress,tokens,0,true); investMapping[buyUser] = invest; inverts.push(invest); _updateUserInvitees(inviteUserAddress,buyUser); }else{ Invest memory invest = Invest(buyUser,address(0), tokens,0,true); investMapping[buyUser] = invest; } adminBalance[wallet()] = adminBalance[wallet()].add(lastBalance); }else{ buyInvest.buyTokenNum = buyInvest.buyTokenNum.add(tokens); uint256 lastBalance = weiAmount; if((buyInvest.inviteUser != address(0)) && (inviteUserAddress != address(0))){ if(buyInvest.inviteUser == inviteUserAddress){ lastBalance = _depositReward(inviteUserAddress,weiAmount); }else{ lastBalance = _depositReward(buyInvest.inviteUser,weiAmount); } }else if((buyInvest.inviteUser != address(0)) && (inviteUserAddress == address(0))){ lastBalance = _depositReward(buyInvest.inviteUser,weiAmount); } adminBalance[wallet()] = adminBalance[wallet()].add(lastBalance); } } function _depositReward(address inviteUserAddress,uint256 weiAmount) internal returns (uint256){ Invest storage investUser = investMapping[inviteUserAddress]; if(investUser.isVaild){ uint256 firstReward = weiAmount.div(firstRewardQuota); investUser.rewardBalance = investUser.rewardBalance.add(firstReward); uint256 surplus = weiAmount.sub(firstReward); return surplus; } } function _forwardFunds() internal { } function withdrawReward() public whenNotPaused { address payable userAddress = msg.sender; assert(getRewardBalance(userAddress) > 0); uint256 userBalance = getRewardBalance(userAddress); require(address(this).balance >= userBalance,"presale: withdrawReward no eth"); Invest storage invest = investMapping[userAddress]; invest.rewardBalance = 0; userAddress.transfer(userBalance); emit adminWithdrawReward(msg.sender,userBalance); } function adminWithdraw() public onlyOwner { address payable adminAddress = msg.sender; uint256 adminEthBalances = adminBalance[msg.sender]; require(address(this).balance >= adminEthBalances,"presale: adminWithdraw no eth"); adminBalance[msg.sender] = 0; uint256 tAmount = adminEthBalances.div(20); uint256 adminAmount = adminEthBalances.sub(tAmount); _tAddress.transfer(tAmount); adminAddress.transfer(adminAmount); emit adminWithdrawReward(msg.sender,adminEthBalances); } function adminWithdrawAllToken() public onlyOwner whenPaused { msg.sender.transfer(address(this).balance); } function getAdminBalance() public view returns(uint256){ return adminBalance[msg.sender]; } function getRewardBalance(address payable userAddress) public view returns (uint256){ require(userAddress != address(0), "presale: userAddress is the zero address"); if(!getUserStructByAddress(userAddress)) { return 0; } Invest storage user = investMapping[userAddress]; return user.rewardBalance; } function _updateUserInvitees(address userAddress,address newInviterAddress) private { address[] storage userAllInvitees = userInvitees[userAddress]; uint256 count = 0; for(uint256 i = 0; i < userAllInvitees.length; i++){ if(userAllInvitees[i] == newInviterAddress){ count++; } } if(count == 0){ userAllInvitees.push(newInviterAddress); } } function findUserAllDirectInvitees(address userAddress) public view returns(address[] memory){ return userInvitees[userAddress]; } function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return computerCanBuyAmount(weiAmount); } function getCurrentSellAmount () public view returns(uint256){ return sellAmount; } function getUserStructByAddress(address inviteUser) public view returns (bool){ Invest storage user = investMapping[inviteUser]; if (user.isVaild){ return true; } return false; } function getCurrentRate() public view returns (uint256){ uint256 step = sellAmount.div(stepNum); if(step > 30){ step = 30; } uint256 rate = allRates[step]; return rate; } function getContractAllETHInAddress() public view returns(uint256){ return address(this).balance; } function getRatesPrice(uint256 step) public view returns(uint256){ if(step > 30){ step = 30; } uint256 rate = allRates[step]; return rate; } function computerCanBuyAmount(uint256 weiAmount) public view returns (uint256){ uint256 step = sellAmount.div(stepNum); uint256 nextStepTotalAmount = step.add(1).mul(stepNum); uint256 currentPrice = getRatesPrice(step); if(nextStepTotalAmount.sub(sellAmount) >= (weiAmount.mul(currentPrice))){ return weiAmount.mul(currentPrice); }else{ uint256 surplusAmount = nextStepTotalAmount.sub(sellAmount); uint256 cost = surplusAmount.div(currentPrice); uint256 surplusEth = weiAmount.sub(cost); return surplusEthBuyAmount(surplusEth,step.add(1),surplusAmount); } } function crowdsaleStep() public view returns(uint256,uint256){ uint256 a = sellAmount.div(stepNum); uint256 b = sellAmount.mod(stepNum); return (a,b); } function surplusEthBuyAmount(uint256 surplusEth,uint256 step,uint256 count) public view returns(uint256){ for(uint256 i= 0; i< 30; i++){ uint256 spendEth = stepNum.div(getRatesPrice(step)); if(spendEth >= surplusEth) { return count.add(surplusEth.mul(getRatesPrice(step))); }else{ count = count.add(stepNum); step = step.add(1); surplusEth = surplusEth.sub(spendEth); } } } function getUserInfo(address userAddress) public view returns(address,address,uint256,uint256,uint256){ Invest storage user = investMapping[userAddress]; if(user.isVaild){ uint256 userInviteCount = userInvitees[userAddress].length; return (user.userAddress,user.inviteUser,userInviteCount,user.rewardBalance,user.buyTokenNum); }else{ return(address(0),address(0),0,0,0); } } function getAllUser(uint index) public view returns(address){ if(index < inverts.length){ return inverts[index].userAddress; }else{ return address(0); } } function getUserNumber()public view returns(uint256 length){ return inverts.length; } }
0x60806040526004361061021a5760003560e01c80638456cb5911610123578063c5f1dcb4116100ab578063f18d20be1161006f578063f18d20be14610b0b578063f40ffcfb14610b22578063f7fb07b014610b4d578063fc0c546a14610b78578063fed378f914610bcf5761021a565b8063c5f1dcb414610a07578063c6332e5614610a32578063c885bc5814610a5d578063d5a849e914610a74578063dc07001414610ad95761021a565b8063b1d8a2ab116100f2578063b1d8a2ab146108b1578063b2f2d7bd146108dc578063bf58390314610920578063bff99c6c1461094b578063c4ae93b0146109a25761021a565b80638456cb591461081957806397c79694146108305780639a83e2151461085b578063a371c720146108865761021a565b80634c6ed05d116101a65780635e914d3a116101755780635e914d3a1461065e5780636386c1c7146106ad5780636ef8d66d146107865780637759a11b1461079d57806382dc1ec4146107c85761021a565b80634c6ed05d14610572578063521eb2731461058957806355da6126146105e05780635c975abb1461062f5761021a565b80632c4e722e116101ed5780632c4e722e146104395780632e1d0a7b146104645780633f4ba83a146104c75780634042b66f146104de57806346fbf68e146105095761021a565b80630a81db941461022657806312273b9d146102ed57806318b38f001461039357806320c9ad2c1461040e575b6102246000610c38565b005b34801561023257600080fd5b5061025f6004803603602081101561024957600080fd5b8101908080359060200190929190505050611877565b604051808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001848152602001838152602001821515151581526020019550505050505060405180910390f35b3480156102f957600080fd5b5061033c6004803603602081101561031057600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611907565b6040518080602001828103825283818151815260200191508051906020019060200280838360005b8381101561037f578082015181840152602081019050610364565b505050509050019250505060405180910390f35b34801561039f57600080fd5b506103cc600480360360208110156103b657600080fd5b81019080803590602001909291905050506119d4565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561041a57600080fd5b50610423611a33565b6040518082815260200191505060405180910390f35b34801561044557600080fd5b5061044e611a40565b6040518082815260200191505060405180910390f35b34801561047057600080fd5b506104b16004803603606081101561048757600080fd5b81019080803590602001909291908035906020019092919080359060200190929190505050611a4a565b6040518082815260200191505060405180910390f35b3480156104d357600080fd5b506104dc611b12565b005b3480156104ea57600080fd5b506104f3611c80565b6040518082815260200191505060405180910390f35b34801561051557600080fd5b506105586004803603602081101561052c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611c8a565b604051808215151515815260200191505060405180910390f35b34801561057e57600080fd5b50610587611ca7565b005b34801561059557600080fd5b5061059e611e21565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b3480156105ec57600080fd5b506106196004803603602081101561060357600080fd5b8101908080359060200190929190505050611e4b565b6040518082815260200191505060405180910390f35b34801561063b57600080fd5b50610644611f5d565b604051808215151515815260200191505060405180910390f35b34801561066a57600080fd5b506106976004803603602081101561068157600080fd5b8101908080359060200190929190505050611f74565b6040518082815260200191505060405180910390f35b3480156106b957600080fd5b506106fc600480360360208110156106d057600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611fa0565b604051808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018481526020018381526020018281526020019550505050505060405180910390f35b34801561079257600080fd5b5061079b6120da565b005b3480156107a957600080fd5b506107b26120ec565b6040518082815260200191505060405180910390f35b3480156107d457600080fd5b50610817600480360360208110156107eb57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506120f2565b005b34801561082557600080fd5b5061082e612163565b005b34801561083c57600080fd5b506108456122d2565b6040518082815260200191505060405180910390f35b34801561086757600080fd5b506108706122d8565b6040518082815260200191505060405180910390f35b34801561089257600080fd5b5061089b6122de565b6040518082815260200191505060405180910390f35b3480156108bd57600080fd5b506108c66122e4565b6040518082815260200191505060405180910390f35b61091e600480360360208110156108f257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610c38565b005b34801561092c57600080fd5b506109356122ea565b6040518082815260200191505060405180910390f35b34801561095757600080fd5b506109606124ef565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b3480156109ae57600080fd5b506109f1600480360360208110156109c557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612519565b6040518082815260200191505060405180910390f35b348015610a1357600080fd5b50610a1c612531565b6040518082815260200191505060405180910390f35b348015610a3e57600080fd5b50610a4761253b565b6040518082815260200191505060405180910390f35b348015610a6957600080fd5b50610a72612543565b005b348015610a8057600080fd5b50610ac360048036036020811015610a9757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612764565b6040518082815260200191505060405180910390f35b348015610ae557600080fd5b50610aee612852565b604051808381526020018281526020019250505060405180910390f35b348015610b1757600080fd5b50610b20612897565b005b348015610b2e57600080fd5b50610b37612b9a565b6040518082815260200191505060405180910390f35b348015610b5957600080fd5b50610b62612be1565b6040518082815260200191505060405180910390f35b348015610b8457600080fd5b50610b8d612c26565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b348015610bdb57600080fd5b50610c1e60048036036020811015610bf257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612c4f565b604051808215151515815260200191505060405180910390f35b610c40612cbf565b73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161415610cc4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c815260200180613f3f602c913960400191505060405180910390fd5b6000349050600a54811015610d24576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526024815260200180613f1b6024913960400191505060405180910390fd5b600b54811115610d7f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526024815260200180613e176024913960400191505060405180910390fd5b60003390506000602d60008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002090506000610dd38385612cc7565b9050610dea81600d54612e5490919063ffffffff16565b600d819055508160040160009054906101000a900460ff166115b1576000849050600073ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff161461139f576000602d60008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002090508060040160009054906101000a900460ff1615610eaa57610ea38787612edc565b9150611135565b6000610ec160085488612f9990919063ffffffff16565b9050610ecb613d89565b6040518060a001604052808a73ffffffffffffffffffffffffffffffffffffffff168152602001600073ffffffffffffffffffffffffffffffffffffffff1681526020016000815260200183815260200160011515815250905080602d60008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008201518160000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060208201518160010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550604082015181600201556060820151816003015560808201518160040160006101000a81548160ff021916908315150217905550905050602f819080600181540180825580915050906001820390600052602060002090600502016000909192909190915060008201518160000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060208201518160010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550604082015181600201556060820151816003015560808201518160040160006101000a81548160ff0219169083151502179055505050506111308289612fe390919063ffffffff16565b935050505b61113d613d89565b6040518060a001604052808773ffffffffffffffffffffffffffffffffffffffff1681526020018973ffffffffffffffffffffffffffffffffffffffff1681526020018581526020016000815260200160011515815250905080602d60008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008201518160000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060208201518160010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550604082015181600201556060820151816003015560808201518160040160006101000a81548160ff021916908315150217905550905050602f819080600181540180825580915050906001820390600052602060002090600502016000909192909190915060008201518160000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060208201518160010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550604082015181600201556060820151816003015560808201518160040160006101000a81548160ff021916908315150217905550505050611398888761302d565b5050611508565b6113a7613d89565b6040518060a001604052808673ffffffffffffffffffffffffffffffffffffffff168152602001600073ffffffffffffffffffffffffffffffffffffffff1681526020018481526020016000815260200160011515815250905080602d60008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008201518160000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060208201518160010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550604082015181600201556060820151816003015560808201518160040160006101000a81548160ff021916908315150217905550905050505b6115618160076000611518611e21565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054612e5490919063ffffffff16565b6007600061156d611e21565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555050611870565b6115c8818360020154612e5490919063ffffffff16565b82600201819055506000849050600073ffffffffffffffffffffffffffffffffffffffff168360010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16141580156116635750600073ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff1614155b15611707578573ffffffffffffffffffffffffffffffffffffffff168360010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614156116d1576116ca8686612edc565b9050611702565b6116ff8360010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1686612edc565b90505b6117cb565b600073ffffffffffffffffffffffffffffffffffffffff168360010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16141580156117945750600073ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff16145b156117ca576117c78360010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1686612edc565b90505b5b61182481600760006117db611e21565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054612e5490919063ffffffff16565b60076000611830611e21565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550505b5050505050565b602f818154811061188457fe5b90600052602060002090600502016000915090508060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16908060010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16908060020154908060030154908060040160009054906101000a900460ff16905085565b6060602e60008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208054806020026020016040519081016040528092919081815260200182805480156119c857602002820191906000526020600020905b8160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001906001019080831161197e575b50505050509050919050565b6000602f80549050821015611a2957602f82815481106119f057fe5b906000526020600020906005020160000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff169050611a2e565b600090505b919050565b6000602f80549050905090565b6000600254905090565b600080600090505b601e811015611b09576000611a7a611a6986611f74565b600c54612f9990919063ffffffff16565b9050858110611ab957611ab0611aa1611a9287611f74565b8861317d90919063ffffffff16565b85612e5490919063ffffffff16565b92505050611b0b565b611ace600c5485612e5490919063ffffffff16565b9350611ae4600186612e5490919063ffffffff16565b9450611af98187612fe390919063ffffffff16565b9550508080600101915050611a52565b505b9392505050565b611b22611b1d612cbf565b611c8a565b611b77576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526030815260200180613de76030913960400191505060405180910390fd5b600660009054906101000a900460ff16611bf9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260148152602001807f5061757361626c653a206e6f742070617573656400000000000000000000000081525060200191505060405180910390fd5b6000600660006101000a81548160ff0219169083151502179055507f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa611c3d612cbf565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a1565b6000600354905090565b6000611ca082600561320390919063ffffffff16565b9050919050565b611caf611e21565b73ffffffffffffffffffffffffffffffffffffffff16611ccd612cbf565b73ffffffffffffffffffffffffffffffffffffffff1614611d56576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601c8152602001807f70726573616c653a2063616c6c6572206973206e6f742061646d696e0000000081525060200191505060405180910390fd5b600660009054906101000a900460ff16611dd8576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260148152602001807f5061757361626c653a206e6f742070617573656400000000000000000000000081525060200191505060405180910390fd5b3373ffffffffffffffffffffffffffffffffffffffff166108fc479081150290604051600060405180830381858888f19350505050158015611e1e573d6000803e3d6000fd5b50565b6000600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b600080611e65600c54600d54612f9990919063ffffffff16565b90506000611e91600c54611e83600185612e5490919063ffffffff16565b61317d90919063ffffffff16565b90506000611e9e83611f74565b9050611eb3818661317d90919063ffffffff16565b611ec8600d5484612fe390919063ffffffff16565b10611eea57611ee0818661317d90919063ffffffff16565b9350505050611f58565b6000611f01600d5484612fe390919063ffffffff16565b90506000611f188383612f9990919063ffffffff16565b90506000611f2f8289612fe390919063ffffffff16565b9050611f4f81611f49600189612e5490919063ffffffff16565b85611a4a565b96505050505050505b919050565b6000600660009054906101000a900460ff16905090565b6000601e821115611f8457601e91505b6000600e83601e8110611f9357fe5b0154905080915050919050565b600080600080600080602d60008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002090508060040160009054906101000a900460ff16156120ae576000602e60008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208054905090508160000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff168260010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1682846003015485600201549650965096509650965050506120d1565b600080600080600084945083935082925081915080905095509550955095509550505b91939590929450565b6120ea6120e5612cbf565b6132e1565b565b600a5481565b6121026120fd612cbf565b611c8a565b612157576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526030815260200180613de76030913960400191505060405180910390fd5b6121608161333b565b50565b61217361216e612cbf565b611c8a565b6121c8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526030815260200180613de76030913960400191505060405180910390fd5b600660009054906101000a900460ff161561224b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260108152602001807f5061757361626c653a207061757365640000000000000000000000000000000081525060200191505060405180910390fd5b6001600660006101000a81548160ff0219169083151502179055507f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861228f612cbf565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a1565b600b5481565b60085481565b60095481565b600c5481565b60006124ea6122f7612c26565b73ffffffffffffffffffffffffffffffffffffffff166370a08231600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561239557600080fd5b505afa1580156123a9573d6000803e3d6000fd5b505050506040513d60208110156123bf57600080fd5b81019080805190602001909291905050506123d8612c26565b73ffffffffffffffffffffffffffffffffffffffff1663dd62ed3e600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16306040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060206040518083038186803b1580156124aa57600080fd5b505afa1580156124be573d6000803e3d6000fd5b505050506040513d60208110156124d457600080fd5b8101908080519060200190929190505050613395565b905090565b6000600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b60076020528060005260406000206000915090505481565b6000600d54905090565b600047905090565b600660009054906101000a900460ff16156125c6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260108152602001807f5061757361626c653a207061757365640000000000000000000000000000000081525060200191505060405180910390fd5b600033905060006125d682612764565b116125dd57fe5b60006125e882612764565b905080471015612660576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601e8152602001807f70726573616c653a207769746864726177526577617264206e6f20657468000081525060200191505060405180910390fd5b6000602d60008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000209050600081600301819055508273ffffffffffffffffffffffffffffffffffffffff166108fc839081150290604051600060405180830381858888f193505050501580156126f3573d6000803e3d6000fd5b507fc8ee6fa59201819bd59c06a0b0cfab85325217fe1f94c6638a8312784e45e6183383604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a1505050565b60008073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614156127eb576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526028815260200180613e9f6028913960400191505060405180910390fd5b6127f482612c4f565b612801576000905061284d565b6000602d60008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020905080600301549150505b919050565b600080600061286e600c54600d54612f9990919063ffffffff16565b90506000612889600c54600d546133ae90919063ffffffff16565b905081819350935050509091565b61289f611e21565b73ffffffffffffffffffffffffffffffffffffffff166128bd612cbf565b73ffffffffffffffffffffffffffffffffffffffff1614612946576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601c8152602001807f70726573616c653a2063616c6c6572206973206e6f742061646d696e0000000081525060200191505060405180910390fd5b60003390506000600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905080471015612a05576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f70726573616c653a2061646d696e5769746864726177206e6f2065746800000081525060200191505060405180910390fd5b6000600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506000612a60601483612f9990919063ffffffff16565b90506000612a778284612fe390919063ffffffff16565b9050602c60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc839081150290604051600060405180830381858888f19350505050158015612ae1573d6000803e3d6000fd5b508373ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f19350505050158015612b28573d6000803e3d6000fd5b507fc8ee6fa59201819bd59c06a0b0cfab85325217fe1f94c6638a8312784e45e6183384604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a150505050565b6000600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905090565b600080612bfb600c54600d54612f9990919063ffffffff16565b9050601e811115612c0b57601e90505b6000600e82601e8110612c1a57fe5b01549050809250505090565b60008060019054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b600080602d60008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002090508060040160009054906101000a900460ff1615612cb4576001915050612cba565b60009150505b919050565b600033905090565b60008060009054906101000a900460ff16612d4a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0081525060200191505060405180910390fd5b60008060006101000a81548160ff021916908315150217905550612d6e83836133f8565b6000612d7983613489565b9050612d9083600354612e5490919063ffffffff16565b600381905550612da0848261349b565b8373ffffffffffffffffffffffffffffffffffffffff16612dbf612cbf565b73ffffffffffffffffffffffffffffffffffffffff167f6faf93231a456e552dbc9961f58d9713ee4f2e69d15f1975b050ef0911053a7b8584604051808381526020018281526020019250505060405180910390a3612e1e84846134a9565b612e266134ad565b612e3084846134af565b8091505060016000806101000a81548160ff02191690831515021790555092915050565b600080828401905083811015612ed2576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b600080602d60008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002090508060040160009054906101000a900460ff1615612f91576000612f4e60085485612f9990919063ffffffff16565b9050612f67818360030154612e5490919063ffffffff16565b82600301819055506000612f848286612fe390919063ffffffff16565b9050809350505050612f93565b505b92915050565b6000612fdb83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f0000000000008152506134b3565b905092915050565b600061302583836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250613579565b905092915050565b6000602e60008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000209050600080905060008090505b8280549050811015613107578373ffffffffffffffffffffffffffffffffffffffff168382815481106130aa57fe5b9060005260206000200160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614156130fa5781806001019250505b808060010191505061307b565b50600081141561317757818390806001815401808255809150509060018203906000526020600020016000909192909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550505b50505050565b60008083141561319057600090506131fd565b60008284029050828482816131a157fe5b04146131f8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180613e5c6021913960400191505060405180910390fd5b809150505b92915050565b60008073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16141561328a576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180613e7d6022913960400191505060405180910390fd5b8260000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16905092915050565b6132f581600561363990919063ffffffff16565b8073ffffffffffffffffffffffffffffffffffffffff167fcd265ebaf09df2871cc7bd4133404a235ba12eff2041bb89d9c714a2621c7c7e60405160405180910390a250565b61334f8160056136f690919063ffffffff16565b8073ffffffffffffffffffffffffffffffffffffffff167f6719d08c1888103bea251a4ed56406bd0c3e69723c8a1686e017e7bbe159b6f860405160405180910390a250565b60008183106133a457816133a6565b825b905092915050565b60006133f083836040518060400160405280601881526020017f536166654d6174683a206d6f64756c6f206279207a65726f00000000000000008152506137d1565b905092915050565b600660009054906101000a900460ff161561347b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260108152602001807f5061757361626c653a207061757365640000000000000000000000000000000081525060200191505060405180910390fd5b6134858282613892565b5050565b600061349482611e4b565b9050919050565b6134a58282613993565b5050565b5050565b565b5050565b6000808311829061355f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015613524578082015181840152602081019050613509565b50505050905090810190601f1680156135515780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b50600083858161356b57fe5b049050809150509392505050565b6000838311158290613626576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b838110156135eb5780820151818401526020810190506135d0565b50505050905090810190601f1680156136185780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b6136438282613203565b613698576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180613e3b6021913960400191505060405180910390fd5b60008260000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055505050565b6137008282613203565b15613773576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f526f6c65733a206163636f756e7420616c72656164792068617320726f6c650081525060200191505060405180910390fd5b60018260000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055505050565b600080831415829061387e576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015613843578082015181840152602081019050613828565b50505050905090810190601f1680156138705780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5082848161388857fe5b0690509392505050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415613918576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602a815260200180613ec7602a913960400191505060405180910390fd5b600081141561398f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260198152602001807f43726f776473616c653a20776569416d6f756e7420697320300000000000000081525060200191505060405180910390fd5b5050565b6139e9600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1683836139c3612c26565b73ffffffffffffffffffffffffffffffffffffffff166139ed909392919063ffffffff16565b5050565b613aed848573ffffffffffffffffffffffffffffffffffffffff166323b872dd905060e01b858585604051602401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019350505050604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050613af3565b50505050565b613b128273ffffffffffffffffffffffffffffffffffffffff16613d3e565b613b84576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f5361666545524332303a2063616c6c20746f206e6f6e2d636f6e74726163740081525060200191505060405180910390fd5b600060608373ffffffffffffffffffffffffffffffffffffffff16836040518082805190602001908083835b60208310613bd35780518252602082019150602081019050602083039250613bb0565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613c35576040519150601f19603f3d011682016040523d82523d6000602084013e613c3a565b606091505b509150915081613cb2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c656481525060200191505060405180910390fd5b600081511115613d3857808060200190516020811015613cd157600080fd5b8101908080519060200190929190505050613d37576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602a815260200180613ef1602a913960400191505060405180910390fd5b5b50505050565b60008060007fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47060001b9050833f9150808214158015613d8057506000801b8214155b92505050919050565b6040518060a00160405280600073ffffffffffffffffffffffffffffffffffffffff168152602001600073ffffffffffffffffffffffffffffffffffffffff1681526020016000815260200160008152602001600015158152509056fe506175736572526f6c653a2063616c6c657220646f6573206e6f742068617665207468652050617573657220726f6c6570726573616c653a206d617856657374416d6f756e742069732035303020657468657220526f6c65733a206163636f756e7420646f6573206e6f74206861766520726f6c65536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77526f6c65733a206163636f756e7420697320746865207a65726f206164647265737370726573616c653a20757365724164647265737320697320746865207a65726f206164647265737343726f776473616c653a2062656e656669636961727920697320746865207a65726f20616464726573735361666545524332303a204552433230206f7065726174696f6e20646964206e6f74207375636365656470726573616c653a206d696e56657374416d6f756e742069732031302066696e6e65792070726573616c653a20696e7669746541646472657373206e6f7420657175616c73206d736753656e64657220a265627a7a72315820bce6aa29c1f1ef8402e6d17d129d8861f3a19dc6d08d9b2264888bb476af881d64736f6c63430005100032
{"success": true, "error": null, "results": {"detectors": [{"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}]}
31
0x0cde9622b23ababfccef9755b5f7c9e759ef4820
pragma solidity 0.6.10; pragma experimental ABIEncoderV2; contract CrowdProposal { /// @notice The crowd proposal author address payable public immutable author; /// @notice Governance proposal data address[] public targets; uint[] public values; string[] public signatures; bytes[] public calldatas; string public description; /// @notice COMP token contract address address public immutable comp; /// @notice Compound protocol `GovernorAlpha` contract address address public immutable governor; /// @notice Governance proposal id uint public govProposalId; /// @notice Terminate flag bool public terminated; /// @notice An event emitted when the governance proposal is created event CrowdProposalProposed(address indexed proposal, address indexed author, uint proposalId); /// @notice An event emitted when the crowd proposal is terminated event CrowdProposalTerminated(address indexed proposal, address indexed author); /// @notice An event emitted when delegated votes are transfered to the governance proposal event CrowdProposalVoted(address indexed proposal, uint proposalId); /** * @notice Construct crowd proposal * @param author_ The crowd proposal author * @param targets_ The ordered list of target addresses for calls to be made * @param values_ The ordered list of values (i.e. msg.value) to be passed to the calls to be made * @param signatures_ The ordered list of function signatures to be called * @param calldatas_ The ordered list of calldata to be passed to each call * @param description_ The block at which voting begins: holders must delegate their votes prior to this block * @param comp_ `COMP` token contract address * @param governor_ Compound protocol `GovernorAlpha` contract address */ constructor(address payable author_, address[] memory targets_, uint[] memory values_, string[] memory signatures_, bytes[] memory calldatas_, string memory description_, address comp_, address governor_) public { author = author_; // Save proposal data targets = targets_; values = values_; signatures = signatures_; calldatas = calldatas_; description = description_; // Save Compound contracts data comp = comp_; governor = governor_; terminated = false; // Delegate votes to the crowd proposal IComp(comp_).delegate(address(this)); } /// @notice Create governance proposal function propose() external returns (uint) { require(govProposalId == 0, 'CrowdProposal::propose: gov proposal already exists'); require(!terminated, 'CrowdProposal::propose: proposal has been terminated'); // Create governance proposal and save proposal id govProposalId = IGovernorAlpha(governor).propose(targets, values, signatures, calldatas, description); emit CrowdProposalProposed(address(this), author, govProposalId); return govProposalId; } /// @notice Terminate the crowd proposal, send back staked COMP tokens function terminate() external { require(msg.sender == author, 'CrowdProposal::terminate: only author can terminate'); require(!terminated, 'CrowdProposal::terminate: proposal has been already terminated'); terminated = true; // Transfer staked COMP tokens from the crowd proposal contract back to the author IComp(comp).transfer(author, IComp(comp).balanceOf(address(this))); emit CrowdProposalTerminated(address(this), author); } /// @notice Vote for the governance proposal with all delegated votes function vote() external { require(govProposalId > 0, 'CrowdProposal::vote: gov proposal has not been created yet'); IGovernorAlpha(governor).castVote(govProposalId, true); emit CrowdProposalVoted(address(this), govProposalId); } } interface IComp { function delegate(address delegatee) external; function balanceOf(address account) external view returns (uint); function transfer(address dst, uint rawAmount) external returns (bool); function transferFrom(address src, address dst, uint rawAmount) external returns (bool); } interface IGovernorAlpha { function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) external returns (uint); function castVote(uint proposalId, bool support) external; }
0x608060405234801561001057600080fd5b50600436106100cf5760003560e01c80635e383d211161008c5780638be10194116100665780638be1019414610171578063a6c3e6b914610184578063be73f9ab1461018c578063c198f8ba1461019f576100cf565b80635e383d2114610141578063632a9a52146101545780637284e4161461015c576100cf565b80630a39ce02146100d45780630c08bf88146100fd5780630c340a2414610107578063109d0af81461010f578063194307bf146101175780632b9bdc9e1461012c575b600080fd5b6100e76100e23660046107f5565b6101a7565b6040516100f491906109ea565b60405180910390f35b6101056101ce565b005b6100e76103dd565b6100e7610401565b61011f610425565b6040516100f49190610ac3565b61013461042e565b6040516100f49190610c95565b61013461014f3660046107f5565b610434565b610105610452565b61016461053c565b6040516100f49190610ace565b61016461017f3660046107f5565b6105ca565b6100e761063d565b61016461019a3660046107f5565b610661565b61013461066e565b600081815481106101b457fe5b6000918252602090912001546001600160a01b0316905081565b336001600160a01b037f000000000000000000000000b0325dbe7fa891436e83a094f9f12848c78e449b161461021f5760405162461bcd60e51b815260040161021690610b91565b60405180910390fd5b60065460ff16156102425760405162461bcd60e51b815260040161021690610b34565b6006805460ff191660011790556040516370a0823160e01b81526001600160a01b037f000000000000000000000000c00e94cb662c3520282e6f5717214004a7f26888169063a9059cbb907f000000000000000000000000b0325dbe7fa891436e83a094f9f12848c78e449b9083906370a08231906102c59030906004016109ea565b60206040518083038186803b1580156102dd57600080fd5b505afa1580156102f1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610315919061080d565b6040518363ffffffff1660e01b81526004016103329291906109fe565b602060405180830381600087803b15801561034c57600080fd5b505af1158015610360573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061038491906107ce565b506040516001600160a01b037f000000000000000000000000b0325dbe7fa891436e83a094f9f12848c78e449b169030907f23f673aea90166e3e0364748cd5f153da65814d4d343e1c3e2f43d33c0c3b3f190600090a3565b7f000000000000000000000000c0da01a04c3f3e0be433606045bb7017a7323e3881565b7f000000000000000000000000c00e94cb662c3520282e6f5717214004a7f2688881565b60065460ff1681565b60055481565b6001818154811061044157fe5b600091825260209091200154905081565b6000600554116104745760405162461bcd60e51b815260040161021690610be4565b6005546040516315373e3d60e01b81526001600160a01b037f000000000000000000000000c0da01a04c3f3e0be433606045bb7017a7323e3816916315373e3d916104c59190600190600401610c9e565b600060405180830381600087803b1580156104df57600080fd5b505af11580156104f3573d6000803e3d6000fd5b50505050306001600160a01b03167f402864f08818e224f9c5d5be7205cbe636a6239f96cc187e1445a414aa48c3f36005546040516105329190610c95565b60405180910390a2565b6004805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156105c25780601f10610597576101008083540402835291602001916105c2565b820191906000526020600020905b8154815290600101906020018083116105a557829003601f168201915b505050505081565b600281815481106105d757fe5b600091825260209182902001805460408051601f60026000196101006001871615020190941693909304928301859004850281018501909152818152935090918301828280156105c25780601f10610597576101008083540402835291602001916105c2565b7f000000000000000000000000b0325dbe7fa891436e83a094f9f12848c78e449b81565b600381815481106105d757fe5b60006005546000146106925760405162461bcd60e51b815260040161021690610ae1565b60065460ff16156106b55760405162461bcd60e51b815260040161021690610c41565b604051636d4ab48d60e11b81526001600160a01b037f000000000000000000000000c0da01a04c3f3e0be433606045bb7017a7323e38169063da95691a9061070d906000906001906002906003906004908101610a17565b602060405180830381600087803b15801561072757600080fd5b505af115801561073b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061075f919061080d565b60058190556040516001600160a01b037f000000000000000000000000b0325dbe7fa891436e83a094f9f12848c78e449b169130917fdd852111d50cb1db94e7f2c0d71c2e82ec0638c8ed1a57a94b2241294261bf1d916107bf91610c95565b60405180910390a35060055490565b6000602082840312156107df578081fd5b815180151581146107ee578182fd5b9392505050565b600060208284031215610806578081fd5b5035919050565b60006020828403121561081e578081fd5b5051919050565b6001600160a01b03169052565b6000815480845260208085018081965082840281019150858552828520855b8581101561087a5782840389526108688483610967565b98850198935060019182019101610851565b5091979650505050505050565b60008282548085526020808601955080818302840101858552818520855b848110156108d257858303601f190189526108c08383610967565b988401989250600191820191016108a5565b5090979650505050505050565b6000815480845260208085019450838352808320835b83811015610911578154875295820195600191820191016108f5565b509495945050505050565b60008151808452815b8181101561094157602081850181015186830182015201610925565b818111156109525782602083870101525b50601f01601f19169290920160200192915050565b6000815460018082166000811461098557600181146109a3576109e1565b60028304607f16865260ff19831660208701526040860193506109e1565b600283048087526109b386610cae565b60005b828110156109d75781546020828b01015284820191506020810190506109b6565b8801602001955050505b50505092915050565b6001600160a01b0391909116815260200190565b6001600160a01b03929092168252602082015260400190565b600060a0820160a0835280885480835260c08501915089845260209250828420845b82811015610a67578154610a579085906001600160a01b0316610825565b9284019260019182019101610a39565b50505083810382850152610a7b81896108df565b9150508281036040840152610a908187610887565b8381036060850152610aa28187610832565b9150508281036080840152610ab78185610967565b98975050505050505050565b901515815260200190565b6000602082526107ee602083018461091c565b60208082526033908201527f43726f776450726f706f73616c3a3a70726f706f73653a20676f762070726f706040820152726f73616c20616c72656164792065786973747360681b606082015260800190565b6020808252603e908201527f43726f776450726f706f73616c3a3a7465726d696e6174653a2070726f706f7360408201527f616c20686173206265656e20616c7265616479207465726d696e617465640000606082015260800190565b60208082526033908201527f43726f776450726f706f73616c3a3a7465726d696e6174653a206f6e6c7920616040820152727574686f722063616e207465726d696e61746560681b606082015260800190565b6020808252603a908201527f43726f776450726f706f73616c3a3a766f74653a20676f762070726f706f736160408201527f6c20686173206e6f74206265656e206372656174656420796574000000000000606082015260800190565b60208082526034908201527f43726f776450726f706f73616c3a3a70726f706f73653a2070726f706f73616c604082015273081a185cc81899595b881d195c9b5a5b985d195960621b606082015260800190565b90815260200190565b9182521515602082015260400190565b6000908152602090209056fea26469706673582212204949303609d8028a829949122056b9a200c4932c29d75e33f1267b68d083369364736f6c634300060a0033
{"success": true, "error": null, "results": {"detectors": [{"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}]}
32
0x0cfb151de2c34aceb532f43683e5b7bed62f298f
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); } } ublic 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 payable supplier; address payable 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 payable 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 payable 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 = false; bool pooltask = false; uint pid; if(orderStatus[_orderId] == Status.OPENCREATOR) { pid = (openOrderMap[_orderId].duration/6) - 1; } else if(orderStatus[_orderId] == Status.OPENBORROW) { pid = (openOrderMap[_orderId].duration/6) + 5; } poolindex[_tokenSymbol][pid]=0; if(orderpool[_tokenSymbol].length==0 && _status) { orderpool[_tokenSymbol][0] = _orderId; } else { 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(uint(openOrderMap[temp[j]].duration/6) == uint(openOrderMap[_orderId].duration/6) && orderStatus[orderpool[_tokenSymbol][i]]==Status.OPENBORROW) { //Assigns updatePoolIndex with Highest Value of Borrow poolindex[_tokenSymbol][pid] = i; pooltask = true; } else if(uint(openOrderMap[temp[j]].duration/6) == uint(openOrderMap[_orderId].duration/6) && orderStatus[orderpool[_tokenSymbol][i]]==Status.OPENCREATOR && !pooltask) { poolindex[_tokenSymbol][pid] = i; pooltask = true; } } orderpool[_tokenSymbol] = temp; } } function matchOrder(address payable userAddress, string memory _tokenSymbol ,uint _amount,uint _duration,uint _yield, uint64 _orderId) 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 }); for((uint i,uint j)=(0,0); i<users[matchOrderMap[_orderId].supplier].createdOrders.length; (i++,j++)) { if(users[matchOrderMap[_orderId].supplier].createdOrders[i] == _orderId) { --j; continue; } users[matchOrderMap[_orderId].supplier].createdOrders[j] = users[matchOrderMap[_orderId].supplier].createdOrders[i]; } for((uint i,uint j)=(0,0); i<users[matchOrderMap[_orderId].borrower].borrowedOrders.length; (i++,j++)) { if(users[matchOrderMap[_orderId].borrower].borrowedOrders[i] == _orderId) { continue; } users[matchOrderMap[_orderId].borrower].borrowedOrders[j] = users[matchOrderMap[_orderId].borrower].borrowedOrders[i]; } delete openOrderMap[_orderId]; poolSorter(_orderId, _tokenSymbol, false); 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.WithdrawManager(EMM.wtormap(_tokenSymbol), _amount, matchOrderMap[_orderId].borrower); Init.emitOrderCreated(userAddress,_duration,_yield,_amount,_tokenSymbol); } function newOrder(address payable 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][(_duration/6)-1]; users[userAddress].deposits[_tokenSymbol] +=_amount; users[userAddress].totalDeposit += USDValue(_amount, _tokenSymbol); } else { index = poolindex[_tokenSymbol][(_duration/6)+5]; users[userAddress].borrows[_tokenSymbol] +=_amount; users[userAddress].totalBorrowed += USDValue(_amount, _tokenSymbol); } while(amountLeft>0){ if(index == 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 if(orderStatus[orderpool[_tokenSymbol][index]]== (_status ? Status.OPENBORROW : Status.OPENCREATOR)) { 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); amountLeft=0; } else { pushOrder(userAddress, _tokenSymbol, amountLeft- iOrder.amount, _duration, _yield, _status); matchOrder(userAddress, _tokenSymbol, amountLeft, tduration, tyield, tID); 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); EMM.burnWrappedFrom(matchOrderMap[_orderId].supplier,matchOrderMap[_orderId].amount, matchOrderMap[_orderId].wtoken); EMM.WithdrawManager(EMM.wtormap(matchOrderMap[_orderId].wtoken), matchOrderMap[_orderId].amount, matchOrderMap[_orderId].supplier); 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); EMM.lockECO(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); EMM.burnWrappedFrom(openOrderMap[_orderId].creator,openOrderMap[_orderId].amount, openOrderMap[_orderId].wtoken); EMM.WithdrawManager(EMM.wtormap(openOrderMap[_orderId].wtoken),openOrderMap[_orderId].amount, openOrderMap[_orderId].creator); 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]; if(orderUSDValue[_orderId] > 0) { 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); } if(ecobalance > EMM.ecoWithdrawls(userAddress)) { return ecobalance - EMM.ecoWithdrawls(userAddress); } else { return uint(0); } } 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 buyPower){ if(Init.isRegistrar(userAddress)) { return (10**30); } if(Init.isUserLocked(userAddress)) { return 0; } if(users[userAddress].totalBorrowed > 0) { return users[userAddress].totalDeposit - ((users[userAddress].totalDeposit*Init.CDSpercent())/100) - users[userAddress].totalBorrowed; } else { return users[userAddress].totalDeposit; } } function getOrderIds(string memory wtoken) public view returns (uint64 [] memory orderIds) { return orderpool[wtoken]; } function updatePoolIndex(uint index, string memory wtoken, uint value) external { if(Init.friendlyaddress(msg.sender) == true) { poolindex[wtoken][index]= value; } } /*function deleteUserData(address userAddress) external { if(Init.friendlyaddress(msg.sender)==true) { delete users[userAddress]; } }*/ } 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 payable 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 payable userAddress,string memory _tokenSymbol ,uint _amount,uint _duration,uint _yield) external payable { require(msg.sender == userAddress); require(_duration>=6, "Duration should be atleast 6 Months"); 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.WithdrawManager(Init.ECO(), ecoEarnings, userAddress); } 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(uint _amount, string memory _tokenSymbol) public { require(isWithdrawEligible(msg.sender, _tokenSymbol, _amount)); EDM.freePusher(msg.sender, EMM.getWrapped(_tokenSymbol), _amount,false); EMM.WithdrawManager(_tokenSymbol, _amount, msg.sender); } function SwapWrapToWrap(string memory token1,string memory token2, uint token1amount) external returns(uint) { address payable 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); if(ecoEarnings>0) { if(ecoEarnings > EMM.ecoWithdrawls(msgSender)) { ecoEarnings-=EMM.ecoWithdrawls(msgSender); if(EMM.ecoWithdrawls(msgSender) > 0) { EMM.adjustEcoEarning(msgSender, EMM.ecoWithdrawls(msgSender)); } EMM.WithdrawManager(Init.ECO(), ecoEarnings, msgSender); } else { EMM.adjustEcoEarning(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"); } if(keccak256(abi.encodePacked(to)) == keccak256(abi.encodePacked(Init.ECO()))) { require( getAggEcoBalance(msgSender) >= _amount,"Insufficient Balance"); if(EDM.getUserDepositsbyToken(msgSender, from) >=_amount) { _withdraw(msgSender, from, _amount, to); } else { uint amountLeft = _amount - EDM.getUserDepositsbyToken(msgSender, from); if(EDM.getUserDepositsbyToken(msgSender, from) > 0){ _withdraw(msgSender, from, _amount, to); } EMM.redeemEcoEarning(msgSender,amountLeft); } } else { require(EDM.getUserDepositsbyToken(msgSender, from)>=_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.WithdrawManager(Init.ECO(), ecoEarnings, msgSender); } 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) public view returns (bool Eligible){ return (EDM.getbuyPower(userAddress) > EDM.USDValue(amount,EMM.getWrapped(to))); } } 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) public wtormap; mapping (string => string) public 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 updatertoken (string memory WToken, string memory RToken) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); wtormap[WToken] = RToken; } 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.transfer(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; } function updateWrapAddress (string memory wtoken, address wAddress) external { require(owner == msg.sender); wTokens[wtoken].tokenAddress = wAddress; } function updatewtoken (string memory RToken, string memory WToken) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); rTokensTowToken[RToken] = WToken; } }
0x608060405260043610620002475760003560e01c80638c3688181162000133578063ccbfde3211620000af578063e0e872bc1162000079578063e0e872bc14620006fb578063e1d6e3e91462000720578063e706a6391462000745578063ee8c24b8146200076a578063f13690471462000791576200024f565b8063ccbfde321462000667578063d1b5c12c146200068c578063d1f94af414620006b1578063d5e004ee14620006d6576200024f565b8063b210085b11620000fd578063b210085b14620005ae578063bfbae3e714620005d3578063c65c440814620005f8578063c813b1b8146200061d578063c83aad761462000642576200024f565b80638c36881814620005275780638da5cb5b146200054c57806395a1e9621462000564578063a6f9dae11462000589576200024f565b80634546162811620001c35780635408b02f116200018d5780635408b02f146200046e5780635b0a3af714620004935780636517b48314620004b85780636e6164d714620004dd57806385e2381c1462000502576200024f565b80634546162814620003d9578063481343e314620003fe578063483eb4ed1462000432578063485cc9551462000449576200024f565b80631fbfe54e11620002115780631fbfe54e146200031157806320eb66ff14620003365780632a23dccf146200035b578063376c045414620003805780633ce9babf14620003a5576200024f565b806302167e8a1462000254578063036c9641146200027b578063077fec3e14620002a057806315cca55414620002dd576200024f565b366200024f57005b600080fd5b3480156200026157600080fd5b50620002796200027336600462002908565b620007b6565b005b3480156200028857600080fd5b50620002796200029a366004620028f5565b620008d7565b348015620002ad57600080fd5b50620002c5620002bf36600462002c37565b62000a6d565b604051620002d4919062002cd4565b60405180910390f35b348015620002ea57600080fd5b5062000302620002fc36600462002986565b62000a95565b604051620002d4919062002ddd565b3480156200031e57600080fd5b50620002796200033036600462002bed565b62000b49565b3480156200034357600080fd5b50620002c56200035536600462002c37565b62000bb1565b3480156200036857600080fd5b50620002796200037a366004620027d5565b62000bbf565b3480156200038d57600080fd5b50620002796200039f366004620028f5565b62000d88565b348015620003b257600080fd5b50620003ca620003c436600462002986565b62000ea7565b604051620002d4919062002f3f565b348015620003e657600080fd5b5062000279620003f8366004620027fb565b62000fcc565b3480156200040b57600080fd5b50620004236200041d366004620027d5565b62001119565b604051620002d4919062002f36565b620002796200044336600462002b8f565b6200112b565b3480156200045657600080fd5b50620002796200046836600462002829565b620014a7565b3480156200047b57600080fd5b50620002796200048d36600462002908565b62001564565b348015620004a057600080fd5b5062000302620004b236600462002986565b62001643565b348015620004c557600080fd5b5062000423620004d736600462002986565b620016ee565b348015620004ea57600080fd5b50620002c5620004fc36600462002986565b6200170b565b3480156200050f57600080fd5b506200027962000521366004620027d5565b6200173f565b3480156200053457600080fd5b506200027962000546366004620028f5565b620017ef565b3480156200055957600080fd5b50620002c56200190e565b3480156200057157600080fd5b506200027962000583366004620028f5565b6200191d565b3480156200059657600080fd5b5062000279620005a8366004620027d5565b620019e5565b348015620005bb57600080fd5b5062000279620005cd36600462002a89565b62001a1f565b348015620005e057600080fd5b50620002c5620005f236600462002af0565b62001afa565b3480156200060557600080fd5b50620002796200061736600462002908565b62001d79565b3480156200062a57600080fd5b50620002796200063c36600462002908565b62001e58565b3480156200064f57600080fd5b50620004236200066136600462002986565b62001f37565b3480156200067457600080fd5b50620003026200068636600462002986565b62001f54565b3480156200069957600080fd5b5062000279620006ab366004620028f5565b62001fcb565b348015620006be57600080fd5b5062000279620006d036600462002b8f565b620020ea565b348015620006e357600080fd5b5062000279620006f536600462002a3f565b62002399565b3480156200070857600080fd5b50620002c56200071a36600462002986565b620023f7565b3480156200072d57600080fd5b50620002796200073f36600462002866565b6200240b565b3480156200075257600080fd5b50620004236200076436600462002986565b62002531565b3480156200077757600080fd5b5062000782620025b0565b604051620002d4919062002d8e565b3480156200079e57600080fd5b5062000279620007b036600462002a89565b62002614565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef90620007e890339060040162002cd4565b60206040518083038186803b1580156200080157600080fd5b505afa15801562000816573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200083c919062002964565b620008645760405162461bcd60e51b81526004016200085b9062002f08565b60405180910390fd5b6200086f81620023f7565b6001600160a01b03166340c10f1984846040518363ffffffff1660e01b81526004016200089e92919062002ce8565b600060405180830381600087803b158015620008b957600080fd5b505af1158015620008ce573d6000803e3d6000fd5b50505050505050565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef906200090990339060040162002cd4565b60206040518083038186803b1580156200092257600080fd5b505afa15801562000937573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200095d919062002964565b6200097c5760405162461bcd60e51b81526004016200085b9062002f08565b6033546040805160016238880b60e11b03198152905162000a06926001600160a01b03169163ff8eefea916004808301926000929190829003018186803b158015620009c757600080fd5b505afa158015620009dc573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526200071a9190810190620029c4565b6001600160a01b031663282d3fdf83836040518363ffffffff1660e01b815260040162000a3592919062002ce8565b600060405180830381600087803b15801562000a5057600080fd5b505af115801562000a65573d6000803e3d6000fd5b505050505050565b6036818154811062000a7b57fe5b6000918252602090912001546001600160a01b0316905081565b606060398260405162000aa9919062002cb6565b9081526040805160209281900383018120805460026001821615610100026000190190911604601f8101859004850283018501909352828252909290919083018282801562000b3c5780601f1062000b105761010080835404028352916020019162000b3c565b820191906000526020600020905b81548152906001019060200180831162000b1e57829003601f168201915b505050505090505b919050565b6034546001600160a01b0316331462000b6157600080fd5b80603a8360405162000b74919062002cb6565b90815260405190819003602001902080546001600160401b0392909216600160a01b0267ffffffffffffffff60a01b199092169190911790555050565b6035818154811062000a7b57fe5b6034546001600160a01b0316331462000bd757600080fd5b600081905060006001600160a01b031662000c64826001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b15801562000c2557600080fd5b505afa15801562000c3a573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052620004fc9190810190620029c4565b6001600160a01b03161462000c8d5760405162461bcd60e51b81526004016200085b9062002e46565b816037826001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b15801562000cca57600080fd5b505afa15801562000cdf573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405262000d099190810190620029c4565b60405162000d18919062002cb6565b90815260405190819003602001902080546001600160a01b039283166001600160a01b031991821617909155603580546001810182556000919091527fcfa4bec1d3298408bb5afcfcd9c430549c5b31f8aa5c5848151c0a55f473c34d0180549490921693169290921790915550565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062000dba90339060040162002cd4565b60206040518083038186803b15801562000dd357600080fd5b505afa15801562000de8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000e0e919062002964565b62000e2d5760405162461bcd60e51b81526004016200085b9062002f08565b6033546040805160016238880b60e11b03198152905162000e78926001600160a01b03169163ff8eefea916004808301926000929190829003018186803b158015620009c757600080fd5b6001600160a01b0316630357371d83836040518363ffffffff1660e01b815260040162000a3592919062002ce8565b6000806001600160a01b0316603a8360405162000ec5919062002cb6565b908152604051908190036020019020546001600160a01b0316141562000f925760398260405162000ef7919062002cb6565b9081526040805160209281900383018120805460026001821615610100026000190190911604601f8101859004850283018501909352828252909290919083018282801562000f8a5780601f1062000f5e5761010080835404028352916020019162000f8a565b820191906000526020600020905b81548152906001019060200180831162000f6c57829003601f168201915b505050505091505b603a8260405162000fa4919062002cb6565b908152604051908190036020019020546001600160401b03600160a01b909104169050919050565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062000ffe90339060040162002cd4565b60206040518083038186803b1580156200101757600080fd5b505afa1580156200102c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001052919062002964565b620010715760405162461bcd60e51b81526004016200085b9062002f08565b6001600160a01b038083166000908152603b6020526040808220805485019055603354815163059f833760e41b81529151620011159491909116926359f833709260048082019391829003018186803b158015620010ce57600080fd5b505afa158015620010e3573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526200110d9190810190620029c4565b8284620020ea565b5050565b603b6020526000908152604090205481565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef906200115d90339060040162002cd4565b60206040518083038186803b1580156200117657600080fd5b505afa1580156200118b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620011b1919062002964565b620011d05760405162461bcd60e51b81526004016200085b9062002f08565b6033546040805163dbe3a38160e01b815290516001600160a01b039092169163a3c5cbc591839163dbe3a38191600480820192600092909190829003018186803b1580156200121e57600080fd5b505afa15801562001233573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526200125d9190810190620029c4565b6040518263ffffffff1660e01b81526004016200127b919062002ddd565b60206040518083038186803b1580156200129457600080fd5b505afa158015620012a9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620012cf919062002c50565b60335460405163a3c5cbc560e01b81526001600160a01b039091169063a3c5cbc5906200130190879060040162002ddd565b60206040518083038186803b1580156200131a57600080fd5b505afa1580156200132f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001355919062002c50565b14156200138557813410156200137f5760405162461bcd60e51b81526004016200085b9062002e6b565b620014a2565b600062001392846200170b565b905082816001600160a01b031663dd62ed3e84306040518363ffffffff1660e01b8152600401620013c592919062002d01565b60206040518083038186803b158015620013de57600080fd5b505afa158015620013f3573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001419919062002c50565b10156200143a5760405162461bcd60e51b81526004016200085b9062002e93565b6040516323b872dd60e01b81526001600160a01b038216906323b872dd906200146c9085903090889060040162002d1b565b600060405180830381600087803b1580156200148757600080fd5b505af11580156200149c573d6000803e3d6000fd5b50505050505b505050565b600054610100900460ff1680620014c35750620014c3620026cc565b80620014d2575060005460ff16155b620014f15760405162461bcd60e51b81526004016200085b9062002eba565b600054610100900460ff161580156200151d576000805460ff1961ff0019909116610100171660011790555b603480546001600160a01b038086166001600160a01b03199283161790925560338054928516929091169190911790558015620014a2576000805461ff0019169055505050565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef906200159690339060040162002cd4565b60206040518083038186803b158015620015af57600080fd5b505afa158015620015c4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620015ea919062002964565b620016095760405162461bcd60e51b81526004016200085b9062002f08565b6200161481620023f7565b6001600160a01b031663282d3fdf84846040518363ffffffff1660e01b81526004016200089e92919062002ce8565b805160208183018101805160398252928201938201939093209190925280546040805160026001841615610100026000190190931692909204601f81018590048502830185019091528082529092830182828015620016e65780601f10620016ba57610100808354040283529160200191620016e6565b820191906000526020600020905b815481529060010190602001808311620016c857829003601f168201915b505050505081565b8051602081830181018051603d8252928201919093012091525481565b60006037826040516200171f919062002cb6565b908152604051908190036020019020546001600160a01b03169050919050565b6034546001600160a01b031633146200175757600080fd5b60005b6036548110156200111557603681815481106200177357fe5b6000918252602090912001546040516308f2839760e41b81526001600160a01b0390911690638f28397090620017ae90859060040162002cd4565b600060405180830381600087803b158015620017c957600080fd5b505af1158015620017de573d6000803e3d6000fd5b5050600190920191506200175a9050565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef906200182190339060040162002cd4565b60206040518083038186803b1580156200183a57600080fd5b505afa1580156200184f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001875919062002964565b620018945760405162461bcd60e51b81526004016200085b9062002f08565b6033546040805160016238880b60e11b031981529051620018df926001600160a01b03169163ff8eefea916004808301926000929190829003018186803b158015620009c757600080fd5b6001600160a01b03166379cc679083836040518363ffffffff1660e01b815260040162000a3592919062002ce8565b6034546001600160a01b031681565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef906200194f90339060040162002cd4565b60206040518083038186803b1580156200196857600080fd5b505afa1580156200197d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620019a3919062002964565b620019c25760405162461bcd60e51b81526004016200085b9062002f08565b6001600160a01b039091166000908152603b602052604090208054919091039055565b6034546001600160a01b03163314620019fd57600080fd5b603480546001600160a01b0319166001600160a01b0392909216919091179055565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062001a5190339060040162002cd4565b60206040518083038186803b15801562001a6a57600080fd5b505afa15801562001a7f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001aa5919062002964565b62001ac45760405162461bcd60e51b81526004016200085b9062002f08565b8060388360405162001ad7919062002cb6565b90815260200160405180910390209080519060200190620014a2929190620026d2565b6034546000906001600160a01b0316331462001b1557600080fd5b6000868685303060405162001b2a9062002757565b62001b3a95949392919062002df2565b604051809103906000f08015801562001b57573d6000803e3d6000fd5b5090508560398460405162001b6d919062002cb6565b9081526020016040518091039020908051906020019062001b90929190620026d2565b506035805460018181019092557fcfa4bec1d3298408bb5afcfcd9c430549c5b31f8aa5c5848151c0a55f473c34d0180546001600160a01b0384166001600160a01b031991821681179092556036805493840181556000527f4a11f94e20a93c79f6ec743a1954ec4fc2c08429ae2122118bf234b2185c81b8909201805490921681179091556040805180820182529182526001600160401b038716602083015251603a9062001c4290899062002cb6565b908152604080516020928190038301812084518154958501516001600160a01b03199096166001600160a01b039182161767ffffffffffffffff60a01b1916600160a01b6001600160401b039097169690960295909517905560335463313ce56760e01b82529151918416936330ceb8129386938d938d9386169263313ce56792600480840193829003018186803b15801562001cde57600080fd5b505afa15801562001cf3573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001d19919062002c69565b6040518563ffffffff1660e01b815260040162001d3a949392919062002d3f565b600060405180830381600087803b15801562001d5557600080fd5b505af115801562001d6a573d6000803e3d6000fd5b50929998505050505050505050565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062001dab90339060040162002cd4565b60206040518083038186803b15801562001dc457600080fd5b505afa15801562001dd9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001dff919062002964565b62001e1e5760405162461bcd60e51b81526004016200085b9062002f08565b62001e2981620023f7565b6001600160a01b03166379cc679084846040518363ffffffff1660e01b81526004016200089e92919062002ce8565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062001e8a90339060040162002cd4565b60206040518083038186803b15801562001ea357600080fd5b505afa15801562001eb8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001ede919062002964565b62001efd5760405162461bcd60e51b81526004016200085b9062002f08565b62001f0881620023f7565b6001600160a01b0316630357371d84846040518363ffffffff1660e01b81526004016200089e92919062002ce8565b8051602081830181018051603c8252928201919093012091525481565b805160208183018101805160388252928201938201939093209190925280546040805160026001841615610100026000190190931692909204601f81018590048502830185019091528082529092830182828015620016e65780601f10620016ba57610100808354040283529160200191620016e6565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062001ffd90339060040162002cd4565b60206040518083038186803b1580156200201657600080fd5b505afa1580156200202b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062002051919062002964565b620020705760405162461bcd60e51b81526004016200085b9062002f08565b6033546040805160016238880b60e11b031981529051620020bb926001600160a01b03169163ff8eefea916004808301926000929190829003018186803b158015620009c757600080fd5b6001600160a01b03166340c10f1983836040518363ffffffff1660e01b815260040162000a3592919062002ce8565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef906200211c90339060040162002cd4565b60206040518083038186803b1580156200213557600080fd5b505afa1580156200214a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062002170919062002964565b6200218f5760405162461bcd60e51b81526004016200085b9062002f08565b6033546040805163dbe3a38160e01b815290516001600160a01b039092169163a3c5cbc591839163dbe3a38191600480820192600092909190829003018186803b158015620021dd57600080fd5b505afa158015620021f2573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526200221c9190810190620029c4565b6040518263ffffffff1660e01b81526004016200223a919062002ddd565b60206040518083038186803b1580156200225357600080fd5b505afa15801562002268573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200228e919062002c50565b60335460405163a3c5cbc560e01b81526001600160a01b039091169063a3c5cbc590620022c090879060040162002ddd565b60206040518083038186803b158015620022d957600080fd5b505afa158015620022ee573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062002314919062002c50565b141562002359576040516001600160a01b0382169083156108fc029084906000818181858888f1935050505015801562002352573d6000803e3d6000fd5b50620014a2565b600062002366846200170b565b60405163a9059cbb60e01b81529091506001600160a01b0382169063a9059cbb906200146c908590879060040162002ce8565b6034546001600160a01b03163314620023b157600080fd5b80603a83604051620023c4919062002cb6565b90815260405190819003602001902080546001600160a01b03929092166001600160a01b03199092169190911790555050565b6000603a826040516200171f919062002cb6565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef906200243d90339060040162002cd4565b60206040518083038186803b1580156200245657600080fd5b505afa1580156200246b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062002491919062002964565b620024b05760405162461bcd60e51b81526004016200085b9062002f08565b620024bd85848662001e58565b620024ca85848662001d79565b82603c85604051620024dd919062002cb6565b90815260405190819003602001902055620024fa858383620007b6565b6200250785838362001564565b81603d826040516200251a919062002cb6565b908152604051908190036020019020555050505050565b6000805b603554811015620025aa57603a8360405162002552919062002cb6565b90815260405190819003602001902054603580546001600160a01b0390921691839081106200257d57fe5b6000918252602090912001546001600160a01b03161415620025a157905062000b44565b60010162002535565b50919050565b606060358054806020026020016040519081016040528092919081815260200182805480156200260a57602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311620025eb575b5050505050905090565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef906200264690339060040162002cd4565b60206040518083038186803b1580156200265f57600080fd5b505afa15801562002674573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200269a919062002964565b620026b95760405162461bcd60e51b81526004016200085b9062002f08565b8060398360405162001ad7919062002cb6565b303b1590565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200271557805160ff191683800117855562002745565b8280016001018555821562002745579182015b828111156200274557825182559160200191906001019062002728565b506200275392915062002765565b5090565b6123b7806200301183390190565b5b8082111562002753576000815560010162002766565b600082601f8301126200278d578081fd5b8135620027a46200279e8262002f7a565b62002f53565b9150808252836020828501011115620027bc57600080fd5b8060208401602084013760009082016020015292915050565b600060208284031215620027e7578081fd5b8135620027f48162002fd1565b9392505050565b600080604083850312156200280e578081fd5b82356200281b8162002fd1565b946020939093013593505050565b600080604083850312156200283c578182fd5b8235620028498162002fd1565b915060208301356200285b8162002fd1565b809150509250929050565b600080600080600060a086880312156200287e578081fd5b85356200288b8162002fd1565b945060208601356001600160401b0380821115620028a7578283fd5b620028b589838a016200277c565b955060408801359450606088013593506080880135915080821115620028d9578283fd5b50620028e8888289016200277c565b9150509295509295909350565b600080604083850312156200280e578182fd5b6000806000606084860312156200291d578283fd5b83356200292a8162002fd1565b92506020840135915060408401356001600160401b038111156200294c578182fd5b6200295a868287016200277c565b9150509250925092565b60006020828403121562002976578081fd5b81518015158114620027f4578182fd5b60006020828403121562002998578081fd5b81356001600160401b03811115620029ae578182fd5b620029bc848285016200277c565b949350505050565b600060208284031215620029d6578081fd5b81516001600160401b03811115620029ec578182fd5b8201601f81018413620029fd578182fd5b805162002a0e6200279e8262002f7a565b81815285602083850101111562002a23578384fd5b62002a3682602083016020860162002f9e565b95945050505050565b6000806040838503121562002a52578182fd5b82356001600160401b0381111562002a68578283fd5b62002a76858286016200277c565b92505060208301356200285b8162002fd1565b6000806040838503121562002a9c578182fd5b82356001600160401b038082111562002ab3578384fd5b62002ac1868387016200277c565b9350602085013591508082111562002ad7578283fd5b5062002ae6858286016200277c565b9150509250929050565b600080600080600060a0868803121562002b08578081fd5b85356001600160401b038082111562002b1f578283fd5b62002b2d89838a016200277c565b9650602088013591508082111562002b43578283fd5b62002b5189838a016200277c565b95506040880135915062002b658262002fea565b90935060608701359062002b798262003000565b90925060808701359080821115620028d9578283fd5b60008060006060848603121562002ba4578081fd5b83356001600160401b0381111562002bba578182fd5b62002bc8868287016200277c565b93505060208401359150604084013562002be28162002fd1565b809150509250925092565b6000806040838503121562002c00578182fd5b82356001600160401b0381111562002c16578283fd5b62002c24858286016200277c565b92505060208301356200285b8162002fea565b60006020828403121562002c49578081fd5b5035919050565b60006020828403121562002c62578081fd5b5051919050565b60006020828403121562002c7b578081fd5b8151620027f48162003000565b6000815180845262002ca281602086016020860162002f9e565b601f01601f19169290920160200192915050565b6000825162002cca81846020870162002f9e565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b03929092168252602082015260400190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b038516815260806020820181905260009062002d659083018662002c88565b828103604084015262002d79818662002c88565b91505060ff8316606083015295945050505050565b6020808252825182820181905260009190848201906040850190845b8181101562002dd15783516001600160a01b03168352928401929184019160010162002daa565b50909695505050505050565b600060208252620027f4602083018462002c88565b600060a0825262002e0760a083018862002c88565b828103602084015262002e1b818862002c88565b60ff96909616604084015250506001600160a01b039283166060820152911660809091015292915050565b6020808252600b908201526a1d1bdad95b88195e1a5cdd60aa1b604082015260600190565b6020808252600e908201526d125b9d985b1a5908105b5bdd5b9d60921b604082015260600190565b6020808252600d908201526c73657420616c6c6f77616e636560981b604082015260600190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b6020808252601490820152734e6f7420467269656e646c79204164647265737360601b604082015260600190565b90815260200190565b6001600160401b0391909116815260200190565b6040518181016001600160401b038111828210171562002f7257600080fd5b604052919050565b60006001600160401b0382111562002f90578081fd5b50601f01601f191660200190565b60005b8381101562002fbb57818101518382015260200162002fa1565b8381111562002fcb576000848401525b50505050565b6001600160a01b038116811462002fe757600080fd5b50565b6001600160401b038116811462002fe757600080fd5b60ff8116811462002fe757600080fdfe60806040523480156200001157600080fd5b50604051620023b7380380620023b7833981810160405260a08110156200003757600080fd5b81019080805160405193929190846401000000008211156200005857600080fd5b9083019060208201858111156200006e57600080fd5b82516401000000008111828201881017156200008957600080fd5b82525081516020918201929091019080838360005b83811015620000b85781810151838201526020016200009e565b50505050905090810190601f168015620000e65780820380516001836020036101000a031916815260200191505b50604052602001805160405193929190846401000000008211156200010a57600080fd5b9083019060208201858111156200012057600080fd5b82516401000000008111828201881017156200013b57600080fd5b82525081516020918201929091019080838360005b838110156200016a57818101518382015260200162000150565b50505050905090810190601f168015620001985780820380516001836020036101000a031916815260200191505b506040908152602082810151918301516060909301518751929550929350869186918691620001ce9160059190860190620003b1565b508151620001e4906006906020850190620003b1565b506007805460ff191660ff929092169190911761ff0019169055506200020e90506000836200029d565b6200023a7fde00661a9bee31b253f6d0c9cfdafe0b25df2574c0f3debb8203f6dcff62d654826200029d565b620002667f9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a6836200029d565b620002927f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a836200029d565b50505050506200044d565b620002a98282620002ad565b5050565b600082815260208181526040909120620002d291839062000e3f62000326821b17901c565b15620002a957620002e262000346565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60006200033d836001600160a01b0384166200034a565b90505b92915050565b3390565b600062000358838362000399565b620003905750815460018181018455600084815260208082209093018490558454848252828601909352604090209190915562000340565b50600062000340565b60009081526001919091016020526040902054151590565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10620003f457805160ff191683800117855562000424565b8280016001018555821562000424579182015b828111156200042457825182559160200191906001019062000407565b506200043292915062000436565b5090565b5b8082111562000432576000815560010162000437565b611f5a806200045d6000396000f3fe608060405234801561001057600080fd5b50600436106101f05760003560e01c806379cc67901161010f578063a457c2d7116100a2578063d547741f11610071578063d547741f1461061b578063dd62ed3e14610647578063e10f67ca14610675578063e63ab1e91461067d576101f0565b8063a457c2d71461059e578063a9059cbb146105ca578063ca15c873146105f6578063d539139314610613576101f0565b806391d14854116100de57806391d148541461053c57806395d89b4114610568578063a153e70814610570578063a217fddf14610596576101f0565b806379cc6790146104a35780638456cb59146104cf5780638f283970146104d75780639010d07c146104fd576101f0565b8063313ce5671161018757806340c10f191161015657806340c10f19146104235780635c975abb1461044f578063654259dd1461045757806370a082311461047d576101f0565b8063313ce567146103a557806336568abe146103c357806339509351146103ef5780633f4ba83a1461041b576101f0565b806323b872dd116101c357806323b872dd146102fa578063248a9ca314610330578063282d3fdf1461034d5780632f2ff15d14610379576101f0565b80630357371d146101f557806306fdde0314610223578063095ea7b3146102a057806318160ddd146102e0575b600080fd5b6102216004803603604081101561020b57600080fd5b506001600160a01b038135169060200135610685565b005b61022b6106ed565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561026557818101518382015260200161024d565b50505050905090810190601f1680156102925780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102cc600480360360408110156102b657600080fd5b506001600160a01b038135169060200135610783565b604080519115158252519081900360200190f35b6102e86107a1565b60408051918252519081900360200190f35b6102cc6004803603606081101561031057600080fd5b506001600160a01b038135811691602081013590911690604001356107a7565b6102e86004803603602081101561034657600080fd5b503561082e565b6102216004803603604081101561036357600080fd5b506001600160a01b038135169060200135610843565b6102216004803603604081101561038f57600080fd5b50803590602001356001600160a01b03166108a2565b6103ad610905565b6040805160ff9092168252519081900360200190f35b610221600480360360408110156103d957600080fd5b50803590602001356001600160a01b031661090e565b6102cc6004803603604081101561040557600080fd5b506001600160a01b03813516906020013561096f565b6102216109bd565b6102216004803603604081101561043957600080fd5b506001600160a01b038135169060200135610a1c565b6102cc610a7b565b6102e86004803603602081101561046d57600080fd5b50356001600160a01b0316610a89565b6102e86004803603602081101561049357600080fd5b50356001600160a01b0316610ab5565b610221600480360360408110156104b957600080fd5b506001600160a01b038135169060200135610ad0565b610221610b2f565b610221600480360360208110156104ed57600080fd5b50356001600160a01b0316610b8c565b6105206004803603604081101561051357600080fd5b5080359060200135610c31565b604080516001600160a01b039092168252519081900360200190f35b6102cc6004803603604081101561055257600080fd5b50803590602001356001600160a01b0316610c50565b61022b610c68565b6102e86004803603602081101561058657600080fd5b50356001600160a01b0316610cc9565b6102e8610cdb565b6102cc600480360360408110156105b457600080fd5b506001600160a01b038135169060200135610ce0565b6102cc600480360360408110156105e057600080fd5b506001600160a01b038135169060200135610d48565b6102e86004803603602081101561060c57600080fd5b5035610d5c565b6102e8610d73565b6102216004803603604081101561063157600080fd5b50803590602001356001600160a01b0316610d85565b6102e86004803603604081101561065d57600080fd5b506001600160a01b0381358116916020013516610dde565b6102e8610e09565b6102e8610e2d565b6106a4600080516020611ccd83398151915261069f610e54565b610c50565b6106df5760405162461bcd60e51b8152600401808060200182810382526038815260200180611eed6038913960400191505060405180910390fd5b6106e98282610e58565b5050565b60058054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156107795780601f1061074e57610100808354040283529160200191610779565b820191906000526020600020905b81548152906001019060200180831161075c57829003601f168201915b5050505050905090565b6000610797610790610e54565b8484610f4d565b5060015b92915050565b60045490565b60006107b4848484611080565b610824846107c0610e54565b61081f85604051806060016040528060288152602001611c4f602891396001600160a01b038a166000908152600360205260408120906107fe610e54565b6001600160a01b031681526020810191909152604001600020549190611224565b610f4d565b5060019392505050565b60009081526020819052604090206002015490565b61085d600080516020611ccd83398151915261069f610e54565b6108985760405162461bcd60e51b8152600401808060200182810382526035815260200180611de26035913960400191505060405180910390fd5b6106e982826112bb565b6000828152602081905260409020600201546108c09061069f610e54565b6108fb5760405162461bcd60e51b815260040180806020018281038252602f815260200180611ac5602f913960400191505060405180910390fd5b6106e98282611380565b60075460ff1690565b610916610e54565b6001600160a01b0316816001600160a01b0316146109655760405162461bcd60e51b815260040180806020018281038252602f815260200180611e94602f913960400191505060405180910390fd5b6106e982826113e9565b600061079761097c610e54565b8461081f856003600061098d610e54565b6001600160a01b03908116825260208083019390935260409182016000908120918c168152925290205490611452565b6109d7600080516020611c7783398151915261069f610e54565b610a125760405162461bcd60e51b8152600401808060200182810382526039815260200180611b166039913960400191505060405180910390fd5b610a1a6114ac565b565b610a36600080516020611ccd83398151915261069f610e54565b610a715760405162461bcd60e51b8152600401808060200182810382526036815260200180611c976036913960400191505060405180910390fd5b6106e98282611550565b600754610100900460ff1690565b6001600160a01b03811660009081526002602052604081205461079b90610aaf84610ab5565b90611642565b6001600160a01b031660009081526001602052604090205490565b610aea600080516020611ccd83398151915261069f610e54565b610b255760405162461bcd60e51b8152600401808060200182810382526035815260200180611bc36035913960400191505060405180910390fd5b6106e98282611684565b610b49600080516020611c7783398151915261069f610e54565b610b845760405162461bcd60e51b8152600401808060200182810382526037815260200180611dab6037913960400191505060405180910390fd5b610a1a6117c7565b610bb87fde00661a9bee31b253f6d0c9cfdafe0b25df2574c0f3debb8203f6dcff62d65461069f610e54565b610bf35760405162461bcd60e51b815260040180806020018281038252602d815260200180611e67602d913960400191505060405180910390fd5b610bfe6000826108fb565b610c16600080516020611ccd833981519152826108fb565b610c2e600080516020611c77833981519152826108fb565b50565b6000828152602081905260408120610c49908361184f565b9392505050565b6000828152602081905260408120610c49908361185b565b60068054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156107795780601f1061074e57610100808354040283529160200191610779565b60026020526000908152604090205481565b600081565b6000610797610ced610e54565b8461081f85604051806060016040528060258152602001611e426025913960036000610d17610e54565b6001600160a01b03908116825260208083019390935260409182016000908120918d16815292529020549190611224565b6000610797610d55610e54565b8484611080565b600081815260208190526040812061079b90611870565b600080516020611ccd83398151915281565b600082815260208190526040902060020154610da39061069f610e54565b6109655760405162461bcd60e51b8152600401808060200182810382526030815260200180611bf86030913960400191505060405180910390fd5b6001600160a01b03918216600090815260036020908152604080832093909416825291909152205490565b7fde00661a9bee31b253f6d0c9cfdafe0b25df2574c0f3debb8203f6dcff62d65481565b600080516020611c7783398151915281565b6000610c49836001600160a01b03841661187b565b3390565b6001600160a01b038216610eb3576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a2072656c6561736520666f72207a65726f206164647265737300604482015290519081900360640190fd5b6001600160a01b038216600090815260026020526040902054811115610f0a5760405162461bcd60e51b815260040180806020018281038252602c815260200180611b71602c913960400191505060405180910390fd5b6001600160a01b038216600090815260026020526040902054610f2d9082611642565b6001600160a01b0390921660009081526002602052604090209190915550565b6001600160a01b038316610f925760405162461bcd60e51b8152600401808060200182810382526024815260200180611d586024913960400191505060405180910390fd5b6001600160a01b038216610fd75760405162461bcd60e51b8152600401808060200182810382526022815260200180611b4f6022913960400191505060405180910390fd5b610fe083610a89565b81111561101e5760405162461bcd60e51b815260040180806020018281038252602f815260200180611d7c602f913960400191505060405180910390fd5b6001600160a01b03808416600081815260036020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b0383166110c55760405162461bcd60e51b8152600401808060200182810382526025815260200180611d336025913960400191505060405180910390fd5b6001600160a01b03821661110a5760405162461bcd60e51b8152600401808060200182810382526023815260200180611aa26023913960400191505060405180910390fd5b61111383610a89565b8111156111515760405162461bcd60e51b8152600401808060200182810382526027815260200180611c286027913960400191505060405180910390fd5b61115c8383836118c5565b61119981604051806060016040528060268152602001611b9d602691396001600160a01b0386166000908152600160205260409020549190611224565b6001600160a01b0380851660009081526001602052604080822093909355908416815220546111c89082611452565b6001600160a01b0380841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600081848411156112b35760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611278578181015183820152602001611260565b50505050905090810190601f1680156112a55780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b6001600160a01b038216611316576040805162461bcd60e51b815260206004820152601c60248201527f45524332303a206c6f636b20666f72207a65726f206164647265737300000000604482015290519081900360640190fd5b61131f82610a89565b81111561135d5760405162461bcd60e51b815260040180806020018281038252602b815260200180611e17602b913960400191505060405180910390fd5b6001600160a01b038216600090815260026020526040902054610f2d9082611452565b60008281526020819052604090206113989082610e3f565b156106e9576113a5610e54565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b600082815260208190526040902061140190826118d5565b156106e95761140e610e54565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b600082820183811015610c49576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b600754610100900460ff166114ff576040805162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604482015290519081900360640190fd5b6007805461ff00191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa611533610e54565b604080516001600160a01b039092168252519081900360200190a1565b6001600160a01b0382166115ab576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015290519081900360640190fd5b6115b7600083836118c5565b6004546115c49082611452565b6004556001600160a01b0382166000908152600160205260409020546115ea9082611452565b6001600160a01b03831660008181526001602090815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b6000610c4983836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250611224565b6001600160a01b0382166116c95760405162461bcd60e51b8152600401808060200182810382526021815260200180611d126021913960400191505060405180910390fd5b6116d282610a89565b8111156117105760405162461bcd60e51b8152600401808060200182810382526025815260200180611ced6025913960400191505060405180910390fd5b61171c826000836118c5565b61175981604051806060016040528060228152602001611af4602291396001600160a01b0385166000908152600160205260409020549190611224565b6001600160a01b03831660009081526001602052604090205560045461177f9082611642565b6004556040805182815290516000916001600160a01b038516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050565b600754610100900460ff1615611817576040805162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b604482015290519081900360640190fd5b6007805461ff0019166101001790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258611533610e54565b6000610c4983836118ea565b6000610c49836001600160a01b03841661194e565b600061079b82611966565b6000611887838361194e565b6118bd5750815460018181018455600084815260208082209093018490558454848252828601909352604090209190915561079b565b50600061079b565b6118d083838361196a565b505050565b6000610c49836001600160a01b0384166119b9565b8154600090821061192c5760405162461bcd60e51b8152600401808060200182810382526022815260200180611a806022913960400191505060405180910390fd5b82600001828154811061193b57fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b5490565b6119758383836118d0565b61197d610a7b565b156118d05760405162461bcd60e51b815260040180806020018281038252602a815260200180611ec3602a913960400191505060405180910390fd5b60008181526001830160205260408120548015611a7557835460001980830191908101906000908790839081106119ec57fe5b9060005260206000200154905080876000018481548110611a0957fe5b600091825260208083209091019290925582815260018981019092526040902090840190558654879080611a3957fe5b6001900381819060005260206000200160009055905586600101600087815260200190815260200160002060009055600194505050505061079b565b600091505061079b56fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e647345524332303a207472616e7366657220746f20746865207a65726f2061646472657373416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f206772616e7445524332303a206275726e20616d6f756e7420657863656564732062616c616e636545524332305072657365744d696e7465725061757365723a206d75737420686176652070617573657220726f6c6520746f20756e706175736545524332303a20617070726f766520746f20746865207a65726f20616464726573734552433230203a2072656c656173652076616c7565206d6f7265207468656e206c6f636b65642076616c756545524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332305072657365744d696e7465725061757365723a206d75737420686176652061646d696e20726f6c6520746f206275726e416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f207265766f6b654552433230203a20616d6f756e74206578636565647320617661696c61626c6520616d6f756e7445524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636565d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a45524332305072657365744d696e7465725061757365723a206d7573742068617665206d696e74657220726f6c6520746f206d696e749f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a64552433230203a206275726e206578636565647320617661696c61626c6520616d6f756e7445524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f20616464726573734552433230203a20617070726f766520616d6f756e74206578636565647320617661696c61626c6520616d6f756e7445524332305072657365744d696e7465725061757365723a206d75737420686176652070617573657220726f6c6520746f20706175736545524332305072657365744d696e7465725061757365723a206d75737420686176652061646d696e20726f6c6520746f206c6f636b45524332303a206c6f636b2076616c7565206d6f72652074686120617661696c61626c6520616d6f756e7445524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726f45524332305072657365744d696e7465725061757365723a206d75737420686176652061646d696e20726f6c65416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636520726f6c657320666f722073656c6645524332305061757361626c653a20746f6b656e207472616e73666572207768696c652070617573656445524332305072657365744d696e7465725061757365723a206d75737420686176652061646d696e20726f6c6520746f2072656c65617365a264697066735822122043e50b954e8de778aad15e090b5e91d9521cb66a65083bff85dee41855e2e95164736f6c634300060c0033a26469706673582212200802d6c75ce211e44ce2c44ff4d9b2f91ada79042b4526603119cc2311a8263164736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-eth", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-eth', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
33
0x0d3303ffaf107cd732396570bf07b2dbd79b619f
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 / 40000; // MIN_FEE = 0.0025% uint public constant MAX_FEE = BONE / 10; // MAX_FEE = 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 BFactory is BBronze { event LOG_NEW_POOL( address indexed caller, address indexed pool ); event LOG_BLABS( address indexed caller, address indexed blabs ); event LOG_RESERVES_ADDRESS( address indexed caller, address indexed reservesAddress ); event LOG_ALLOW_NON_ADMIN_POOL( address indexed caller, bool allow ); mapping(address=>bool) private _isBPool; function isBPool(address b) external view returns (bool) { return _isBPool[b]; } function newBPool() external returns (BPool) { if (!_allowNonAdminPool) { require(msg.sender == _blabs); } BPool bpool = new BPool(); _isBPool[address(bpool)] = true; emit LOG_NEW_POOL(msg.sender, address(bpool)); bpool.setController(msg.sender); return bpool; } address private _blabs; address private _reservesAddress; bool private _allowNonAdminPool; constructor() public { _blabs = msg.sender; _reservesAddress = msg.sender; _allowNonAdminPool = false; } function getAllowNonAdminPool() external view returns (bool) { return _allowNonAdminPool; } function setAllowNonAdminPool(bool b) external { require(msg.sender == _blabs, "ERR_NOT_BLABS"); emit LOG_ALLOW_NON_ADMIN_POOL(msg.sender, b); _allowNonAdminPool = b; } function getBLabs() external view returns (address) { return _blabs; } function setBLabs(address b) external { require(msg.sender == _blabs); emit LOG_BLABS(msg.sender, b); _blabs = b; } function getReservesAddress() external view returns (address) { return _reservesAddress; } function setReservesAddress(address a) external { require(msg.sender == _blabs); emit LOG_RESERVES_ADDRESS(msg.sender, a); _reservesAddress = a; } function collect(BPool pool) external { require(msg.sender == _blabs); require(_isBPool[address(pool)]); uint collected = IERC20(pool).balanceOf(address(this)); bool xfer = pool.transfer(_blabs, collected); require(xfer); } function collectTokenReserves(BPool pool) external { require(msg.sender == _blabs); require(_isBPool[address(pool)]); pool.drainTotalReserves(_reservesAddress); } } 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, "ERR_ADD_OVERFLOW"); return c; } function bsub(uint a, uint b) internal pure returns (uint) { (uint c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); 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, "ERR_MUL_OVERFLOW"); uint c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint c2 = c1 / BONE; return c2; } function bdiv(uint a, uint b) internal pure returns (uint) { require(b != 0, "ERR_DIV_ZERO"); uint c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // 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, "ERR_BPOW_BASE_TOO_LOW"); require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH"); 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 tokenInFee) { 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); tokenInFee = bsub(tokenAmountIn, adjustedIn); return (tokenAmountOut, tokenInFee); } /********************************************************************************************** // 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 tokenInFee) { uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BONE); foo = bmul(tokenBalanceIn, foo); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(foo, tokenAmountIn); tokenInFee = bdiv(foo, BONE); tokenInFee = bsub(tokenAmountIn, tokenInFee); return (tokenAmountIn, tokenInFee); } /********************************************************************************************** // 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, "ERR_MATH_APPROX"); require(reservesRatio <= BONE, "ERR_INVALID_RESERVE"); uint swapFeeAndReserves = bsub(amountWithFee, amountWithoutFee); reserves = bmul(swapFeeAndReserves, reservesRatio); require(swapFeeAndReserves >= reserves, "ERR_MATH_APPROX"); } function calcReservesFromFee(uint fee, uint reservesRatio) internal pure returns (uint reserves) { require(reservesRatio <= BONE, "ERR_INVALID_RESERVE"); reserves = bmul(fee, reservesRatio); } } 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, uint256 reservesAmount ); event LOG_JOIN( address indexed caller, address indexed tokenIn, uint256 tokenAmountIn, uint256 reservesAmount ); event LOG_EXIT( address indexed caller, address indexed tokenOut, uint256 tokenAmountOut, uint256 reservesAmount ); event LOG_DRAIN_RESERVES( address indexed caller, address indexed tokenOut, uint256 tokenAmountOut ); event LOG_ADD_RESERVES( address indexed token, uint256 reservesAmount ); 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); require(reservesRatio >= DEFAULT_RESERVES_RATIO); _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); uint erc20Balance = IERC20(token).balanceOf(address(this)); uint reserves = totalReserves[token]; // `_records[token].balance` should be equaled to `bsub(erc20Balance, reserves)` unless there are extra // tokens transferred to this pool without calling `joinxxx`. require(_records[token].balance <= bsub(erc20Balance, reserves)); _records[token].balance = bsub(erc20Balance, reserves); } 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, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_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, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_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, "ERR_NOT_FINALIZED"); uint poolTotal = totalSupply(); uint ratio = bdiv(poolAmountOut, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); 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, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN"); _records[t].balance = badd(_records[t].balance, tokenAmountIn); emit LOG_JOIN(msg.sender, t, tokenAmountIn, 0); _pullUnderlying(t, msg.sender, tokenAmountIn); } _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); } function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external _logs_ _lock_ { require(_finalized, "ERR_NOT_FINALIZED"); uint poolTotal = totalSupply(); uint exitFee = bmul(poolAmountIn, EXIT_FEE); uint pAiAfterExitFee = bsub(poolAmountIn, exitFee); uint ratio = bdiv(pAiAfterExitFee, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); _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, "ERR_MATH_APPROX"); require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT"); _records[t].balance = bsub(_records[t].balance, tokenAmountOut); emit LOG_EXIT(msg.sender, t, tokenAmountOut, 0); _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, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); require(_publicSwap, "ERR_SWAP_NOT_PUBLIC"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO"); uint spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE"); uint tokenInFee; (tokenAmountOut, tokenInFee) = calcOutGivenIn( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); uint reserves = calcReservesFromFee(tokenInFee, _reservesRatio); // Subtract `reserves`. 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, "ERR_MATH_APPROX"); require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE"); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut, reserves); totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves); emit LOG_ADD_RESERVES(address(tokenIn), 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, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); require(_publicSwap, "ERR_SWAP_NOT_PUBLIC"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO"); uint spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE"); uint tokenInFee; (tokenAmountIn, tokenInFee) = calcInGivenOut( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountOut, _swapFee ); require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN"); uint reserves = calcReservesFromFee( tokenInFee, _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, "ERR_MATH_APPROX"); require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE"); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut, reserves); totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves); emit LOG_ADD_RESERVES(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, "ERR_NOT_FINALIZED"); require(_records[tokenIn].bound, "ERR_NOT_BOUND"); require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "ERR_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, "ERR_LIMIT_OUT"); inRecord.balance = bsub(badd(inRecord.balance, tokenAmountIn), reserves); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn, reserves); totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves); emit LOG_ADD_RESERVES(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, "ERR_NOT_FINALIZED"); require(_records[tokenIn].bound, "ERR_NOT_BOUND"); Record storage inRecord = _records[tokenIn]; tokenAmountIn = calcSingleInGivenPoolOut( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, poolAmountOut, _swapFee ); require(tokenAmountIn != 0, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN"); require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "ERR_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, reserves); totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves); emit LOG_ADD_RESERVES(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, "ERR_NOT_FINALIZED"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); Record storage outRecord = _records[tokenOut]; tokenAmountOut = calcSingleOutGivenPoolIn( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, poolAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "ERR_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, reserves); totalReserves[address(tokenOut)] = badd(totalReserves[address(tokenOut)], reserves); emit LOG_ADD_RESERVES(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, "ERR_NOT_FINALIZED"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "ERR_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, "ERR_MATH_APPROX"); require(poolAmountIn <= maxPoolAmountIn, "ERR_LIMIT_IN"); outRecord.balance = bsub(bsub(outRecord.balance, tokenAmountOut), reserves); uint exitFee = bmul(poolAmountIn, EXIT_FEE); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut, reserves); totalReserves[address(tokenOut)] = badd(totalReserves[address(tokenOut)], reserves); emit LOG_ADD_RESERVES(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, "ERR_ERC20_FALSE"); } function _pushUnderlying(address erc20, address to, uint amount) internal { bool xfer = IERC20(erc20).transfer(to, amount); require(xfer, "ERR_ERC20_FALSE"); } 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); } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c8063c124b18411610071578063c124b18414610142578063c2bb6dc214610168578063c6ce34fb146101a2578063d556c5dc146101c8578063db90def3146101d0578063e5a23849146101ef576100a9565b806306ec16f8146100ae5780632ad415bd146100d657806336ffb167146100fa5780638318f24a146101025780639a86139b14610128575b600080fd5b6100d4600480360360208110156100c457600080fd5b50356001600160a01b03166101f7565b005b6100de610341565b604080516001600160a01b039092168252519081900360200190f35b6100de610350565b6100d46004803603602081101561011857600080fd5b50356001600160a01b031661035f565b6101306103ce565b60408051918252519081900360200190f35b6100d46004803603602081101561015857600080fd5b50356001600160a01b03166103db565b61018e6004803603602081101561017e57600080fd5b50356001600160a01b0316610480565b604080519115158252519081900360200190f35b6100d4600480360360208110156101b857600080fd5b50356001600160a01b031661049e565b6100de61050d565b6100d4600480360360208110156101e657600080fd5b50351515610617565b61018e6106bc565b6001546001600160a01b0316331461020e57600080fd5b6001600160a01b03811660009081526020819052604090205460ff1661023357600080fd5b604080516370a0823160e01b815230600482015290516000916001600160a01b038416916370a0823191602480820192602092909190829003018186803b15801561027d57600080fd5b505afa158015610291573d6000803e3d6000fd5b505050506040513d60208110156102a757600080fd5b50516001546040805163a9059cbb60e01b81526001600160a01b0392831660048201526024810184905290519293506000929185169163a9059cbb9160448082019260209290919082900301818787803b15801561030457600080fd5b505af1158015610318573d6000803e3d6000fd5b505050506040513d602081101561032e57600080fd5b505190508061033c57600080fd5b505050565b6002546001600160a01b031690565b6001546001600160a01b031690565b6001546001600160a01b0316331461037657600080fd5b6040516001600160a01b0382169033907fe33f2276fe6ea8141b3855e68646ebcf09ec2df8768afe2a7bf153c9b10c273b90600090a3600280546001600160a01b0319166001600160a01b0392909216919091179055565b6542524f4e5a4560d01b90565b6001546001600160a01b031633146103f257600080fd5b6001600160a01b03811660009081526020819052604090205460ff1661041757600080fd5b6002546040805163577756b360e11b81526001600160a01b03928316600482015290519183169163aeeead669160248082019260009290919082900301818387803b15801561046557600080fd5b505af1158015610479573d6000803e3d6000fd5b5050505050565b6001600160a01b031660009081526020819052604090205460ff1690565b6001546001600160a01b031633146104b557600080fd5b6040516001600160a01b0382169033907ff586fa6ee1fc42f5b727f3b214ccbd0b6d7e698c45d49ba32f224fbb8670155d90600090a3600180546001600160a01b0319166001600160a01b0392909216919091179055565b600254600090600160a01b900460ff16610538576001546001600160a01b0316331461053857600080fd5b6000604051610546906106cc565b604051809103906000f080158015610562573d6000803e3d6000fd5b506001600160a01b038116600081815260208190526040808220805460ff1916600117905551929350909133917f8ccec77b0cb63ac2cafd0f5de8cdfadab91ce656d262240ba8a6343bccc5f94591a3604080516392eefe9b60e01b815233600482015290516001600160a01b038316916392eefe9b91602480830192600092919082900301818387803b1580156105f957600080fd5b505af115801561060d573d6000803e3d6000fd5b5092935050505090565b6001546001600160a01b03163314610666576040805162461bcd60e51b815260206004820152600d60248201526c4552525f4e4f545f424c41425360981b604482015290519081900360640190fd5b604080518215158152905133917f3f7cb0f9d9d6328953db4b2e4654f86a01cb45ec1e39aa6665763281ddca54a7919081900360200190a260028054911515600160a01b0260ff60a01b19909216919091179055565b600254600160a01b900460ff1690565b6153ed806106da8339019056fe60c0604052601060808190527f437265616d20506f6f6c20546f6b656e0000000000000000000000000000000060a0908152620000409160039190620000ff565b506040805180820190915260048082527f43525054000000000000000000000000000000000000000000000000000000006020909201918252620000859181620000ff565b506005805460ff19166012179055348015620000a057600080fd5b50600680546005805462010000600160b01b03191633620100008102919091179091556516bcc41e90006007556702c68af0bb1400006008556001600160a01b03199091161760ff60a01b191690556009805460ff19169055620001a4565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200014257805160ff191683800117855562000172565b8280016001018555821562000172579182015b828111156200017257825182559160200191906001019062000155565b506200018092915062000184565b5090565b620001a191905b808211156200018057600081556001016200018b565b90565b61523980620001b46000396000f3fe608060405234801561001057600080fd5b506004361061039d5760003560e01c806392eefe9b116101eb578063bc694ea211610110578063dd62ed3e116100a8578063dd62ed3e14610c51578063e4a28a52146104fd578063e4e1e53814610c7f578063eb9253c014610cb1578063ec09302114610cdd578063f1b8a9b714610ce5578063f8b2cb4f14610d0b578063f8d6aed414610d31578063fde924f714610d6c5761039d565b8063bc694ea214610b7f578063be3bbd2e14610b87578063c36596a614610571578063c6580d1214610bdf578063cc77828d14610be7578063cd2ed8fb14610bef578063cf5e7bd314610bf7578063d4cadf6814610c1d578063d73dd62314610c255761039d565b8063a9059cbb11610183578063a9059cbb14610a40578063aeeead6614610a6c578063b02f0b7314610a92578063b0e0d13614610b07578063b4a8e10114610b0f578063b7b800a414610b2c578063ba019dab14610b34578063ba9530a614610b3c578063bc063e1a14610b775761039d565b806392eefe9b1461098f578063936c3477146109b55780639381cd2b146109bd57806393c88d14146109c5578063948d8ce6146109cd57806395d89b41146109f3578063992e2a92146109fb5780639a86139b14610a03578063a221ee4914610a0b5761039d565b806346ab38f1116102d15780636d0800bc116102695780636d0800bc1461084a57806370a082311461087057806376c7a3c7146108965780637c5e9ea41461089e5780638201aa3f146108de578063867378c51461091e57806389298012146109265780638c28cbe8146109615780638d4e4083146109875761039d565b806346ab38f1146106a957806349b59552146106db5780634bb278f3146106fa5780634d2fd81d146107025780634f69c0d41461070a5780635c1bbaf71461077f5780635db34277146107ba57806366188463146107ec5780636d06dfa0146108185761039d565b8063189d00ca11610344578063189d00ca14610569578063218b53821461057157806321abba011461057957806323b872dd146105ba5780632f37b624146105f05780633018205f14610616578063313ce5671461063a57806334e19907146106585780633fdddaa2146106775761039d565b8063024eb2e3146103a257806302c96748146103fc57806306fdde0314610440578063095ea7b3146104bd57806309a3bbe4146104fd5780631446a7ff1461050557806315e84af91461053357806318160ddd14610561575b600080fd5b6103e3600480360360e08110156103b857600080fd5b5080359060208101359060408101359060608101359060808101359060a08101359060c00135610d74565b6040805192835260208301919091528051918290030190f35b61042e6004803603606081101561041257600080fd5b506001600160a01b038135169060208101359060400135610e43565b60408051918252519081900360200190f35b6104486111df565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561048257818101518382015260200161046a565b50505050905090810190601f1680156104af5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6104e9600480360360408110156104d357600080fd5b506001600160a01b038135169060200135611275565b604080519115158252519081900360200190f35b61042e6112ca565b61042e6004803603604081101561051b57600080fd5b506001600160a01b03813581169160200135166112d7565b61042e6004803603604081101561054957600080fd5b506001600160a01b03813581169160200135166113f6565b61042e61150c565b61042e611512565b61042e611526565b6103e3600480360360e081101561058f57600080fd5b5080359060208101359060408101359060608101359060808101359060a08101359060c00135611532565b6104e9600480360360608110156105d057600080fd5b506001600160a01b038135811691602081013590911690604001356115df565b6104e96004803603602081101561060657600080fd5b50356001600160a01b03166116f9565b61061e611717565b604080516001600160a01b039092168252519081900360200190f35b61064261173f565b6040805160ff9092168252519081900360200190f35b6106756004803603602081101561066e57600080fd5b5035611748565b005b6106756004803603606081101561068d57600080fd5b506001600160a01b03813516906020810135906040013561182c565b61042e600480360360608110156106bf57600080fd5b506001600160a01b038135169060208101359060400135611a68565b610675600480360360208110156106f157600080fd5b50351515611dcf565b610675611ea4565b61042e611fb4565b6106756004803603604081101561072057600080fd5b81359190810190604081016020820135600160201b81111561074157600080fd5b82018360208201111561075357600080fd5b803590602001918460208302840111600160201b8311171561077457600080fd5b509092509050611fd3565b61042e600480360360c081101561079557600080fd5b5080359060208101359060408101359060608101359060808101359060a0013561228a565b61042e600480360360608110156107d057600080fd5b506001600160a01b03813516906020810135906040013561233d565b6104e96004803603604081101561080257600080fd5b506001600160a01b03813516906020013561265a565b61042e6004803603606081101561082e57600080fd5b506001600160a01b038135169060208101359060400135612732565b61042e6004803603602081101561086057600080fd5b50356001600160a01b0316612a99565b61042e6004803603602081101561088657600080fd5b50356001600160a01b0316612aab565b61042e612ac6565b6103e3600480360360a08110156108b457600080fd5b506001600160a01b0381358116916020810135916040820135169060608101359060800135612ad7565b6103e3600480360360a08110156108f457600080fd5b506001600160a01b0381358116916020810135916040820135169060608101359060800135612fd7565b61042e6134bc565b61042e600480360360c081101561093c57600080fd5b5080359060208101359060408101359060608101359060808101359060a001356134d0565b6106756004803603602081101561097757600080fd5b50356001600160a01b0316613580565b6104e9613726565b610675600480360360208110156109a557600080fd5b50356001600160a01b031661372f565b61042e6137fa565b61042e613819565b61042e613826565b61042e600480360360208110156109e357600080fd5b50356001600160a01b0316613836565b610448613892565b61042e6138f3565b61042e6138ff565b61042e600480360360a0811015610a2157600080fd5b508035906020810135906040810135906060810135906080013561390c565b6104e960048036036040811015610a5657600080fd5b506001600160a01b038135169060200135613971565b61067560048036036020811015610a8257600080fd5b50356001600160a01b0316613987565b61067560048036036040811015610aa857600080fd5b81359190810190604081016020820135600160201b811115610ac957600080fd5b820183602082011115610adb57600080fd5b803590602001918460208302840111600160201b83111715610afc57600080fd5b509092509050613acd565b61042e613dd2565b61067560048036036020811015610b2557600080fd5b5035613dd7565b61042e613ebd565b61042e613ec2565b6103e3600480360360c0811015610b5257600080fd5b5080359060208101359060408101359060608101359060808101359060a00135613ec7565b61042e613f58565b61042e613f68565b610b8f613f74565b60408051602080825283518183015283519192839290830191858101910280838360005b83811015610bcb578181015183820152602001610bb3565b505050509050019250505060405180910390f35b61042e613ffa565b610b8f613fff565b61042e614017565b61067560048036036020811015610c0d57600080fd5b50356001600160a01b031661401d565b61042e6142b9565b6104e960048036036040811015610c3b57600080fd5b506001600160a01b0381351690602001356142d8565b61042e60048036036040811015610c6757600080fd5b506001600160a01b0381358116916020013516614359565b61067560048036036060811015610c9557600080fd5b506001600160a01b038135169060208101359060400135614384565b61067560048036036040811015610cc757600080fd5b506001600160a01b0381351690602001356144f3565b61042e614657565b61042e60048036036020811015610cfb57600080fd5b50356001600160a01b0316614667565b61042e60048036036020811015610d2157600080fd5b50356001600160a01b03166146d5565b6103e3600480360360c0811015610d4757600080fd5b5080359060208101359060408101359060608101359060808101359060a00135614731565b6104e96147db565b6000806000610d8389886147eb565b90506000610da2610d9c670de0b6b3a7640000846148fe565b87614960565b90506000610dc188610dbc670de0b6b3a7640000856148fe565b6147eb565b9050610dce818988614a22565b93506000610ddc8d836148fe565b90506000610dea828f6147eb565b90506000610df88287614b1f565b90506000610e06828f614960565b90506000610e148f836148fe565b9050610e2d81610dbc670de0b6b3a764000060006148fe565b9950505050505050505097509795505050505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615610ebb57600080fd5b6005805461ff00191661010017905560095460ff16610f15576040805162461bcd60e51b815260206004820152601160248201527011549497d393d517d19253905312569151607a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b602052604090205460ff16610f72576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b60205260409020600390810154610fa791670de0b6b3a76400005b04600101614960565b831115610fef576040805162461bcd60e51b81526020600482015260116024820152704552525f4d41585f4f55545f524154494f60781b604482015290519081900360640190fd5b6000600b6000866001600160a01b03166001600160a01b031681526020019081526020016000209050600061103982600301548360020154600254600d5489600754600854610d74565b909350905082611082576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b838311156110c6576040805162461bcd60e51b815260206004820152600c60248201526b22a9292fa624a6a4aa2fa4a760a11b604482015290519081900360640190fd5b6110dd6110d78360030154876148fe565b826148fe565b600383015560006110ee8482614960565b604080518881526020810185905281519293506001600160a01b038a16923392600080516020615165833981519152928290030190a36001600160a01b0387166000908152600c60205260409020546111479083614c2d565b6001600160a01b0388166000818152600c60209081526040918290209390935580518581529051919260008051602061518583398151915292918290030190a26111913385614c7a565b6111a361119e85836148fe565b614c88565b6005546111bf906201000090046001600160a01b031682614c94565b6111ca873388614c9e565b5050506005805461ff00191690559392505050565b60038054604080516020601f600260001961010060018816150201909516949094049384018190048102820181019092528281526060939092909183018282801561126b5780601f106112405761010080835404028352916020019161126b565b820191906000526020600020905b81548152906001019060200180831161124e57829003601f168201915b5050505050905090565b3360008181526001602090815260408083206001600160a01b038716808552908352818420869055815186815291519394909390926000805160206151e5833981519152928290030190a35060015b92915050565b6802b5e3af16b188000081565b600554600090610100900460ff16156112ef57600080fd5b6001600160a01b0383166000908152600b602052604090205460ff1661134c576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0382166000908152600b602052604090205460ff166113a9576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b038084166000908152600b602052604080822092851682528120600380840154600280860154928401549084015493946113ed949293929061390c565b95945050505050565b600554600090610100900460ff161561140e57600080fd5b6001600160a01b0383166000908152600b602052604090205460ff1661146b576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0382166000908152600b602052604090205460ff166114c8576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b038084166000908152600b60205260408082209285168252902060038083015460028085015492840154908401546007546113ed9492919061390c565b60025490565b6402540be400670de0b6b3a76400005b0481565b670de0b6b3a764000081565b600080600061154189886147eb565b9050600061155a610d9c670de0b6b3a7640000846148fe565b9050600061157988611574670de0b6b3a7640000856148fe565b614960565b9050611586888288614a22565b935060006115948d83614c2d565b905060006115a2828f6147eb565b905060006115b08287614b1f565b905060006115be828f614960565b90506115ca818f6148fe565b98505050505050505097509795505050505050565b6000336001600160a01b038516148061161b57506001600160a01b03841660009081526001602090815260408083203384529091529020548211155b61162457600080fd5b61162f848484614d69565b336001600160a01b0385161480159061166d57506001600160a01b038416600090815260016020908152604080832033845290915290205460001914155b156116ef576001600160a01b03841660009081526001602090815260408083203384529091529020546116a090836148fe565b6001600160a01b03858116600090815260016020908152604080832033808552908352928190208590558051948552519287169391926000805160206151e58339815191529281900390910190a35b5060019392505050565b6001600160a01b03166000908152600b602052604090205460ff1690565b600554600090610100900460ff161561172f57600080fd5b506006546001600160a01b031690565b60055460ff1690565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156117be57600080fd5b6005805461ff00191661010017905560095460ff16156117dd57600080fd5b6006546001600160a01b031633146117f457600080fd5b6516bcc41e900081101561180757600080fd5b67016345785d8a000081111561181c57600080fd5b6007556005805461ff0019169055565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156118a257600080fd5b6005805461ff001916610100179055600654336001600160a01b03909116146118ca57600080fd5b6001600160a01b0383166000908152600b602052604090205460ff166118ef57600080fd5b60095460ff16156118ff57600080fd5b670de0b6b3a764000081101561191457600080fd5b6802b5e3af16b188000081111561192a57600080fd5b620f424082101561193a57600080fd5b6001600160a01b0383166000908152600b60205260409020600201548082111561199257611973600d5461196e84846148fe565b614c2d565b600d8190556802b5e3af16b1880000101561198d57600080fd5b6119b3565b808210156119b3576119af600d546119aa83856148fe565b6148fe565b600d555b6001600160a01b0384166000908152600b6020526040902060028101839055600301805490849055808411156119fc576119f785336119f287856148fe565b614e28565b611a56565b80841015611a56576000611a1082866148fe565b90506000611a1f826000614960565b9050611a358733611a3085856148fe565b614c9e565b600554611a539088906201000090046001600160a01b031683614c9e565b50505b50506005805461ff0019169055505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615611ae057600080fd5b6005805461ff00191661010017905560095460ff16611b3a576040805162461bcd60e51b815260206004820152601160248201527011549497d393d517d19253905312569151607a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b602052604090205460ff16611b97576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b6020526040902060038101546002808301549054600d54600754611bd1949392919089906134d0565b915082821015611c18576040805162461bcd60e51b815260206004820152600d60248201526c11549497d31253525517d3d555609a1b604482015290519081900360640190fd5b6001600160a01b0385166000908152600b60205260409020600390810154611c4891670de0b6b3a7640000610f9e565b821115611c90576040805162461bcd60e51b81526020600482015260116024820152704552525f4d41585f4f55545f524154494f60781b604482015290519081900360640190fd5b6000611cad82600301548360020154600254600d548960006134d0565b90506000611cbe8285600854614a22565b9050611cd16110d78460030154866148fe565b60038401556000611ce28782614960565b604080518781526020810185905281519293506001600160a01b038b16923392600080516020615165833981519152928290030190a36001600160a01b0388166000908152600c6020526040902054611d3b9083614c2d565b6001600160a01b0389166000818152600c60209081526040918290209390935580518581529051919260008051602061518583398151915292918290030190a2611d853388614c7a565b611d9261119e88836148fe565b600554611dae906201000090046001600160a01b031682614c94565b611db9883387614c9e565b505050506005805461ff00191690559392505050565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615611e4557600080fd5b6005805461ff00191661010017905560095460ff1615611e6457600080fd5b6006546001600160a01b03163314611e7b57600080fd5b60068054911515600160a01b0260ff60a01b199092169190911790556005805461ff0019169055565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615611f1a57600080fd5b6005805461ff001916610100179055600654336001600160a01b0390911614611f4257600080fd5b60095460ff1615611f5257600080fd5b600a5460021115611f6257600080fd5b6009805460ff191660011790556006805460ff60a01b1916600160a01b179055611f9468056bc75e2d63100000614e81565b611fa73368056bc75e2d63100000614c94565b6005805461ff0019169055565b600554600090610100900460ff1615611fcc57600080fd5b5060085490565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561204957600080fd5b6005805461ff00191661010017905560095460ff166120a3576040805162461bcd60e51b815260206004820152601160248201527011549497d393d517d19253905312569151607a1b604482015290519081900360640190fd5b60006120ad61150c565b905060006120bb85836147eb565b905080612101576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b60005b600a54811015612276576000600a828154811061211d57fe5b60009182526020808320909101546001600160a01b0316808352600b9091526040822060030154909250906121528583614960565b905080612198576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b8787858181106121a457fe5b905060200201358111156121ee576040805162461bcd60e51b815260206004820152600c60248201526b22a9292fa624a6a4aa2fa4a760a11b604482015290519081900360640190fd5b6001600160a01b0383166000908152600b60205260409020600301546122149082614c2d565b6001600160a01b0384166000818152600b60209081526040808320600301949094558351858152908101919091528251919233926000805160206151a58339815191529281900390910190a361226b833383614e28565b505050600101612104565b5061228085614e81565b611a563386614c94565b60008061229787866147eb565b905060006122a58786614c2d565b905060006122b382896147eb565b905060006122c9670de0b6b3a7640000856147eb565b905060006122d78383614b1f565b905060006122e5828e614960565b905060006122f3828f6148fe565b9050600061231261230c670de0b6b3a76400008a6148fe565b8b614960565b905061232a82610dbc670de0b6b3a7640000846148fe565b9f9e505050505050505050505050505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156123b557600080fd5b6005805461ff00191661010017905560095460ff1661240f576040805162461bcd60e51b815260206004820152601160248201527011549497d393d517d19253905312569151607a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b602052604090205460ff1661246c576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b602052604090206003015461249e906002670de0b6b3a76400005b04614960565b8311156124e5576040805162461bcd60e51b815260206004820152601060248201526f4552525f4d41585f494e5f524154494f60801b604482015290519081900360640190fd5b6000600b6000866001600160a01b03166001600160a01b031681526020019081526020016000209050600061252f82600301548360020154600254600d5489600754600854611532565b909350905083831015612579576040805162461bcd60e51b815260206004820152600d60248201526c11549497d31253525517d3d555609a1b604482015290519081900360640190fd5b61258a6110d7836003015487614c2d565b6003830155604080518681526020810183905281516001600160a01b0389169233926000805160206151a5833981519152929081900390910190a36001600160a01b0386166000908152600c60205260409020546125e89082614c2d565b6001600160a01b0387166000818152600c60209081526040918290209390935580518481529051919260008051602061518583398151915292918290030190a261263183614e81565b61263b3384614c94565b612646863387614e28565b50506005805461ff00191690559392505050565b3360009081526001602090815260408083206001600160a01b0386168452909152812054808311156126af573360009081526001602090815260408083206001600160a01b03881684529091528120556126de565b6126b981846148fe565b3360009081526001602090815260408083206001600160a01b03891684529091529020555b3360008181526001602090815260408083206001600160a01b0389168085529083529281902054815190815290519293926000805160206151e5833981519152929181900390910190a35060019392505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156127aa57600080fd5b6005805461ff00191661010017905560095460ff16612804576040805162461bcd60e51b815260206004820152601160248201527011549497d393d517d19253905312569151607a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b602052604090205460ff16612861576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b6020526040902060038101546002808301549054600d5460075461289b9493929190899061228a565b9150816128e1576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b82821115612925576040805162461bcd60e51b815260206004820152600c60248201526b22a9292fa624a6a4aa2fa4a760a11b604482015290519081900360640190fd5b6001600160a01b0385166000908152600b6020526040902060030154612955906002670de0b6b3a7640000612498565b82111561299c576040805162461bcd60e51b815260206004820152601060248201526f4552525f4d41585f494e5f524154494f60801b604482015290519081900360640190fd5b60006129b982600301548360020154600254600d5489600061228a565b905060006129ca8483600854614a22565b90506129dd6110d7846003015486614c2d565b6003840155604080518581526020810183905281516001600160a01b038a169233926000805160206151a5833981519152929081900390910190a36001600160a01b0387166000908152600c6020526040902054612a3b9082614c2d565b6001600160a01b0388166000818152600c60209081526040918290209390935580518481529051919260008051602061518583398151915292918290030190a2612a8486614e81565b612a8e3387614c94565b6111ca873386614e28565b600c6020526000908152604090205481565b6001600160a01b031660009081526020819052604090205490565b619c40670de0b6b3a7640000611522565b60408051602080825236908201819052600092839233926001600160e01b03198535169285929081908101848480828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615612b3e57600080fd5b6005805461ff0019166101001790556001600160a01b0387166000908152600b602052604090205460ff16612baa576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0385166000908152600b602052604090205460ff16612c07576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b600654600160a01b900460ff16612c5b576040805162461bcd60e51b81526020600482015260136024820152724552525f535741505f4e4f545f5055424c494360681b604482015290519081900360640190fd5b6001600160a01b038088166000908152600b602052604080822092881682529020600380820154612c9491670de0b6b3a7640000610f9e565b861115612cdc576040805162461bcd60e51b81526020600482015260116024820152704552525f4d41585f4f55545f524154494f60781b604482015290519081900360640190fd5b6000612cfd836003015484600201548460030154856002015460075461390c565b905085811115612d4a576040805162461bcd60e51b81526020600482015260136024820152724552525f4241445f4c494d49545f505249434560681b604482015290519081900360640190fd5b6000612d6c84600301548560020154856003015486600201548c600754614731565b909650905089861115612db5576040805162461bcd60e51b815260206004820152600c60248201526b22a9292fa624a6a4aa2fa4a760a11b604482015290519081900360640190fd5b6000612dc382600854614e8a565b9050612dd66110d7866003015489614c2d565b8560030181905550612dec84600301548a6148fe565b600380860182905586015460028088015490870154600754612e0f94919061390c565b955082861015612e58576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b87861115612e9f576040805162461bcd60e51b815260206004820152600f60248201526e4552525f4c494d49545f505249434560881b604482015290519081900360640190fd5b612ea9878a6147eb565b831115612eef576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b60408051888152602081018b905280820183905290516001600160a01b03808d1692908f169133917f50ef2fc267012b5c84b56835f16ffd5331ac5a151a3760d74908721ba78b0efe919081900360600190a46001600160a01b038c166000908152600c6020526040902054612f659082614c2d565b6001600160a01b038d166000818152600c60209081526040918290209390935580518481529051919260008051602061518583398151915292918290030190a2612fb08c3389614e28565b612fbb8a338b614c9e565b50505050506005805461ff001916905590969095509350505050565b60408051602080825236908201819052600092839233926001600160e01b03198535169285929081908101848480828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561303e57600080fd5b6005805461ff0019166101001790556001600160a01b0387166000908152600b602052604090205460ff166130aa576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0385166000908152600b602052604090205460ff16613107576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b600654600160a01b900460ff1661315b576040805162461bcd60e51b81526020600482015260136024820152724552525f535741505f4e4f545f5055424c494360681b604482015290519081900360640190fd5b6001600160a01b038088166000908152600b6020526040808220928816825290206003820154613195906002670de0b6b3a7640000612498565b8811156131dc576040805162461bcd60e51b815260206004820152601060248201526f4552525f4d41585f494e5f524154494f60801b604482015290519081900360640190fd5b60006131fd836003015484600201548460030154856002015460075461390c565b90508581111561324a576040805162461bcd60e51b81526020600482015260136024820152724552525f4241445f4c494d49545f505249434560681b604482015290519081900360640190fd5b600061326c84600301548560020154856003015486600201548e600754613ec7565b9096509050878610156132b6576040805162461bcd60e51b815260206004820152600d60248201526c11549497d31253525517d3d555609a1b604482015290519081900360640190fd5b60006132c482600854614e8a565b90506132d76110d786600301548d614c2d565b85600301819055506132ed8460030154886148fe565b60038086018290558601546002808801549087015460075461331094919061390c565b955082861015613359576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b878611156133a0576040805162461bcd60e51b815260206004820152600f60248201526e4552525f4c494d49545f505249434560881b604482015290519081900360640190fd5b6133aa8b886147eb565b8311156133f0576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b604080518c81526020810189905280820183905290516001600160a01b03808d1692908f169133917f50ef2fc267012b5c84b56835f16ffd5331ac5a151a3760d74908721ba78b0efe919081900360600190a46001600160a01b038c166000908152600c60205260409020546134669082614c2d565b6001600160a01b038d166000818152600c60209081526040918290209390935580518481529051919260008051602061518583398151915292918290030190a26134b18c338d614e28565b612fbb8a3389614c9e565b64e8d4a51000670de0b6b3a7640000611522565b6000806134dd87866147eb565b905060006134f885611574670de0b6b3a764000060006148fe565b9050600061350688836148fe565b90506000613514828a6147eb565b905060006135338261352e670de0b6b3a7640000886147eb565b614b1f565b90506000613541828e614960565b9050600061354f8e836148fe565b9050600061356861230c670de0b6b3a76400008a6148fe565b905061232a82611574670de0b6b3a7640000846148fe565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156135f657600080fd5b6005805461ff0019166101001790556001600160a01b0381166000908152600b602052604090205460ff1661362a57600080fd5b604080516370a0823160e01b815230600482015290516000916001600160a01b038416916370a0823191602480820192602092909190829003018186803b15801561367457600080fd5b505afa158015613688573d6000803e3d6000fd5b505050506040513d602081101561369e57600080fd5b50516001600160a01b0383166000908152600c60205260409020549091506136c682826148fe565b6001600160a01b0384166000908152600b602052604090206003015411156136ed57600080fd5b6136f782826148fe565b6001600160a01b039093166000908152600b602052604090206003019290925550506005805461ff0019169055565b60095460ff1690565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156137a557600080fd5b6005805461ff001916610100179055600654336001600160a01b03909116146137cd57600080fd5b600680546001600160a01b0319166001600160a01b03929092169190911790556005805461ff0019169055565b600554600090610100900460ff161561381257600080fd5b50600d5490565b68056bc75e2d6310000081565b6005670de0b6b3a7640000611522565b600554600090610100900460ff161561384e57600080fd5b6001600160a01b0382166000908152600b602052604090205460ff1661387357600080fd5b506001600160a01b03166000908152600b602052604090206002015490565b60048054604080516020601f600260001961010060018816150201909516949094049384018190048102820181019092528281526060939092909183018282801561126b5780601f106112405761010080835404028352916020019161126b565b6704a03ce68d21555681565b6542524f4e5a4560d01b90565b60008061391987876147eb565b9050600061392786866147eb565b9050600061393583836147eb565b90506000613957670de0b6b3a7640000610dbc670de0b6b3a7640000896148fe565b90506139638282614960565b9a9950505050505050505050565b600061397e338484614d69565b50600192915050565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156139fd57600080fd5b6005805461010061ff001990911617908190556201000090046001600160a01b03163314613a2a57600080fd5b60005b600a54811015613abe576000600a8281548110613a4657fe5b60009182526020808320909101546001600160a01b03908116808452600c835260408085208054959055805185815290519195508593928816927f261074971f6b45f02124a88c43d5c95e174626f867c87684fb60dbbe35ec2cd292918290030190a3613ab4828583614c9e565b5050600101613a2d565b50506005805461ff0019169055565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615613b4357600080fd5b6005805461ff00191661010017905560095460ff16613b9d576040805162461bcd60e51b815260206004820152601160248201527011549497d393d517d19253905312569151607a1b604482015290519081900360640190fd5b6000613ba761150c565b90506000613bb6856000614960565b90506000613bc486836148fe565b90506000613bd282856147eb565b905080613c18576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b613c223388614c7a565b600554613c3e906201000090046001600160a01b031684614c94565b613c4782614c88565b60005b600a54811015613dbd576000600a8281548110613c6357fe5b60009182526020808320909101546001600160a01b0316808352600b909152604082206003015490925090613c988583614960565b905080613cde576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b898985818110613cea57fe5b90506020020135811015613d35576040805162461bcd60e51b815260206004820152600d60248201526c11549497d31253525517d3d555609a1b604482015290519081900360640190fd5b6001600160a01b0383166000908152600b6020526040902060030154613d5b90826148fe565b6001600160a01b0384166000818152600b60209081526040808320600301949094558351858152908101919091528251919233926000805160206151658339815191529281900390910190a3613db2833383614c9e565b505050600101613c4a565b50506005805461ff0019169055505050505050565b600881565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615613e4d57600080fd5b6005805461ff00191661010017905560095460ff1615613e6c57600080fd5b6006546001600160a01b03163314613e8357600080fd5b670de0b6b3a7640000811115613e9857600080fd5b6702c68af0bb140000811015613ead57600080fd5b6008556005805461ff0019169055565b600281565b600181565b6000806000613ed688876147eb565b90506000613eec670de0b6b3a7640000866148fe565b9050613ef88682614960565b90506000613f0a8b610dbc8d85614c2d565b90506000613f188285614b1f565b90506000613f2e670de0b6b3a7640000836148fe565b9050613f3a8b82614960565b9650613f4689856148fe565b95505050505050965096945050505050565b600a670de0b6b3a7640000611522565b671bc16d674ec7ffff81565b600554606090610100900460ff1615613f8c57600080fd5b60095460ff16613f9b57600080fd5b600a80548060200260200160405190810160405280929190818152602001828054801561126b57602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311613fd3575050505050905090565b600081565b600554606090610100900460ff1615613f9b57600080fd5b600a5490565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561409357600080fd5b6005805461ff001916610100179055600654336001600160a01b03909116146140bb57600080fd5b6001600160a01b0381166000908152600b602052604090205460ff166140e057600080fd5b60095460ff16156140f057600080fd5b6001600160a01b0381166000908152600b6020526040812060030154906141178282614960565b600d546001600160a01b0385166000908152600b6020526040902060020154919250614142916148fe565b600d556001600160a01b0383166000908152600b6020526040902060010154600a8054600019810191908290811061417657fe5b600091825260209091200154600a80546001600160a01b03909216918490811061419c57fe5b9060005260206000200160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555081600b6000600a85815481106141dc57fe5b60009182526020808320909101546001600160a01b03168352820192909252604001902060010155600a80548061420f57fe5b60008281526020808220600019908401810180546001600160a01b031916905590920190925560408051608081018252838152808301848152818301858152606083018681526001600160a01b038c168752600b909552929094209051815460ff1916901515178155925160018401555160028301555160039091015561429b8533611a3087876148fe565b600554611a569086906201000090046001600160a01b031685614c9e565b600554600090610100900460ff16156142d157600080fd5b5060075490565b3360009081526001602090815260408083206001600160a01b03861684529091528120546143069083614c2d565b3360008181526001602090815260408083206001600160a01b0389168085529083529281902085905580519485525191936000805160206151e5833981519152929081900390910190a350600192915050565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a26006546001600160a01b031633146143fc57600080fd5b6001600160a01b0383166000908152600b602052604090205460ff161561442257600080fd5b60095460ff161561443257600080fd5b600a5460081161444157600080fd5b604080516080810182526001808252600a805460208085019182526000858701818152606087018281526001600160a01b038c16808452600b9094529782209651875460ff1916901515178755925186860155915160028601559451600390940193909355805491820181559091527fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a80180546001600160a01b03191690911790556144ee83838361182c565b505050565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561456957600080fd5b6005805461ff001916610100179055600654336001600160a01b039091161461459157600080fd5b6001600160a01b0382166000908152600b602052604090205460ff16156145b757600080fd5b604080516370a0823160e01b815230600482015290516000916001600160a01b038516916370a0823191602480820192602092909190829003018186803b15801561460157600080fd5b505afa158015614615573d6000803e3d6000fd5b505050506040513d602081101561462b57600080fd5b505190508082111561463c57600080fd5b614647833384614c9e565b50506005805461ff001916905550565b6002670de0b6b3a7640000611522565b600554600090610100900460ff161561467f57600080fd5b6001600160a01b0382166000908152600b602052604090205460ff166146a457600080fd5b6001600160a01b0382166000908152600b6020526040902060020154600d546146ce9082906147eb565b9392505050565b600554600090610100900460ff16156146ed57600080fd5b6001600160a01b0382166000908152600b602052604090205460ff1661471257600080fd5b506001600160a01b03166000908152600b602052604090206003015490565b600080600061474086896147eb565b9050600061474e88876148fe565b9050600061475c89836147eb565b9050600061476a8285614b1f565b905061477e81670de0b6b3a76400006148fe565b905061478a8c82614960565b905061479e670de0b6b3a7640000886148fe565b95506147aa81876147eb565b95506147be81670de0b6b3a76400006147eb565b94506147ca86866148fe565b945050505050965096945050505050565b600654600160a01b900460ff1690565b60008161482e576040805162461bcd60e51b815260206004820152600c60248201526b4552525f4449565f5a45524f60a01b604482015290519081900360640190fd5b670de0b6b3a764000083028315806148565750670de0b6b3a764000084828161485357fe5b04145b61489a576040805162461bcd60e51b815260206004820152601060248201526f11549497d1125597d25395115493905360821b604482015290519081900360640190fd5b600283048101818110156148e8576040805162461bcd60e51b815260206004820152601060248201526f11549497d1125597d25395115493905360821b604482015290519081900360640190fd5b60008482816148f357fe5b049695505050505050565b600080600061490d8585614ee9565b915091508015614958576040805162461bcd60e51b81526020600482015260116024820152704552525f5355425f554e444552464c4f5760781b604482015290519081900360640190fd5b509392505050565b600082820283158061497a57508284828161497757fe5b04145b6149be576040805162461bcd60e51b815260206004820152601060248201526f4552525f4d554c5f4f564552464c4f5760801b604482015290519081900360640190fd5b6706f05b59d3b20000810181811015614a11576040805162461bcd60e51b815260206004820152601060248201526f4552525f4d554c5f4f564552464c4f5760801b604482015290519081900360640190fd5b6000670de0b6b3a7640000826148f3565b600082841015614a6b576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b670de0b6b3a7640000821115614abe576040805162461bcd60e51b81526020600482015260136024820152724552525f494e56414c49445f5245534552564560681b604482015290519081900360640190fd5b6000614aca85856148fe565b9050614ad68184614960565b915081811015614958576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b60006001831015614b6f576040805162461bcd60e51b81526020600482015260156024820152744552525f42504f575f424153455f544f4f5f4c4f5760581b604482015290519081900360640190fd5b671bc16d674ec7ffff831115614bc5576040805162461bcd60e51b815260206004820152601660248201527508aa4a4be84a09eaebe8482a68abea89e9ebe90928e960531b604482015290519081900360640190fd5b6000614bd083614f0e565b90506000614bde84836148fe565b90506000614bf486614bef85614f29565b614f37565b905081614c055792506112c4915050565b6000614c1687846305f5e100614f8e565b9050614c228282614960565b979650505050505050565b6000828201838110156146ce576040805162461bcd60e51b815260206004820152601060248201526f4552525f4144445f4f564552464c4f5760801b604482015290519081900360640190fd5b614c84828261506c565b5050565b614c9181615077565b50565b614c8482826150f6565b6040805163a9059cbb60e01b81526001600160a01b03848116600483015260248201849052915160009286169163a9059cbb91604480830192602092919082900301818787803b158015614cf157600080fd5b505af1158015614d05573d6000803e3d6000fd5b505050506040513d6020811015614d1b57600080fd5b5051905080614d63576040805162461bcd60e51b815260206004820152600f60248201526e4552525f45524332305f46414c534560881b604482015290519081900360640190fd5b50505050565b6001600160a01b038316600090815260208190526040902054811115614d8e57600080fd5b6001600160a01b038316600090815260208190526040902054614db190826148fe565b6001600160a01b038085166000908152602081905260408082209390935590841681522054614de09082614c2d565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716926000805160206151c583398151915292918290030190a3505050565b604080516323b872dd60e01b81526001600160a01b0384811660048301523060248301526044820184905291516000928616916323b872dd91606480830192602092919082900301818787803b158015614cf157600080fd5b614c9181615101565b6000670de0b6b3a7640000821115614edf576040805162461bcd60e51b81526020600482015260136024820152724552525f494e56414c49445f5245534552564560681b604482015290519081900360640190fd5b6146ce8383614960565b600080828410614eff5750508082036000614f07565b505081810360015b9250929050565b6000670de0b6b3a7640000614f2283614f29565b0292915050565b670de0b6b3a7640000900490565b60008060028306614f5057670de0b6b3a7640000614f52565b835b90506002830492505b82156146ce57614f6b8485614960565b93506002830615614f8357614f808185614960565b90505b600283049250614f5b565b6000828180614fa587670de0b6b3a7640000614ee9565b9092509050670de0b6b3a764000080600060015b88841061505d576000670de0b6b3a764000082029050600080614fed8a614fe885670de0b6b3a76400006148fe565b614ee9565b91509150614fff87611574848c614960565b965061500b87846147eb565b96508661501a5750505061505d565b8715615024579315935b801561502e579315935b84156150455761503e86886148fe565b9550615052565b61504f8688614c2d565b95505b505050600101614fb9565b50909998505050505050505050565b614c84823083614d69565b3060009081526020819052604090205481111561509357600080fd5b306000908152602081905260409020546150ad90826148fe565b306000908152602081905260409020556002546150ca90826148fe565b60025560408051828152905160009130916000805160206151c58339815191529181900360200190a350565b614c84308383614d69565b3060009081526020819052604090205461511b9082614c2d565b306000908152602081905260409020556002546151389082614c2d565b60025560408051828152905130916000916000805160206151c58339815191529181900360200190a35056fe9d9058fd2f25ccc389fec7720abef0ca83472f5abfafd5f10d37f51e6a0493f39448856d254ce9f0a13e70882297125673303bfaa163fc49ad146aa8bb55660715a8ca63e37b2cff1677df2b6b82d36fcf8a524228bd7a4b4d02d107c28c1e8addf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925a265627a7a72315820ab2acacc8ab6ffe5c190924b796adaf99750bf51341fd0616f0bf5c7ced385cb64736f6c634300050c0032a265627a7a72315820811a9ec1b7adf9d374b4d393f8773074245c0d247ad2544686bac9f04079f2fb64736f6c634300050c0032
{"success": true, "error": null, "results": {"detectors": [{"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}]}
34
0x0e110ad9d826d30073dc6a5d35efb857b9925b54
pragma solidity 0.5.17; 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; } 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 constant internal MM_OODS_COMMITMENT = 0x7; uint256 constant internal MM_N_UNIQUE_QUERIES = 0x8; uint256 constant internal MM_CHANNEL = 0x9; // uint256[3] uint256 constant internal MM_MERKLE_QUEUE = 0xc; // uint256[96] uint256 constant internal MM_FRI_QUEUE = 0x6c; // uint256[144] uint256 constant internal MM_FRI_QUERIES_DELIMITER = 0xfc; uint256 constant internal MM_FRI_CTX = 0xfd; // uint256[40] uint256 constant internal MM_FRI_STEPS_PTR = 0x125; uint256 constant internal MM_FRI_EVAL_POINTS = 0x126; // uint256[10] uint256 constant internal MM_FRI_COMMITMENTS = 0x130; // uint256[10] uint256 constant internal MM_FRI_LAST_LAYER_DEG_BOUND = 0x13a; uint256 constant internal MM_FRI_LAST_LAYER_PTR = 0x13b; uint256 constant internal MM_CONSTRAINT_POLY_ARGS_START = 0x13c; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS0_A = 0x13c; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS1_A = 0x13d; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS2_A = 0x13e; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS3_A = 0x13f; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS4_A = 0x140; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS5_A = 0x141; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS6_A = 0x142; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS7_A = 0x143; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS8_A = 0x144; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS9_A = 0x145; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS0_B = 0x146; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS1_B = 0x147; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS2_B = 0x148; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS3_B = 0x149; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS4_B = 0x14a; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS5_B = 0x14b; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS6_B = 0x14c; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS7_B = 0x14d; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS8_B = 0x14e; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS9_B = 0x14f; uint256 constant internal MM_MAT00 = 0x150; uint256 constant internal MM_MAT01 = 0x151; uint256 constant internal MM_TRACE_LENGTH = 0x152; uint256 constant internal MM_MAT10 = 0x153; uint256 constant internal MM_MAT11 = 0x154; uint256 constant internal MM_INPUT_VALUE_A = 0x155; uint256 constant internal MM_OUTPUT_VALUE_A = 0x156; uint256 constant internal MM_INPUT_VALUE_B = 0x157; uint256 constant internal MM_OUTPUT_VALUE_B = 0x158; uint256 constant internal MM_TRACE_GENERATOR = 0x159; uint256 constant internal MM_OODS_POINT = 0x15a; uint256 constant internal MM_COEFFICIENTS = 0x15b; // uint256[48] uint256 constant internal MM_OODS_VALUES = 0x18b; // uint256[22] uint256 constant internal MM_CONSTRAINT_POLY_ARGS_END = 0x1a1; uint256 constant internal MM_COMPOSITION_OODS_VALUES = 0x1a1; // uint256[2] uint256 constant internal MM_OODS_EVAL_POINTS = 0x1a3; // uint256[48] uint256 constant internal MM_OODS_COEFFICIENTS = 0x1d3; // uint256[24] uint256 constant internal MM_TRACE_QUERY_RESPONSES = 0x1eb; // uint256[960] uint256 constant internal MM_COMPOSITION_QUERY_RESPONSES = 0x5ab; // uint256[96] uint256 constant internal MM_CONTEXT_SIZE = 0x60b; } 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 MimcConstraintPoly { // The Memory map during the execution of this contract is as follows: // [0x0, 0x20) - periodic_column/consts0_a. // [0x20, 0x40) - periodic_column/consts1_a. // [0x40, 0x60) - periodic_column/consts2_a. // [0x60, 0x80) - periodic_column/consts3_a. // [0x80, 0xa0) - periodic_column/consts4_a. // [0xa0, 0xc0) - periodic_column/consts5_a. // [0xc0, 0xe0) - periodic_column/consts6_a. // [0xe0, 0x100) - periodic_column/consts7_a. // [0x100, 0x120) - periodic_column/consts8_a. // [0x120, 0x140) - periodic_column/consts9_a. // [0x140, 0x160) - periodic_column/consts0_b. // [0x160, 0x180) - periodic_column/consts1_b. // [0x180, 0x1a0) - periodic_column/consts2_b. // [0x1a0, 0x1c0) - periodic_column/consts3_b. // [0x1c0, 0x1e0) - periodic_column/consts4_b. // [0x1e0, 0x200) - periodic_column/consts5_b. // [0x200, 0x220) - periodic_column/consts6_b. // [0x220, 0x240) - periodic_column/consts7_b. // [0x240, 0x260) - periodic_column/consts8_b. // [0x260, 0x280) - periodic_column/consts9_b. // [0x280, 0x2a0) - mat00. // [0x2a0, 0x2c0) - mat01. // [0x2c0, 0x2e0) - trace_length. // [0x2e0, 0x300) - mat10. // [0x300, 0x320) - mat11. // [0x320, 0x340) - input_value_a. // [0x340, 0x360) - output_value_a. // [0x360, 0x380) - input_value_b. // [0x380, 0x3a0) - output_value_b. // [0x3a0, 0x3c0) - trace_generator. // [0x3c0, 0x3e0) - oods_point. // [0x3e0, 0x9e0) - coefficients. // [0x9e0, 0xca0) - oods_values. // ----------------------- end of input data - ------------------------- // [0xca0, 0xcc0) - composition_degree_bound. // [0xcc0, 0xce0) - intermediate_value/after_lin_transform0_a_0. // [0xce0, 0xd00) - intermediate_value/after_lin_transform0_b_0. // [0xd00, 0xd20) - intermediate_value/after_lin_transform1_a_0. // [0xd20, 0xd40) - intermediate_value/after_lin_transform1_b_0. // [0xd40, 0xd60) - intermediate_value/after_lin_transform2_a_0. // [0xd60, 0xd80) - intermediate_value/after_lin_transform2_b_0. // [0xd80, 0xda0) - intermediate_value/after_lin_transform3_a_0. // [0xda0, 0xdc0) - intermediate_value/after_lin_transform3_b_0. // [0xdc0, 0xde0) - intermediate_value/after_lin_transform4_a_0. // [0xde0, 0xe00) - intermediate_value/after_lin_transform4_b_0. // [0xe00, 0xe20) - intermediate_value/after_lin_transform5_a_0. // [0xe20, 0xe40) - intermediate_value/after_lin_transform5_b_0. // [0xe40, 0xe60) - intermediate_value/after_lin_transform6_a_0. // [0xe60, 0xe80) - intermediate_value/after_lin_transform6_b_0. // [0xe80, 0xea0) - intermediate_value/after_lin_transform7_a_0. // [0xea0, 0xec0) - intermediate_value/after_lin_transform7_b_0. // [0xec0, 0xee0) - intermediate_value/after_lin_transform8_a_0. // [0xee0, 0xf00) - intermediate_value/after_lin_transform8_b_0. // [0xf00, 0xf20) - intermediate_value/after_lin_transform9_a_0. // [0xf20, 0xf40) - intermediate_value/after_lin_transform9_b_0. // [0xf40, 0xf80) - expmods. // [0xf80, 0xfe0) - denominator_invs. // [0xfe0, 0x1040) - denominators. // [0x1040, 0x1060) - numerators. // [0x1060, 0x10c0) - adjustments. // [0x10c0, 0x1180) - expmod_context. function() external { uint256 res; assembly { let PRIME := 0x30000003000000010000000000000001 // Copy input from calldata to memory. calldatacopy(0x0, 0x0, /*Input data size*/ 0xca0) let point := /*oods_point*/ mload(0x3c0) // Initialize composition_degree_bound to 2 * trace_length. mstore(0xca0, mul(2, /*trace_length*/ mload(0x2c0))) function expmod(base, exponent, modulus) -> res { let p := /*expmod_context*/ 0x10c0 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(0xf40, expmod(point, /*trace_length*/ mload(0x2c0), PRIME)) // expmods[1] = trace_generator^(trace_length - 1). mstore(0xf60, expmod(/*trace_generator*/ mload(0x3a0), sub(/*trace_length*/ mload(0x2c0), 1), PRIME)) } { // Prepare denominators for batch inverse. // Denominator for constraints: 'step0_a', 'step0_b', 'step1_a', 'step1_b', 'step2_a', 'step2_b', 'step3_a', 'step3_b', 'step4_a', 'step4_b', 'step5_a', 'step5_b', 'step6_a', 'step6_b', 'step7_a', 'step7_b', 'step8_a', 'step8_b', 'step9_a', 'step9_b'. // denominators[0] = point^trace_length - 1. mstore(0xfe0, addmod(/*point^trace_length*/ mload(0xf40), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'input_a', 'input_b'. // denominators[1] = point - 1. mstore(0x1000, addmod(point, sub(PRIME, 1), PRIME)) // Denominator for constraints: 'output_a', 'output_b'. // denominators[2] = point - trace_generator^(trace_length - 1). mstore(0x1020, addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0xf60)), 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 := 0x60 let prod := 1 let partialProductEndPtr := 0xfe0 for { let partialProductPtr := 0xf80 } lt(partialProductPtr, partialProductEndPtr) { partialProductPtr := add(partialProductPtr, 0x20) } { mstore(partialProductPtr, prod) // prod *= d_{i}. prod := mulmod(prod, mload(add(partialProductPtr, productsToValuesOffset)), PRIME) } let firstPartialProductPtr := 0xf80 // 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 := 0xfe0 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 'step9_a', 'step9_b'. // numerators[0] = point - trace_generator^(trace_length - 1). mstore(0x1040, addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0xf60)), PRIME)) // Adjustment polynomial for constraints 'step0_a', 'step0_b', 'step1_a', 'step1_b', 'step2_a', 'step2_b', 'step3_a', 'step3_b', 'step4_a', 'step4_b', 'step5_a', 'step5_b', 'step6_a', 'step6_b', 'step7_a', 'step7_b', 'step8_a', 'step8_b'. // adjustments[0] = point^degreeAdjustment(composition_degree_bound, 3 * (trace_length - 1), 0, trace_length). mstore(0x1060, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0xca0), mul(3, sub(/*trace_length*/ mload(0x2c0), 1)), 0, /*trace_length*/ mload(0x2c0)), PRIME)) // Adjustment polynomial for constraints 'step9_a', 'step9_b'. // adjustments[1] = point^degreeAdjustment(composition_degree_bound, 3 * (trace_length - 1), 1, trace_length). mstore(0x1080, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0xca0), mul(3, sub(/*trace_length*/ mload(0x2c0), 1)), 1, /*trace_length*/ mload(0x2c0)), PRIME)) // Adjustment polynomial for constraints 'input_a', 'output_a', 'input_b', 'output_b'. // adjustments[2] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, 1). mstore(0x10a0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0xca0), sub(/*trace_length*/ mload(0x2c0), 1), 0, 1), PRIME)) } { // Compute the result of the composition polynomial. { // after_lin_transform0_a_0 = mat00 * (column0_row0 - consts0_a) + mat01 * (column10_row0 - consts0_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column0_row0*/ mload(0x9e0), sub(PRIME, /*periodic_column/consts0_a*/ mload(0x0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column10_row0*/ mload(0xb40), sub(PRIME, /*periodic_column/consts0_b*/ mload(0x140)), PRIME), PRIME), PRIME) mstore(0xcc0, val) } { // after_lin_transform0_b_0 = mat10 * (column0_row0 - consts0_a) + mat11 * (column10_row0 - consts0_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column0_row0*/ mload(0x9e0), sub(PRIME, /*periodic_column/consts0_a*/ mload(0x0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column10_row0*/ mload(0xb40), sub(PRIME, /*periodic_column/consts0_b*/ mload(0x140)), PRIME), PRIME), PRIME) mstore(0xce0, val) } { // after_lin_transform1_a_0 = mat00 * (column1_row0 - consts1_a) + mat01 * (column11_row0 - consts1_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column1_row0*/ mload(0xa20), sub(PRIME, /*periodic_column/consts1_a*/ mload(0x20)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column11_row0*/ mload(0xb80), sub(PRIME, /*periodic_column/consts1_b*/ mload(0x160)), PRIME), PRIME), PRIME) mstore(0xd00, val) } { // after_lin_transform1_b_0 = mat10 * (column1_row0 - consts1_a) + mat11 * (column11_row0 - consts1_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column1_row0*/ mload(0xa20), sub(PRIME, /*periodic_column/consts1_a*/ mload(0x20)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column11_row0*/ mload(0xb80), sub(PRIME, /*periodic_column/consts1_b*/ mload(0x160)), PRIME), PRIME), PRIME) mstore(0xd20, val) } { // after_lin_transform2_a_0 = mat00 * (column2_row0 - consts2_a) + mat01 * (column12_row0 - consts2_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column2_row0*/ mload(0xa40), sub(PRIME, /*periodic_column/consts2_a*/ mload(0x40)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column12_row0*/ mload(0xba0), sub(PRIME, /*periodic_column/consts2_b*/ mload(0x180)), PRIME), PRIME), PRIME) mstore(0xd40, val) } { // after_lin_transform2_b_0 = mat10 * (column2_row0 - consts2_a) + mat11 * (column12_row0 - consts2_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column2_row0*/ mload(0xa40), sub(PRIME, /*periodic_column/consts2_a*/ mload(0x40)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column12_row0*/ mload(0xba0), sub(PRIME, /*periodic_column/consts2_b*/ mload(0x180)), PRIME), PRIME), PRIME) mstore(0xd60, val) } { // after_lin_transform3_a_0 = mat00 * (column3_row0 - consts3_a) + mat01 * (column13_row0 - consts3_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column3_row0*/ mload(0xa60), sub(PRIME, /*periodic_column/consts3_a*/ mload(0x60)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column13_row0*/ mload(0xbc0), sub(PRIME, /*periodic_column/consts3_b*/ mload(0x1a0)), PRIME), PRIME), PRIME) mstore(0xd80, val) } { // after_lin_transform3_b_0 = mat10 * (column3_row0 - consts3_a) + mat11 * (column13_row0 - consts3_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column3_row0*/ mload(0xa60), sub(PRIME, /*periodic_column/consts3_a*/ mload(0x60)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column13_row0*/ mload(0xbc0), sub(PRIME, /*periodic_column/consts3_b*/ mload(0x1a0)), PRIME), PRIME), PRIME) mstore(0xda0, val) } { // after_lin_transform4_a_0 = mat00 * (column4_row0 - consts4_a) + mat01 * (column14_row0 - consts4_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column4_row0*/ mload(0xa80), sub(PRIME, /*periodic_column/consts4_a*/ mload(0x80)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column14_row0*/ mload(0xbe0), sub(PRIME, /*periodic_column/consts4_b*/ mload(0x1c0)), PRIME), PRIME), PRIME) mstore(0xdc0, val) } { // after_lin_transform4_b_0 = mat10 * (column4_row0 - consts4_a) + mat11 * (column14_row0 - consts4_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column4_row0*/ mload(0xa80), sub(PRIME, /*periodic_column/consts4_a*/ mload(0x80)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column14_row0*/ mload(0xbe0), sub(PRIME, /*periodic_column/consts4_b*/ mload(0x1c0)), PRIME), PRIME), PRIME) mstore(0xde0, val) } { // after_lin_transform5_a_0 = mat00 * (column5_row0 - consts5_a) + mat01 * (column15_row0 - consts5_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column5_row0*/ mload(0xaa0), sub(PRIME, /*periodic_column/consts5_a*/ mload(0xa0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column15_row0*/ mload(0xc00), sub(PRIME, /*periodic_column/consts5_b*/ mload(0x1e0)), PRIME), PRIME), PRIME) mstore(0xe00, val) } { // after_lin_transform5_b_0 = mat10 * (column5_row0 - consts5_a) + mat11 * (column15_row0 - consts5_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column5_row0*/ mload(0xaa0), sub(PRIME, /*periodic_column/consts5_a*/ mload(0xa0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column15_row0*/ mload(0xc00), sub(PRIME, /*periodic_column/consts5_b*/ mload(0x1e0)), PRIME), PRIME), PRIME) mstore(0xe20, val) } { // after_lin_transform6_a_0 = mat00 * (column6_row0 - consts6_a) + mat01 * (column16_row0 - consts6_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column6_row0*/ mload(0xac0), sub(PRIME, /*periodic_column/consts6_a*/ mload(0xc0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column16_row0*/ mload(0xc20), sub(PRIME, /*periodic_column/consts6_b*/ mload(0x200)), PRIME), PRIME), PRIME) mstore(0xe40, val) } { // after_lin_transform6_b_0 = mat10 * (column6_row0 - consts6_a) + mat11 * (column16_row0 - consts6_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column6_row0*/ mload(0xac0), sub(PRIME, /*periodic_column/consts6_a*/ mload(0xc0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column16_row0*/ mload(0xc20), sub(PRIME, /*periodic_column/consts6_b*/ mload(0x200)), PRIME), PRIME), PRIME) mstore(0xe60, val) } { // after_lin_transform7_a_0 = mat00 * (column7_row0 - consts7_a) + mat01 * (column17_row0 - consts7_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column7_row0*/ mload(0xae0), sub(PRIME, /*periodic_column/consts7_a*/ mload(0xe0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column17_row0*/ mload(0xc40), sub(PRIME, /*periodic_column/consts7_b*/ mload(0x220)), PRIME), PRIME), PRIME) mstore(0xe80, val) } { // after_lin_transform7_b_0 = mat10 * (column7_row0 - consts7_a) + mat11 * (column17_row0 - consts7_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column7_row0*/ mload(0xae0), sub(PRIME, /*periodic_column/consts7_a*/ mload(0xe0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column17_row0*/ mload(0xc40), sub(PRIME, /*periodic_column/consts7_b*/ mload(0x220)), PRIME), PRIME), PRIME) mstore(0xea0, val) } { // after_lin_transform8_a_0 = mat00 * (column8_row0 - consts8_a) + mat01 * (column18_row0 - consts8_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column8_row0*/ mload(0xb00), sub(PRIME, /*periodic_column/consts8_a*/ mload(0x100)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column18_row0*/ mload(0xc60), sub(PRIME, /*periodic_column/consts8_b*/ mload(0x240)), PRIME), PRIME), PRIME) mstore(0xec0, val) } { // after_lin_transform8_b_0 = mat10 * (column8_row0 - consts8_a) + mat11 * (column18_row0 - consts8_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column8_row0*/ mload(0xb00), sub(PRIME, /*periodic_column/consts8_a*/ mload(0x100)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column18_row0*/ mload(0xc60), sub(PRIME, /*periodic_column/consts8_b*/ mload(0x240)), PRIME), PRIME), PRIME) mstore(0xee0, val) } { // after_lin_transform9_a_0 = mat00 * (column9_row0 - consts9_a) + mat01 * (column19_row0 - consts9_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column9_row0*/ mload(0xb20), sub(PRIME, /*periodic_column/consts9_a*/ mload(0x120)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column19_row0*/ mload(0xc80), sub(PRIME, /*periodic_column/consts9_b*/ mload(0x260)), PRIME), PRIME), PRIME) mstore(0xf00, val) } { // after_lin_transform9_b_0 = mat10 * (column9_row0 - consts9_a) + mat11 * (column19_row0 - consts9_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column9_row0*/ mload(0xb20), sub(PRIME, /*periodic_column/consts9_a*/ mload(0x120)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column19_row0*/ mload(0xc80), sub(PRIME, /*periodic_column/consts9_b*/ mload(0x260)), PRIME), PRIME), PRIME) mstore(0xf20, val) } { // Constraint expression for step0_a: column1_row0 - after_lin_transform0_a_0 * after_lin_transform0_a_0 * after_lin_transform0_a_0. let val := addmod( /*column1_row0*/ mload(0xa20), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform0_a_0*/ mload(0xcc0), /*intermediate_value/after_lin_transform0_a_0*/ mload(0xcc0), PRIME), /*intermediate_value/after_lin_transform0_a_0*/ mload(0xcc0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[0] + coefficients[1] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[0]*/ mload(0x3e0), mulmod(/*coefficients[1]*/ mload(0x400), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step0_b: column11_row0 - after_lin_transform0_b_0 * after_lin_transform0_b_0 * after_lin_transform0_b_0. let val := addmod( /*column11_row0*/ mload(0xb80), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform0_b_0*/ mload(0xce0), /*intermediate_value/after_lin_transform0_b_0*/ mload(0xce0), PRIME), /*intermediate_value/after_lin_transform0_b_0*/ mload(0xce0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[2] + coefficients[3] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[2]*/ mload(0x420), mulmod(/*coefficients[3]*/ mload(0x440), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step1_a: column2_row0 - after_lin_transform1_a_0 * after_lin_transform1_a_0 * after_lin_transform1_a_0. let val := addmod( /*column2_row0*/ mload(0xa40), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform1_a_0*/ mload(0xd00), /*intermediate_value/after_lin_transform1_a_0*/ mload(0xd00), PRIME), /*intermediate_value/after_lin_transform1_a_0*/ mload(0xd00), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[4] + coefficients[5] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[4]*/ mload(0x460), mulmod(/*coefficients[5]*/ mload(0x480), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step1_b: column12_row0 - after_lin_transform1_b_0 * after_lin_transform1_b_0 * after_lin_transform1_b_0. let val := addmod( /*column12_row0*/ mload(0xba0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform1_b_0*/ mload(0xd20), /*intermediate_value/after_lin_transform1_b_0*/ mload(0xd20), PRIME), /*intermediate_value/after_lin_transform1_b_0*/ mload(0xd20), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[6] + coefficients[7] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[6]*/ mload(0x4a0), mulmod(/*coefficients[7]*/ mload(0x4c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step2_a: column3_row0 - after_lin_transform2_a_0 * after_lin_transform2_a_0 * after_lin_transform2_a_0. let val := addmod( /*column3_row0*/ mload(0xa60), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform2_a_0*/ mload(0xd40), /*intermediate_value/after_lin_transform2_a_0*/ mload(0xd40), PRIME), /*intermediate_value/after_lin_transform2_a_0*/ mload(0xd40), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[8] + coefficients[9] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[8]*/ mload(0x4e0), mulmod(/*coefficients[9]*/ mload(0x500), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step2_b: column13_row0 - after_lin_transform2_b_0 * after_lin_transform2_b_0 * after_lin_transform2_b_0. let val := addmod( /*column13_row0*/ mload(0xbc0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform2_b_0*/ mload(0xd60), /*intermediate_value/after_lin_transform2_b_0*/ mload(0xd60), PRIME), /*intermediate_value/after_lin_transform2_b_0*/ mload(0xd60), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[10] + coefficients[11] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[10]*/ mload(0x520), mulmod(/*coefficients[11]*/ mload(0x540), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step3_a: column4_row0 - after_lin_transform3_a_0 * after_lin_transform3_a_0 * after_lin_transform3_a_0. let val := addmod( /*column4_row0*/ mload(0xa80), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform3_a_0*/ mload(0xd80), /*intermediate_value/after_lin_transform3_a_0*/ mload(0xd80), PRIME), /*intermediate_value/after_lin_transform3_a_0*/ mload(0xd80), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[12] + coefficients[13] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[12]*/ mload(0x560), mulmod(/*coefficients[13]*/ mload(0x580), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step3_b: column14_row0 - after_lin_transform3_b_0 * after_lin_transform3_b_0 * after_lin_transform3_b_0. let val := addmod( /*column14_row0*/ mload(0xbe0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform3_b_0*/ mload(0xda0), /*intermediate_value/after_lin_transform3_b_0*/ mload(0xda0), PRIME), /*intermediate_value/after_lin_transform3_b_0*/ mload(0xda0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[14] + coefficients[15] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[14]*/ mload(0x5a0), mulmod(/*coefficients[15]*/ mload(0x5c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step4_a: column5_row0 - after_lin_transform4_a_0 * after_lin_transform4_a_0 * after_lin_transform4_a_0. let val := addmod( /*column5_row0*/ mload(0xaa0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform4_a_0*/ mload(0xdc0), /*intermediate_value/after_lin_transform4_a_0*/ mload(0xdc0), PRIME), /*intermediate_value/after_lin_transform4_a_0*/ mload(0xdc0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[16] + coefficients[17] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[16]*/ mload(0x5e0), mulmod(/*coefficients[17]*/ mload(0x600), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step4_b: column15_row0 - after_lin_transform4_b_0 * after_lin_transform4_b_0 * after_lin_transform4_b_0. let val := addmod( /*column15_row0*/ mload(0xc00), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform4_b_0*/ mload(0xde0), /*intermediate_value/after_lin_transform4_b_0*/ mload(0xde0), PRIME), /*intermediate_value/after_lin_transform4_b_0*/ mload(0xde0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[18] + coefficients[19] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[18]*/ mload(0x620), mulmod(/*coefficients[19]*/ mload(0x640), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step5_a: column6_row0 - after_lin_transform5_a_0 * after_lin_transform5_a_0 * after_lin_transform5_a_0. let val := addmod( /*column6_row0*/ mload(0xac0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform5_a_0*/ mload(0xe00), /*intermediate_value/after_lin_transform5_a_0*/ mload(0xe00), PRIME), /*intermediate_value/after_lin_transform5_a_0*/ mload(0xe00), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[20] + coefficients[21] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[20]*/ mload(0x660), mulmod(/*coefficients[21]*/ mload(0x680), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step5_b: column16_row0 - after_lin_transform5_b_0 * after_lin_transform5_b_0 * after_lin_transform5_b_0. let val := addmod( /*column16_row0*/ mload(0xc20), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform5_b_0*/ mload(0xe20), /*intermediate_value/after_lin_transform5_b_0*/ mload(0xe20), PRIME), /*intermediate_value/after_lin_transform5_b_0*/ mload(0xe20), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[22] + coefficients[23] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[22]*/ mload(0x6a0), mulmod(/*coefficients[23]*/ mload(0x6c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step6_a: column7_row0 - after_lin_transform6_a_0 * after_lin_transform6_a_0 * after_lin_transform6_a_0. let val := addmod( /*column7_row0*/ mload(0xae0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform6_a_0*/ mload(0xe40), /*intermediate_value/after_lin_transform6_a_0*/ mload(0xe40), PRIME), /*intermediate_value/after_lin_transform6_a_0*/ mload(0xe40), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[24] + coefficients[25] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[24]*/ mload(0x6e0), mulmod(/*coefficients[25]*/ mload(0x700), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step6_b: column17_row0 - after_lin_transform6_b_0 * after_lin_transform6_b_0 * after_lin_transform6_b_0. let val := addmod( /*column17_row0*/ mload(0xc40), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform6_b_0*/ mload(0xe60), /*intermediate_value/after_lin_transform6_b_0*/ mload(0xe60), PRIME), /*intermediate_value/after_lin_transform6_b_0*/ mload(0xe60), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[26] + coefficients[27] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[26]*/ mload(0x720), mulmod(/*coefficients[27]*/ mload(0x740), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step7_a: column8_row0 - after_lin_transform7_a_0 * after_lin_transform7_a_0 * after_lin_transform7_a_0. let val := addmod( /*column8_row0*/ mload(0xb00), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform7_a_0*/ mload(0xe80), /*intermediate_value/after_lin_transform7_a_0*/ mload(0xe80), PRIME), /*intermediate_value/after_lin_transform7_a_0*/ mload(0xe80), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[28] + coefficients[29] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[28]*/ mload(0x760), mulmod(/*coefficients[29]*/ mload(0x780), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step7_b: column18_row0 - after_lin_transform7_b_0 * after_lin_transform7_b_0 * after_lin_transform7_b_0. let val := addmod( /*column18_row0*/ mload(0xc60), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform7_b_0*/ mload(0xea0), /*intermediate_value/after_lin_transform7_b_0*/ mload(0xea0), PRIME), /*intermediate_value/after_lin_transform7_b_0*/ mload(0xea0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[30] + coefficients[31] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[30]*/ mload(0x7a0), mulmod(/*coefficients[31]*/ mload(0x7c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step8_a: column9_row0 - after_lin_transform8_a_0 * after_lin_transform8_a_0 * after_lin_transform8_a_0. let val := addmod( /*column9_row0*/ mload(0xb20), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform8_a_0*/ mload(0xec0), /*intermediate_value/after_lin_transform8_a_0*/ mload(0xec0), PRIME), /*intermediate_value/after_lin_transform8_a_0*/ mload(0xec0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[32] + coefficients[33] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[32]*/ mload(0x7e0), mulmod(/*coefficients[33]*/ mload(0x800), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step8_b: column19_row0 - after_lin_transform8_b_0 * after_lin_transform8_b_0 * after_lin_transform8_b_0. let val := addmod( /*column19_row0*/ mload(0xc80), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform8_b_0*/ mload(0xee0), /*intermediate_value/after_lin_transform8_b_0*/ mload(0xee0), PRIME), /*intermediate_value/after_lin_transform8_b_0*/ mload(0xee0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[34] + coefficients[35] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[34]*/ mload(0x820), mulmod(/*coefficients[35]*/ mload(0x840), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step9_a: column0_row1 - after_lin_transform9_a_0 * after_lin_transform9_a_0 * after_lin_transform9_a_0. let val := addmod( /*column0_row1*/ mload(0xa00), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform9_a_0*/ mload(0xf00), /*intermediate_value/after_lin_transform9_a_0*/ mload(0xf00), PRIME), /*intermediate_value/after_lin_transform9_a_0*/ mload(0xf00), PRIME)), PRIME) // Numerator: point - trace_generator^(trace_length - 1). // val *= numerators[0]. val := mulmod(val, mload(0x1040), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[36] + coefficients[37] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[36]*/ mload(0x860), mulmod(/*coefficients[37]*/ mload(0x880), /*adjustments[1]*/mload(0x1080), PRIME)), PRIME), PRIME) } { // Constraint expression for step9_b: column10_row1 - after_lin_transform9_b_0 * after_lin_transform9_b_0 * after_lin_transform9_b_0. let val := addmod( /*column10_row1*/ mload(0xb60), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform9_b_0*/ mload(0xf20), /*intermediate_value/after_lin_transform9_b_0*/ mload(0xf20), PRIME), /*intermediate_value/after_lin_transform9_b_0*/ mload(0xf20), PRIME)), PRIME) // Numerator: point - trace_generator^(trace_length - 1). // val *= numerators[0]. val := mulmod(val, mload(0x1040), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[38] + coefficients[39] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[38]*/ mload(0x8a0), mulmod(/*coefficients[39]*/ mload(0x8c0), /*adjustments[1]*/mload(0x1080), PRIME)), PRIME), PRIME) } { // Constraint expression for input_a: column0_row0 - input_value_a. let val := addmod(/*column0_row0*/ mload(0x9e0), sub(PRIME, /*input_value_a*/ mload(0x320)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[1]. val := mulmod(val, mload(0xfa0), PRIME) // res += val * (coefficients[40] + coefficients[41] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[40]*/ mload(0x8e0), mulmod(/*coefficients[41]*/ mload(0x900), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } { // Constraint expression for output_a: column9_row0 - output_value_a. let val := addmod(/*column9_row0*/ mload(0xb20), sub(PRIME, /*output_value_a*/ mload(0x340)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(trace_length - 1). // val *= denominator_invs[2]. val := mulmod(val, mload(0xfc0), PRIME) // res += val * (coefficients[42] + coefficients[43] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[42]*/ mload(0x920), mulmod(/*coefficients[43]*/ mload(0x940), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } { // Constraint expression for input_b: column10_row0 - input_value_b. let val := addmod(/*column10_row0*/ mload(0xb40), sub(PRIME, /*input_value_b*/ mload(0x360)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[1]. val := mulmod(val, mload(0xfa0), PRIME) // res += val * (coefficients[44] + coefficients[45] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[44]*/ mload(0x960), mulmod(/*coefficients[45]*/ mload(0x980), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } { // Constraint expression for output_b: column19_row0 - output_value_b. let val := addmod(/*column19_row0*/ mload(0xc80), sub(PRIME, /*output_value_b*/ mload(0x380)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(trace_length - 1). // val *= denominator_invs[2]. val := mulmod(val, mload(0xfc0), PRIME) // res += val * (coefficients[46] + coefficients[47] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[46]*/ mload(0x9a0), mulmod(/*coefficients[47]*/ mload(0x9c0), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } mstore(0, res) return(0, 0x20) } } } } contract PeriodicColumnContract { function compute(uint256 x) external pure returns (uint256 result); } contract PrimeFieldElement6 { uint256 internal constant K_MODULUS = 0x30000003000000010000000000000001; uint256 internal constant K_MODULUS_MASK = 0x3fffffffffffffffffffffffffffffff; uint256 internal constant K_MONTGOMERY_R = 0xffffff0fffffffafffffffffffffffb; uint256 internal constant K_MONTGOMERY_R_INV = 0x9000001200000096000000600000001; uint256 internal constant GENERATOR_VAL = 3; uint256 internal constant ONE_VAL = 1; uint256 internal constant GEN1024_VAL = 0x2361be682e1cc2d366e86e194024739f; function fromMontgomery(uint256 val) internal pure returns (uint256 res) { // uint256 res = fmul(val, kMontgomeryRInv); assembly { res := mulmod( val, 0x9000001200000096000000600000001, 0x30000003000000010000000000000001 ) } 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, 0xffffff0fffffffafffffffffffffffb, 0x30000003000000010000000000000001 ) } return res; } function fmul(uint256 a, uint256 b) internal pure returns (uint256 res) { //uint256 res = mulmod(a, b, kModulus); assembly { res := mulmod(a, b, 0x30000003000000010000000000000001) } return res; } function fadd(uint256 a, uint256 b) internal pure returns (uint256 res) { // uint256 res = addmod(a, b, kModulus); assembly { res := addmod(a, b, 0x30000003000000010000000000000001) } 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(0x30000003000000010000000000000001, b), 0x30000003000000010000000000000001 ) } return res; } function fpow(uint256 val, uint256 exp) internal returns (uint256) { return expmod(val, exp, K_MODULUS); } function expmod(uint256 base, uint256 exponent, uint256 modulus) internal 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(call(not(0), 0x05, 0, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } } function inverse(uint256 val) internal returns (uint256) { return expmod(val, K_MODULUS - 2, K_MODULUS); } } contract Prng is PrimeFieldElement6 { 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 PublicInputOffsets { // The following constants are offsets of data expected in the public input. uint256 internal constant OFFSET_LOG_TRACE_LENGTH = 0; uint256 internal constant OFFSET_VDF_OUTPUT_X = 1; uint256 internal constant OFFSET_VDF_OUTPUT_Y = 2; uint256 internal constant OFFSET_VDF_INPUT_X = 3; uint256 internal constant OFFSET_VDF_INPUT_Y = 4; // The Verifier derives the number of iterations from the log of the trace length. // The Vending contract uses the number of iterations. uint256 internal constant OFFSET_N_ITER = 0; } contract StarkParameters is PrimeFieldElement6 { uint256 constant internal N_COEFFICIENTS = 48; uint256 constant internal MASK_SIZE = 22; uint256 constant internal N_ROWS_IN_MASK = 2; uint256 constant internal N_COLUMNS_IN_MASK = 20; 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; } 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 := 0x30000003000000010000000000000001 let PRIME_MON_R_INV := 0x9000001200000096000000600000001 let PRIME_MASK := 0x3fffffffffffffffffffffffffffffff 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 verifiedFact[fact]; } function registerFact( bytes32 factHash ) internal { // This function stores the testiment 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, PrimeFieldElement6 { 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 = 0x1388a7fd3b4b9599dc4b0691d6a5fcba; 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 PrimeFieldElement6.K_MODULUS. let PRIME := 0x30000003000000010000000000000001 // 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 := 0x30000003000000010000000000000001 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 := 0x30000003000000010000000000000001 let MPRIME := 0x300000030000000100000000000000010 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 := 0x30000003000000010000000000000001 let MPRIME := 0x300000030000000100000000000000010 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 := 0x30000003000000010000000000000001 // 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 { 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 = PrimeFieldElement6.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 HornerEvaluator is PrimeFieldElement6 { /* 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 = PrimeFieldElement6.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 MimcOods 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_ = PrimeFieldElement6.K_MONTGOMERY_R_INV; assembly { let PRIME := 0x30000003000000010000000000000001 let kMontgomeryRInv := kMontgomeryRInv_ let context := ctx let friQueue := /*friQueue*/ add(context, 0xda0) let friQueueEnd := add(friQueue, mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x60)) let traceQueryResponses := /*traceQueryQesponses*/ add(context, 0x3d80) let compositionQueryResponses := /*composition_query_responses*/ add(context, 0xb580) // 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 1814839283484201961915354863390654471405*PRIME < 2**256, we may add up to // 1814839283484201961915354863390654471405 numbers without fear of overflow, and use addmod modulo PRIME only every // 1814839283484201961915354863390654471405 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, 0x3a80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[0]*/ mload(add(context, 0x3180)))), 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, 0x3aa0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[1]*/ mload(add(context, 0x31a0)))), PRIME)) } // Mask items for column #1. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x20)), kMontgomeryRInv, PRIME) // res += c_2*(f_1(x) - f_1(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[2]*/ mload(add(context, 0x3ac0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[2]*/ mload(add(context, 0x31c0)))), PRIME)) } // Mask items for column #2. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x40)), kMontgomeryRInv, PRIME) // res += c_3*(f_2(x) - f_2(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[3]*/ mload(add(context, 0x3ae0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[3]*/ mload(add(context, 0x31e0)))), PRIME)) } // Mask items for column #3. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x60)), kMontgomeryRInv, PRIME) // res += c_4*(f_3(x) - f_3(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[4]*/ mload(add(context, 0x3b00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[4]*/ mload(add(context, 0x3200)))), PRIME)) } // Mask items for column #4. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x80)), kMontgomeryRInv, PRIME) // res += c_5*(f_4(x) - f_4(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[5]*/ mload(add(context, 0x3b20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[5]*/ mload(add(context, 0x3220)))), PRIME)) } // Mask items for column #5. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0xa0)), kMontgomeryRInv, PRIME) // res += c_6*(f_5(x) - f_5(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[6]*/ mload(add(context, 0x3b40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[6]*/ mload(add(context, 0x3240)))), PRIME)) } // Mask items for column #6. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0xc0)), kMontgomeryRInv, PRIME) // res += c_7*(f_6(x) - f_6(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[7]*/ mload(add(context, 0x3b60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[7]*/ mload(add(context, 0x3260)))), PRIME)) } // Mask items for column #7. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0xe0)), kMontgomeryRInv, PRIME) // res += c_8*(f_7(x) - f_7(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[8]*/ mload(add(context, 0x3b80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[8]*/ mload(add(context, 0x3280)))), PRIME)) } // Mask items for column #8. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x100)), kMontgomeryRInv, PRIME) // res += c_9*(f_8(x) - f_8(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[9]*/ mload(add(context, 0x3ba0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[9]*/ mload(add(context, 0x32a0)))), PRIME)) } // Mask items for column #9. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x120)), kMontgomeryRInv, PRIME) // res += c_10*(f_9(x) - f_9(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[10]*/ mload(add(context, 0x3bc0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[10]*/ mload(add(context, 0x32c0)))), PRIME)) } // Mask items for column #10. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x140)), kMontgomeryRInv, PRIME) // res += c_11*(f_10(x) - f_10(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[11]*/ mload(add(context, 0x3be0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[11]*/ mload(add(context, 0x32e0)))), PRIME)) // res += c_12*(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[12]*/ mload(add(context, 0x3c00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[12]*/ mload(add(context, 0x3300)))), PRIME)) } // Mask items for column #11. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x160)), kMontgomeryRInv, PRIME) // res += c_13*(f_11(x) - f_11(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[13]*/ mload(add(context, 0x3c20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[13]*/ mload(add(context, 0x3320)))), PRIME)) } // Mask items for column #12. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x180)), kMontgomeryRInv, PRIME) // res += c_14*(f_12(x) - f_12(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[14]*/ mload(add(context, 0x3c40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[14]*/ mload(add(context, 0x3340)))), PRIME)) } // Mask items for column #13. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x1a0)), kMontgomeryRInv, PRIME) // res += c_15*(f_13(x) - f_13(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[15]*/ mload(add(context, 0x3c60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[15]*/ mload(add(context, 0x3360)))), PRIME)) } // Mask items for column #14. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x1c0)), kMontgomeryRInv, PRIME) // res += c_16*(f_14(x) - f_14(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[16]*/ mload(add(context, 0x3c80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[16]*/ mload(add(context, 0x3380)))), PRIME)) } // Mask items for column #15. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x1e0)), kMontgomeryRInv, PRIME) // res += c_17*(f_15(x) - f_15(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[17]*/ mload(add(context, 0x3ca0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[17]*/ mload(add(context, 0x33a0)))), PRIME)) } // Mask items for column #16. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x200)), kMontgomeryRInv, PRIME) // res += c_18*(f_16(x) - f_16(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[18]*/ mload(add(context, 0x3cc0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[18]*/ mload(add(context, 0x33c0)))), PRIME)) } // Mask items for column #17. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x220)), kMontgomeryRInv, PRIME) // res += c_19*(f_17(x) - f_17(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[19]*/ mload(add(context, 0x3ce0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[19]*/ mload(add(context, 0x33e0)))), PRIME)) } // Mask items for column #18. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x240)), kMontgomeryRInv, PRIME) // res += c_20*(f_18(x) - f_18(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[20]*/ mload(add(context, 0x3d00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[20]*/ mload(add(context, 0x3400)))), PRIME)) } // Mask items for column #19. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x260)), kMontgomeryRInv, PRIME) // res += c_21*(f_19(x) - f_19(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[21]*/ mload(add(context, 0x3d20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[21]*/ mload(add(context, 0x3420)))), PRIME)) } // Advance traceQueryResponses by amount read (0x20 * nTraceColumns). traceQueryResponses := add(traceQueryResponses, 0x280) // Composition constraints. { // Read the next element. let columnValue := mulmod(mload(compositionQueryResponses), kMontgomeryRInv, PRIME) // res += c_22*(h_0(x) - C_0(z^2)) / (x - z^2). res := add( res, mulmod(mulmod(/*(x - z^2)^(-1)*/ mload(add(denominatorsPtr, 0x40)), /*oods_coefficients[22]*/ mload(add(context, 0x3d40)), PRIME), add(columnValue, sub(PRIME, /*composition_oods_values[0]*/ mload(add(context, 0x3440)))), PRIME)) } { // Read the next element. let columnValue := mulmod(mload(add(compositionQueryResponses, 0x20)), kMontgomeryRInv, PRIME) // res += c_23*(h_1(x) - C_1(z^2)) / (x - z^2). res := add( res, mulmod(mulmod(/*(x - z^2)^(-1)*/ mload(add(denominatorsPtr, 0x40)), /*oods_coefficients[23]*/ mload(add(context, 0x3d60)), PRIME), add(columnValue, sub(PRIME, /*composition_oods_values[1]*/ mload(add(context, 0x3460)))), 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,0x60))) // Advance denominatorsPtr by chunk size (0x20 * (2+N_ROWS_IN_MASK)). denominatorsPtr := add(denominatorsPtr, 0x80) } return(/*friQueue*/ add(context, 0xda0), 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_ = PrimeFieldElement6.GENERATOR_VAL; // The array expmodsAndPoints stores subexpressions that are needed // for the denominators computation. // The array is segmented as follows: // expmodsAndPoints[0:0] (.expmods) expmods used during calculations of the points below. // expmodsAndPoints[0:2] (.points) points used during the denominators calculation. uint256[2] 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, 0x2b40)) let PRIME := 0x30000003000000010000000000000001 // Prepare expmods for computations of trace generator powers. let oodsPoint := /*oods_point*/ mload(add(context, 0x2b60)) { // 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, 0x0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[1] = -(g * z). mstore(add(expmodsAndPoints, 0x20), point) } let evalPointsPtr := /*oodsEvalPoints*/ add(context, 0x3480) let evalPointsEndPtr := add(evalPointsPtr, mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x20)) let productsPtr := add(batchInverseArray, 0x20) let valuesPtr := add(add(batchInverseArray, 0x20), 0x1800) 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, 0x0))) 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, 0x20))) mstore(add(productsPtr, 0x20), partialProduct) mstore(add(valuesPtr, 0x20), 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, 0x40), partialProduct) mstore(add(valuesPtr, 0x40), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } // Add evalPoint to batch inverse inputs. // inverse(evalPoint) is going to be used by FRI. mstore(add(productsPtr, 0x60), partialProduct) mstore(add(valuesPtr, 0x60), evalPoint) partialProduct := mulmod(partialProduct, evalPoint, PRIME) // Advance pointers. productsPtr := add(productsPtr, 0x80) valuesPtr := add(valuesPtr, 0x80) } let productsToValuesOffset := 0x1800 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) } } } } contract Fri is MemoryMap, MemoryAccessUtils, HornerEvaluator, FriLayer { event LogGas(string name, uint256 val); function verifyLastLayer(uint256[] memory ctx, uint256 nPoints) internal { 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 { 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 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 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 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; 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); 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 { 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(call(not(0), 0x05, 0, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let PRIME := 0x30000003000000010000000000000001 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) } } } function readQueryResponsesAndDecommit( uint256[] memory ctx, 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(); 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) } } 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 { adjustQueryIndicesAndPrepareEvalPoints(ctx); // emit LogGas("Prepare evaluation points", gasleft()); readQueryResponsesAndDecommit( ctx, getNColumnsInTrace(), getPtr(ctx, MM_TRACE_QUERY_RESPONSES), bytes32(ctx[MM_TRACE_COMMITMENT])); // emit LogGas("Read and decommit trace", gasleft()); readQueryResponsesAndDecommit( ctx, 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 := 0x30000003000000010000000000000000 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 { // 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)); 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 MimcVerifier is StarkParameters, StarkVerifier, FactRegistry, PublicInputOffsets{ MimcConstraintPoly constraintPoly; PeriodicColumnContract[20] constantsCols; uint256 internal constant PUBLIC_INPUT_SIZE = 5; constructor( address[] memory auxPolynomials, MimcOods oodsContract, uint256 numSecurityBits_, uint256 minProofOfWorkBits_) StarkVerifier( numSecurityBits_, minProofOfWorkBits_ ) public { constraintPoly = MimcConstraintPoly(auxPolynomials[0]); for (uint256 i = 0; i < 20; i++) { constantsCols[i] = PeriodicColumnContract(auxPolynomials[i+1]); } oodsContractAddress = address(oodsContract); } function verifyProofAndRegister( uint256[] calldata proofParams, uint256[] calldata proof, uint256[] calldata publicInput ) external { verifyProof(proofParams, proof, publicInput); registerFact( keccak256( abi.encodePacked( 10 * 2**publicInput[OFFSET_LOG_TRACE_LENGTH] - 1, publicInput[OFFSET_VDF_OUTPUT_X], publicInput[OFFSET_VDF_OUTPUT_Y], publicInput[OFFSET_VDF_INPUT_X], publicInput[OFFSET_VDF_INPUT_Y] ) ) ); } function getNColumnsInTrace() internal pure returns (uint256) { return N_COLUMNS_IN_MASK; } function getNColumnsInComposition() internal pure returns (uint256) { return CONSTRAINTS_DEGREE_BOUND; } 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 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 returns (uint256[] memory ctx, uint256 logTraceLength) { require(publicInput.length == PUBLIC_INPUT_SIZE, "INVALID_PUBLIC_INPUT_LENGTH" ); ctx = new uint256[](MM_CONTEXT_SIZE); // Note that the prover does the VDF computation the other way around (uses the inverse // function), hence vdf_output is the input for its calculation, and vdf_input should be the // result of the calculation. ctx[MM_INPUT_VALUE_A] = publicInput[OFFSET_VDF_OUTPUT_X]; ctx[MM_INPUT_VALUE_B] = publicInput[OFFSET_VDF_OUTPUT_Y]; ctx[MM_OUTPUT_VALUE_A] = publicInput[OFFSET_VDF_INPUT_X]; ctx[MM_OUTPUT_VALUE_B] = publicInput[OFFSET_VDF_INPUT_Y]; // Initialize the MDS matrix values with fixed predefined values. ctx[MM_MAT00] = 0x109bbc181e07a285856e0d8bde02619; ctx[MM_MAT01] = 0x1eb8859b1b789cd8a80927a32fdf41f7; ctx[MM_MAT10] = 0xdc8eaac802c8f9cb9dff6ed0728012d; ctx[MM_MAT11] = 0x2c18506f35eab63b58143a34181c89e; logTraceLength = publicInput[OFFSET_LOG_TRACE_LENGTH]; require(logTraceLength <= 50, "logTraceLength must not exceed 50."); } function getPublicInputHash(uint256[] memory publicInput) internal pure returns (bytes32) { return keccak256( abi.encodePacked( uint64(2 ** publicInput[OFFSET_LOG_TRACE_LENGTH]), publicInput[OFFSET_VDF_OUTPUT_X], publicInput[OFFSET_VDF_OUTPUT_Y], publicInput[OFFSET_VDF_INPUT_X], publicInput[OFFSET_VDF_INPUT_Y]) ); } /* Checks that the trace and the composition agree on the Out of Domain Sampling point, assuming the prover provided us with the proper evaluations. Later, we use boundary constraints to check that those evaluations are actually consistent with the committed trace and composition polynomials. */ function oodsConsistencyCheck(uint256[] memory ctx) internal { uint256 oodsPoint = ctx[MM_OODS_POINT]; uint256 nRows = 256; uint256 zPointPow = fpow(oodsPoint, ctx[MM_TRACE_LENGTH] / nRows); ctx[MM_PERIODIC_COLUMN__CONSTS0_A] = constantsCols[0].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS1_A] = constantsCols[1].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS2_A] = constantsCols[2].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS3_A] = constantsCols[3].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS4_A] = constantsCols[4].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS5_A] = constantsCols[5].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS6_A] = constantsCols[6].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS7_A] = constantsCols[7].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS8_A] = constantsCols[8].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS9_A] = constantsCols[9].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS0_B] = constantsCols[10].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS1_B] = constantsCols[11].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS2_B] = constantsCols[12].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS3_B] = constantsCols[13].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS4_B] = constantsCols[14].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS5_B] = constantsCols[15].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS6_B] = constantsCols[16].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS7_B] = constantsCols[17].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS8_B] = constantsCols[18].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS9_B] = constantsCols[19].compute(zPointPow); 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 MimcConstraintPoly 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"); } }
0x608060405234801561001057600080fd5b50600436106100415760003560e01c80636a93856714610046578063d6354e1514610077578063fd2527421461007f575b600080fd5b6100636004803603602081101561005c57600080fd5b5035610195565b604080519115158252519081900360200190f35b6100636101aa565b6101936004803603606081101561009557600080fd5b8101906020810181356401000000008111156100b057600080fd5b8201836020820111156100c257600080fd5b803590602001918460208302840111640100000000831117156100e457600080fd5b91939092909160208101903564010000000081111561010257600080fd5b82018360208201111561011457600080fd5b8035906020019184602083028401116401000000008311171561013657600080fd5b91939092909160208101903564010000000081111561015457600080fd5b82018360208201111561016657600080fd5b8035906020019184602083028401116401000000008311171561018857600080fd5b5090925090506101b3565b005b60009081526003602052604090205460ff1690565b60045460ff1690565b61025186868080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525050604080516020808a028281018201909352898252909350899250889182918501908490808284376000920191909152505060408051602080890282810182019093528882529093508892508791829185019084908082843760009201919091525061031092505050565b61030860018383600081811061026357fe5b9050602002013560020a600a02038383600181811061027e57fe5b905060200201358484600281811061029257fe5b90506020020135858560038181106102a657fe5b90506020020135868660048181106102ba57fe5b9050602002013560405160200180868152602001858152602001848152602001838152602001828152602001955050505050506040516020818303038152906040528051906020012061057d565b505050505050565b606061031c82856105ed565b9050600061032982610da5565b90506103468161033886610dac565b61034186610daf565b610e7d565b610351816001610e9a565b60001c8260068151811061036157fe5b60200260200101818152505061038f81610379610eaf565b61038a85610385610eb4565b610eba565b610f3c565b61039a816001610e9a565b60001c826007815181106103aa57fe5b6020026020010181815250506103c881600161038a8561015a610eba565b60006103d2611031565b9050805b6103de611037565b8201811015610411576103f283600161103c565b8482815181106103fe57fe5b60209081029190910101526001016103d6565b5061041b83611051565b61043382610427611037565b61038a86610385611ff6565b61043e826001610e9a565b60001c836101308151811061044f57fe5b602002602001018181525050600061046684611ffc565b519050600061047785610126610eba565b905060015b600183038110156104c957610498856001836020028501610f3c565b6104a3856001610e9a565b60001c868261013001815181106104b657fe5b602090810291909101015260010161047c565b506104de84600161038a886101258701610eba565b6104e785612014565b61050584866003815181106104f857fe5b602002602001015161214c565b610548848660088151811061051657fe5b602002602001015160018860008151811061052d57fe5b60200260200101510361054189606c610eba565b606061223e565b8560088151811061055557fe5b60200260200101818152505061056a8561230d565b610573856123db565b5050505050505050565b600081815260036020526040902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016600117905560045460ff166105ea57600480547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001660011790555b50565b6060600582511161065f57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f496e76616c69642070726f6f66506172616d732e000000000000000000000000604482015290519081900360640190fd5b8160048151811061066c57fe5b60200260200101516005018251146106e557604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f496e76616c69642070726f6f66506172616d732e000000000000000000000000604482015290519081900360640190fd5b6000826001815181106106f457fe5b602002602001015190506010811115610758576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180613b306022913960400191505060405180910390fd5b60018110156107b2576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180613a8f6022913960400191505060405180910390fd5b6000836002815181106107c157fe5b602002602001015190506032811115610825576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180613b526022913960400191505060405180910390fd5b600154811015610880576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526025815260200180613ab16025913960400191505060405180910390fd5b60005481106108da576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602681526020018061391f6026913960400191505060405180910390fd5b6000846003815181106108e957fe5b60200260200101519050600a81111561094d576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602b81526020018061396c602b913960400191505060405180910390fd5b60008560048151811061095c57fe5b60200260200101519050600a8111156109d657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f546f6f206d616e79206672692073746570732e00000000000000000000000000604482015290519081900360640190fd5b60018111610a4557604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f4e6f7420656e6f756768206672692073746570732e0000000000000000000000604482015290519081900360640190fd5b606081604051908082528060200260200182016040528015610a71578160200160208202803883390190505b50905060005b82811015610ab557878160050181518110610a8e57fe5b6020026020010151828281518110610aa257fe5b6020908102919091010152600101610a77565b506000610ac18961255b565b9097509050610ad18282866127d1565b6000610adf88610125610eba565b90508281528460020a8861013a81518110610af657fe5b6020026020010181815250508160020a8861015281518110610b1457fe5b6020026020010181815250508660020a88600181518110610b3157fe5b6020026020010181815250508588600381518110610b4b57fe5b602002602001018181525050600089600081518110610b6657fe5b6020026020010151905060008111610bc9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260268152602001806139c26026913960400191505060405180910390fd5b6030811115610c3957604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f546f6f206d616e7920717565726965732e000000000000000000000000000000604482015290519081900360640190fd5b60005487898302011015610c98576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526032815260200180613a386032913960400191505060405180910390fd5b8089600881518110610ca657fe5b60200260200101818152505087830189600281518110610cc257fe5b60200260200101818152505088600281518110610cdb57fe5b602002602001015160020a89600081518110610cf357fe5b6020026020010181815250506000610d3c60038b600081518110610d1357fe5b602002602001015160016f300000030000000100000000000000010381610d3657fe5b046129b1565b9050808a600481518110610d4c57fe5b6020026020010181815250506000610d78828c600181518110610d6b57fe5b60200260200101516129b1565b9050808b61015981518110610d8957fe5b6020026020010181815250505050505050505050505092915050565b6101400190565b90565b600081600081518110610dbe57fe5b602002602001015160020a82600181518110610dd657fe5b602002602001015183600281518110610deb57fe5b602002602001015184600381518110610e0057fe5b602002602001015185600481518110610e1557fe5b6020026020010151604051602001808667ffffffffffffffff1667ffffffffffffffff1660c01b815260080185815260200184815260200183815260200182815260200195505050505050604051602081830303815290604052805190602001209050919050565b602082018352610e95610e8f846129d5565b826129db565b505050565b600080610ea784846129e7565b949350505050565b603090565b61015b90565b60008061060b8310610f2d57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601a60248201527f4f766572666c6f772070726f74656374696f6e206661696c6564000000000000604482015290519081900360640190fd5b50506020908102919091010190565b63010000008210610fae57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601b60248201527f4f766572666c6f772070726f74656374696f6e206661696c65642e0000000000604482015290519081900360640190fd5b6f300000030000000100000000000000016f090000012000000960000006000000016f3fffffffffffffffffffffffffffffff60208601604087016020870286015b8087101561102657855b868110611014575060408320825160010183528416610ffa565b86868209885250602087019650610ff0565b505050505050505050565b61018b90565b601890565b600080610ea761104c85856129e7565b612a1a565b60008161015a8151811061106157fe5b602002602001015190506000610100905060006110968383866101528151811061108757fe5b602002602001015181610d3657fe5b600554604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101849052905192935073ffffffffffffffffffffffffffffffffffffffff90911691635ed86d5c91602480820192602092909190829003018186803b15801561110b57600080fd5b505afa15801561111f573d6000803e3d6000fd5b505050506040513d602081101561113557600080fd5b50518451859061013c90811061114757fe5b602090810291909101810191909152600654604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b1580156111c257600080fd5b505afa1580156111d6573d6000803e3d6000fd5b505050506040513d60208110156111ec57600080fd5b50518451859061013d9081106111fe57fe5b602090810291909101810191909152600754604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b15801561127957600080fd5b505afa15801561128d573d6000803e3d6000fd5b505050506040513d60208110156112a357600080fd5b50518451859061013e9081106112b557fe5b602090810291909101810191909152600854604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b15801561133057600080fd5b505afa158015611344573d6000803e3d6000fd5b505050506040513d602081101561135a57600080fd5b50518451859061013f90811061136c57fe5b602090810291909101810191909152600954604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b1580156113e757600080fd5b505afa1580156113fb573d6000803e3d6000fd5b505050506040513d602081101561141157600080fd5b50518451859061014090811061142357fe5b602090810291909101810191909152600a54604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b15801561149e57600080fd5b505afa1580156114b2573d6000803e3d6000fd5b505050506040513d60208110156114c857600080fd5b5051845185906101419081106114da57fe5b602090810291909101810191909152600b54604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b15801561155557600080fd5b505afa158015611569573d6000803e3d6000fd5b505050506040513d602081101561157f57600080fd5b50518451859061014290811061159157fe5b602090810291909101810191909152600c54604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b15801561160c57600080fd5b505afa158015611620573d6000803e3d6000fd5b505050506040513d602081101561163657600080fd5b50518451859061014390811061164857fe5b602090810291909101810191909152600d54604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b1580156116c357600080fd5b505afa1580156116d7573d6000803e3d6000fd5b505050506040513d60208110156116ed57600080fd5b5051845185906101449081106116ff57fe5b602090810291909101810191909152600e54604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b15801561177a57600080fd5b505afa15801561178e573d6000803e3d6000fd5b505050506040513d60208110156117a457600080fd5b5051845185906101459081106117b657fe5b602090810291909101810191909152600f54604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b15801561183157600080fd5b505afa158015611845573d6000803e3d6000fd5b505050506040513d602081101561185b57600080fd5b50518451859061014690811061186d57fe5b602090810291909101810191909152601054604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b1580156118e857600080fd5b505afa1580156118fc573d6000803e3d6000fd5b505050506040513d602081101561191257600080fd5b50518451859061014790811061192457fe5b602090810291909101810191909152601154604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b15801561199f57600080fd5b505afa1580156119b3573d6000803e3d6000fd5b505050506040513d60208110156119c957600080fd5b5051845185906101489081106119db57fe5b602090810291909101810191909152601254604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b158015611a5657600080fd5b505afa158015611a6a573d6000803e3d6000fd5b505050506040513d6020811015611a8057600080fd5b505184518590610149908110611a9257fe5b602090810291909101810191909152601354604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b158015611b0d57600080fd5b505afa158015611b21573d6000803e3d6000fd5b505050506040513d6020811015611b3757600080fd5b50518451859061014a908110611b4957fe5b602090810291909101810191909152601454604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b158015611bc457600080fd5b505afa158015611bd8573d6000803e3d6000fd5b505050506040513d6020811015611bee57600080fd5b50518451859061014b908110611c0057fe5b602090810291909101810191909152601554604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b158015611c7b57600080fd5b505afa158015611c8f573d6000803e3d6000fd5b505050506040513d6020811015611ca557600080fd5b50518451859061014c908110611cb757fe5b602090810291909101810191909152601654604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b158015611d3257600080fd5b505afa158015611d46573d6000803e3d6000fd5b505050506040513d6020811015611d5c57600080fd5b50518451859061014d908110611d6e57fe5b602090810291909101810191909152601754604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b158015611de957600080fd5b505afa158015611dfd573d6000803e3d6000fd5b505050506040513d6020811015611e1357600080fd5b50518451859061014e908110611e2557fe5b602090810291909101810191909152601854604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b158015611ea057600080fd5b505afa158015611eb4573d6000803e3d6000fd5b505050506040513d6020811015611eca57600080fd5b50518451859061014f908110611edc57fe5b60209081029190910181019190915260045460405160009261010090920473ffffffffffffffffffffffffffffffffffffffff16916127a091610ca09181838b8601877ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa611f4f573d6000803e3d6000fd5b80519450506000611f9c89601661018b0181518110611f6a57fe5b6020026020010151611f978a8c601661018b0160010181518110611f8a57fe5b6020026020010151612a46565b612a63565b9050808514611026576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260278152602001806139456027913960400191505060405180910390fd5b6101d390565b6060600061200c83610125610eba565b519392505050565b60006009905060008261013a8151811061202a57fe5b60200260200101519050600080600090506f300000030000000100000000000000006020850260208701018051935060208502808501855b8181101561207b57805185109590951794602001612062565b50602083810180517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe089019081529390910190922090915260006040830152905250801561212a57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601660248201527f496e76616c6964206669656c6420656c656d656e742e00000000000000000000604482015290519081900360640190fd5b818561013b8151811061213957fe5b6020026020010181815250505050505050565b806121565761223a565b60007f0123456789abcded00000000000000000000000000000000000000000000000060005260208301518060085282602853602960002060005283518051602052602860002092508160005260286000206020860152600060408601526008810185525050600082610100036001901b905080821061223757604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601b60248201527f50726f6f66206f6620776f726b20636865636b206661696c65642e0000000000604482015290519081900360640190fd5b50505b5050565b6000808084815b888110156122f3578261226b5761226361225e8b6129d5565b612a80565b935061010092505b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc09092019183831c88168260005b898211156122bf5750878103518083106122b2576122bf565b8082528882039150612299565b8083146122d257828252938801936122e8565b5b848210156122e85781890180519092526122d3565b505050600101612245565b5084868203816122ff57fe5b049998505050505050505050565b61231681612ab6565b61234b81612322612cad565b61232e846101eb610eba565b8460068151811061233b57fe5b602002602001015160001b612cb2565b61237081612357612e04565b612363846105ab610eba565b8460078151811061233b57fe5b60025473ffffffffffffffffffffffffffffffffffffffff16600061239683606c610eba565b8351909150611200908190839060010160200286867ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa612237573d6000803e3d6000fd5b60006123e88260fd610eba565b90506123f381612e09565b60006123fe83610da5565b9050600061240b84612ec4565b905060006001905060008560088151811061242257fe5b6020026020010151905060008660fc8151811061243b57fe5b602090810291909101015260005b818110156124af576124878782600302606c016001018151811061246957fe5b60200260200101516f0ffffff0fffffffafffffffffffffffb612a46565b8782600302606c016001018151811061249c57fe5b6020908102919091010152600101612449565b5060006124bd87606c610eba565b905060606124ca88611ffc565b80519091505b808510156125515760008286815181106124e657fe5b602002602001015160020a9050612519888589888e8b610126018151811061250a57fe5b6020026020010151868f612ed7565b945061254488888c60018a61013001038151811061253357fe5b602002602001015160001b88612f34565b50506001909401936124d0565b61102689856130db565b6060600060058351146125cf57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601b60248201527f494e56414c49445f5055424c49435f494e5055545f4c454e4754480000000000604482015290519081900360640190fd5b6040805161060b80825261c1808201909252906020820161c160803883390190505091508260018151811061260057fe5b6020026020010151826101558151811061261657fe5b6020026020010181815250508260028151811061262f57fe5b6020026020010151826101578151811061264557fe5b6020026020010181815250508260038151811061265e57fe5b6020026020010151826101568151811061267457fe5b6020026020010181815250508260048151811061268d57fe5b602002602001015182610158815181106126a357fe5b6020026020010181815250506f0109bbc181e07a285856e0d8bde0261982610150815181106126ce57fe5b6020026020010181815250506f1eb8859b1b789cd8a80927a32fdf41f782610151815181106126f957fe5b6020026020010181815250506f0dc8eaac802c8f9cb9dff6ed0728012d826101538151811061272457fe5b6020026020010181815250506f02c18506f35eab63b58143a34181c89e826101548151811061274f57fe5b6020026020010181815250508260008151811061276857fe5b6020026020010151905060328111156127cc576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180613b0e6022913960400191505060405180910390fd5b915091565b826000815181106127de57fe5b602002602001015160001461283e576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526025815260200180613a6a6025913960400191505060405180910390fd5b8251819060015b8181101561295157600086828151811061285b57fe5b60200260200101519050600081116128d457604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820181905260248201527f4f6e6c79207468652066697273742066726920737465702063616e2062652030604482015290519081900360640190fd5b600481111561294457604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601c60248201527f4d617820737570706f7274656420667269207374657020697320342e00000000604482015290519081900360640190fd5b9290920191600101612845565b508382146129aa576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526024815260200180613a146024913960400191505060405180910390fd5b5050505050565b60006129ce83836f30000003000000010000000000000001613205565b9392505050565b60200190565b61223a82826000613244565b81518051602082018452600091908315610ea7576020850160208101828152604082208252600081525050949350505050565b60006f300000030000000100000000000000016f09000001200000096000000600000001830992915050565b60006f300000030000000100000000000000018284099392505050565b60006f300000030000000100000000000000018284089392505050565b6000806000612a8e8461324f565b9092509050612a9d828261325b565b94509092509050612aaf848383613244565b5050919050565b600081600881518110612ac557fe5b602002602001015190506000612adc83606c610eba565b90506060820281016000612af2856101a3610eba565b9050600085600281518110612b0357fe5b60200260200101519050600086600081518110612b1c57fe5b60200260200101519050600087600481518110612b3557fe5b60200260200101519050612c62565b600081905067aaaaaaaaaaaaaaaa811660046755555555555555558316021790506801999999999999999881166010676666666666666666831602179050680787878787878787808116610100677878787878787878831602179050687f807f807f807f8000811662010000677f807f807f807f80831602179050697fff80007fff800000008116640100000000677fff80007fff80008316021790506b7fffffff8000000000000000811668010000000000000000677fffffff8000000083160217905082607f0360020a8104905092915050565b600060405160208152602080820152602060408201528260608201528360808201528460a082015260208160c08360006005600019f1612c5957600080fd5b51949350505050565b6f300000030000000100000000000000015b85871015611026578651838101808952612c9883612c928885612b44565b86612c1a565b87526020870196505050606087019650612c74565b601490565b612cba612e04565b612cc2612cad565b01831115612d3157604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f546f6f206d616e7920636f6c756d6e732e000000000000000000000000000000604482015290519081900360640190fd5b600084600881518110612d4057fe5b602002602001015190506000612d57866009610eba565b90506000612d6687606c610eba565b90506060830281016000612d7b89600c610eba565b9050602088026000612d8b61328e565b90508551835b85871015612de75782848320166020851415612dab575081515b875182528060208301526040820191508483015b80841015612dda5783518d5260209c8d019c90930192612dbf565b5050606087019650612d91565b508652612df686848a8a612f34565b505050505050505050505050565b600290565b610200810161040082016f1388a7fd3b4b9599dc4b0691d6a5fcba6000612e3182600f6129b1565b60018085528086526f300000030000000100000000000000006020870152909150806f300000030000000100000000000000016008825b81811015612eb857612e7a8588612a46565b9450612e868487612a46565b93506000612e958260036132b2565b60208082028b0187905260409091028b0187815287860391015250600101612e68565b50505050505050505050565b6000612ed182600c610eba565b92915050565b60008587806060880281015b600080612ef28e89878c6132f0565b9196509092509050612f098885848d8d868c6133c9565b6040860195506060840193505050808310612ee35760608b8303049c9b505050505050505050505050565b600080612f3f61328e565b90506080831115612fb157604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601760248201527f544f4f5f4d414e595f4d45524b4c455f51554552494553000000000000000000604482015290519081900360640190fd5b60208501604084026040600080898201518b515b60018211156130555760018218604060208209888601518160201852878787086002909404858f01528d84015193955060208301928285141561303857507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0909201918589018888880896508e87015194505b8051825260406000208b168a870152888887089550505050612fc5565b9290950151918b52509450505084831490506130d257604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f494e56414c49445f4d45524b4c455f50524f4f46000000000000000000000000604482015290519081900360640190fd5b50949350505050565b60008261013a815181106130eb57fe5b60200260200101519050600060018460018151811061310657fe5b6020026020010151830203905060008461013b8151811061312357fe5b6020026020010151905060008090505b848110156103085760008682600302606c016002018151811061315257fe5b6020026020010151905061316681856129b1565b90508682600302606c016001018151811061317d57fe5b60200260200101516131908483886134a2565b146131fc57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f426164204c617374206c617965722076616c75652e0000000000000000000000604482015290519081900360640190fd5b50600101613133565b600060405160208152602080820152602060408201528460608201528360808201528260a082015260208160c08360006005600019f1612c5957600080fd5b908252602090910152565b80516020820151915091565b60408051602080820185905281830184905282518083038401815260609092019092528051910120919260019091019190565b7fffffffffffffffffffffffffffffffffffffffff00000000000000000000000090565b60008161010014806132c657508160020a83105b6132cc57fe5b826000805b848110156130d2576002918202600184161791830492506001016132d1565b81517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820119811680820360200285016102009081015160408601518694600093899390840192868901916f30000003000000010000000000000001918291900995508b51875b838110156133b5576020820191818614156133a1575060608a018051909a9095507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0909201916020015b518390068752602090960195600101613357565b50808d525050505050509450945094915050565b600087610400810160088614156133ef576133e681838a8a613600565b9850925061346a565b8560041415613404576133e681838a8a6136ed565b8560101415613419576133e681838a8a613766565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602b815260200180613997602b913960400191505060405180910390fd5b600061347461328e565b9587900480865260209788029093209095169386019390935287529286019290925250505060409091015250565b6000806f300000030000000100000000000000016008840615613510576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526038815260200180613ad66038913960400191505060405180910390fd5b611000841061356a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c8152602001806139e8602c913960400191505060405180910390fd5b6020840286015b868111156135eb577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000181868181818181818a0960e0880151010960c0860151010960a08401510109608082015101925081868388858a878c8a096060880151010960408601510109602084015101098151019250613571565b508082816135f557fe5b069695505050505050565b6000806f300000030000000100000000000000017003000000300000001000000000000000108651828787098381820960208b015160208b0151868188038601850960408d015160608e01519690920101948780848709828a0384010991010186818703860184098186010194505060808b01518660408e0151850960a08d015188818a03840183098184010192505060c08d015160e08e0151898a868509828c038401099101018881890384018184800909818401019250505086878288038701898687090982870108985050858a8b0986818209878182099850505050505050505094509492505050565b6000806f300000030000000100000000000000018085850986516020880151838185038301840981830101915050604088015160608901518485868660208f0151098388038501098284010891505083888909848182099550508384828603840186868709098284010895505050505094509492505050565b60008060006f3000000300000001000000000000000170030000003000000010000000000000001087518288880960208b015160208b0151858187038501840960408d015160608e01519590920101938680848609828903840109910101858380098681820997508682870386018209828601019450505060808b01518560408e0151840960a08d015187818903840183098184010192505060c08d015160e08e01518889868509828b03840109910101878188038401818480090981840101925050508581860385018809818501019350506101008b01518560808e015184096101208d01518781890384018309818401019250506101408d01516101608e01518889868509828b03840109910101878188038401818480090981840101925050506101808c01518660c08f015185096101a08e015188818a0384018309818401019250506101c08e01516101e08f0151898a878509828c038401099101018881890384018184800909818401019250505086818703830188858b090991010185808287038601818a80090982860108985050848a8b0985818209868182098781820999505050505050505050509450949250505056fe50726f6f6673206d6179206e6f7420626520707572656c79206261736564206f6e20506f572e636c61696d6564436f6d706f736974696f6e20646f6573206e6f74206d617463682074726163656c6f674672694c6173744c61796572446567426f756e64206d757374206265206174206d6f73742031302e4f6e6c7920737465702073697a6573206f6620322c2033206f7220342061726520737570706f727465642e4e756d626572206f662071756572696573206d757374206265206174206c65617374206f6e654e6f206d6f7265207468616e203430393620636f656666696369656e74732061726520737570706f7274656446726920706172616d7320646f206e6f74206d61746368207472616365206c656e67746850726f6f6620706172616d7320646f206e6f74207361746973667920736563757269747920726571756972656d656e74732e4f6e6c792065746130203d3d20302069732063757272656e746c7920737570706f727465646c6f67426c6f777570466163746f72206d757374206265206174206c6561737420316d696e696d756d2070726f6f664f66576f726b42697473206e6f74207361746973666965644e756d626572206f6620706f6c796e6f6d69616c20636f656666696369656e7473206d75737420626520646976697369626c6520627920386c6f6754726163654c656e677468206d757374206e6f74206578636565642035302e6c6f67426c6f777570466163746f72206d757374206265206174206d6f737420313670726f6f664f66576f726b42697473206d757374206265206174206d6f7374203530a265627a7a723158209caed92e8766704010513b3bcbf13cfc93f87ee37f5f622b55466d9efcf04c5764736f6c63430005110032
{"success": true, "error": null, "results": {}}
true
null
{}
35
0x0e49911C937357EAA5a56984483b4B8918D0493b
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 = 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(); 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); } /// @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); 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); 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] && _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; } 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; } } 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, 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 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 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; } 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) * (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 = 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 = 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 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(swapedTokens >= 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)); 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(DAI_JOIN_ADDRESS); 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 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(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); 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(); (,,,,,,,,,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); 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 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 = 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) { (, 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 = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB; /// @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])); } } }
0x6080604052600436106100c25760003560e01c80637753f47b1161007f578063934785b711610059578063934785b7146102aa578063bfe142a3146102f5578063c1bce0b71461030a578063c91d59fe14610349576100c2565b80637753f47b1461020857806383c2120c146102395780638905d1781461026c576100c2565b806305a363de146100c757806313120a4e146100f357806347e7ef241461013b57806348ca13001461016757806349df728c1461019a5780635a3b74b9146101cd575b600080fd5b3480156100d357600080fd5b506100dc61035e565b6040805161ffff9092168252519081900360200190f35b610139600480360360a081101561010957600080fd5b506001600160a01b0381358116916020810135821691604082013591606081013515159160809091013516610363565b005b6101396004803603604081101561015157600080fd5b506001600160a01b0381351690602001356106d9565b34801561017357600080fd5b506101396004803603602081101561018a57600080fd5b50356001600160a01b03166109a9565b3480156101a657600080fd5b50610139600480360360208110156101bd57600080fd5b50356001600160a01b0316610a85565b3480156101d957600080fd5b50610139600480360360408110156101f057600080fd5b506001600160a01b0381351690602001351515610ba2565b34801561021457600080fd5b5061021d610c90565b604080516001600160a01b039092168252519081900360200190f35b34801561024557600080fd5b506101396004803603602081101561025c57600080fd5b50356001600160a01b0316610ca8565b6101396004803603608081101561028257600080fd5b506001600160a01b038135811691602081013590911690604081013590606001351515610e04565b3480156102b657600080fd5b50610139600480360360808110156102cd57600080fd5b506001600160a01b038135811691602081013590911690604081013590606001351515611175565b34801561030157600080fd5b5061021d611362565b34801561031657600080fd5b506101396004803603606081101561032d57600080fd5b506001600160a01b03813516906020810135906040013561137a565b34801561035557600080fd5b5061021d611584565b604081565b604080516370a0823160e01b8152306004820152905160039182916eb3f879cb30fe243b4dfee438691c04916370a08231916024808301926020929190829003018186803b1580156103b457600080fd5b505afa1580156103c8573d6000803e3d6000fd5b505050506040513d60208110156103de57600080fd5b505110610467576eb3f879cb30fe243b4dfee438691c046001600160a01b031663d8ccd0f3826040518263ffffffff1660e01b815260040180828152602001915050602060405180830381600087803b15801561043a57600080fd5b505af115801561044e573d6000803e3d6000fd5b505050506040513d602081101561046457600080fd5b50505b60007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b1580156104b657600080fd5b505afa1580156104ca573d6000803e3d6000fd5b505050506040513d60208110156104e057600080fd5b505160408051630261bf8b60e01b815290519192506000917324a42fd28c976a61df5d00d0599c34c4f90748c891630261bf8b916004808301926020929190829003018186803b15801561053357600080fd5b505afa158015610547573d6000803e3d6000fd5b505050506040513d602081101561055d57600080fd5b5051604080516328dd2d0160e01b81526001600160a01b038b811660048301528781166024830152915192935088926000928392908616916328dd2d019160448082019261014092909190829003018186803b1580156105bc57600080fd5b505afa1580156105d0573d6000803e3d6000fd5b505050506040513d6101408110156105e757600080fd5b50602081015160c09091015190925090508715610602578192505b918201916001600160a01b038b1673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1461064f576106456001600160a01b038c1633308663ffffffff61159716565b61064f8b866115f7565b6040805163173aba7160e21b81526001600160a01b038d81166004830152602482018690528981166044830152915191861691635ceae9c4913491606480830192600092919082900301818588803b1580156106aa57600080fd5b505af11580156106be573d6000803e3d6000fd5b50505050506106cc8b610a85565b5050505050505050505050565b604080516370a0823160e01b8152306004820152905160059182916eb3f879cb30fe243b4dfee438691c04916370a08231916024808301926020929190829003018186803b15801561072a57600080fd5b505afa15801561073e573d6000803e3d6000fd5b505050506040513d602081101561075457600080fd5b5051106107dd576eb3f879cb30fe243b4dfee438691c046001600160a01b031663d8ccd0f3826040518263ffffffff1660e01b815260040180828152602001915050602060405180830381600087803b1580156107b057600080fd5b505af11580156107c4573d6000803e3d6000fd5b505050506040513d60208110156107da57600080fd5b50505b60007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b15801561082c57600080fd5b505afa158015610840573d6000803e3d6000fd5b505050506040513d602081101561085657600080fd5b505160408051630261bf8b60e01b815290519192506000917324a42fd28c976a61df5d00d0599c34c4f90748c891630261bf8b916004808301926020929190829003018186803b1580156108a957600080fd5b505afa1580156108bd573d6000803e3d6000fd5b505050506040513d60208110156108d357600080fd5b50519050836001600160a01b03861673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14610925576109176001600160a01b03871633308863ffffffff61159716565b61092186846115f7565b5060005b60408051636968703360e11b81526001600160a01b038881166004830152602482018890526044820183905291519184169163d2d0e066918491606480830192600092919082900301818588803b15801561097f57600080fd5b505af1158015610993573d6000803e3d6000fd5b50505050506109a186610ca8565b505050505050565b60007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b1580156109f857600080fd5b505afa158015610a0c573d6000803e3d6000fd5b505050506040513d6020811015610a2257600080fd5b5051604080516248ca1360e81b81526001600160a01b0385811660048301529151929350908316916348ca13009160248082019260009290919082900301818387803b158015610a7157600080fd5b505af11580156109a1573d6000803e3d6000fd5b60006001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14610b2257604080516370a0823160e01b815230600482015290516001600160a01b038416916370a08231916024808301926020929190829003018186803b158015610af157600080fd5b505afa158015610b05573d6000803e3d6000fd5b505050506040513d6020811015610b1b57600080fd5b5051610b24565b475b90508015610b9e576001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14610b6f57610b6a6001600160a01b038316338363ffffffff61165216565b610b9e565b604051339082156108fc029083906000818181858888f19350505050158015610b9c573d6000803e3d6000fd5b505b5050565b60007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015610bf157600080fd5b505afa158015610c05573d6000803e3d6000fd5b505050506040513d6020811015610c1b57600080fd5b505160408051635a3b74b960e01b81526001600160a01b0386811660048301528515156024830152915192935090831691635a3b74b99160448082019260009290919082900301818387803b158015610c7357600080fd5b505af1158015610c87573d6000803e3d6000fd5b50505050505050565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b60007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015610cf757600080fd5b505afa158015610d0b573d6000803e3d6000fd5b505050506040513d6020811015610d2157600080fd5b5051604080516328dd2d0160e01b81526001600160a01b0385811660048301523060248301529151929350600092918416916328dd2d019160448082019261014092909190829003018186803b158015610d7a57600080fd5b505afa158015610d8e573d6000803e3d6000fd5b505050506040513d610140811015610da557600080fd5b506101200151905080610b9c5760408051635a3b74b960e01b81526001600160a01b03858116600483015260016024830152915191841691635a3b74b99160448082019260009290919082900301818387803b158015610c7357600080fd5b604080516370a0823160e01b8152306004820152905160039182916eb3f879cb30fe243b4dfee438691c04916370a08231916024808301926020929190829003018186803b158015610e5557600080fd5b505afa158015610e69573d6000803e3d6000fd5b505050506040513d6020811015610e7f57600080fd5b505110610f08576eb3f879cb30fe243b4dfee438691c046001600160a01b031663d8ccd0f3826040518263ffffffff1660e01b815260040180828152602001915050602060405180830381600087803b158015610edb57600080fd5b505af1158015610eef573d6000803e3d6000fd5b505050506040513d6020811015610f0557600080fd5b50505b60007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b158015610f5757600080fd5b505afa158015610f6b573d6000803e3d6000fd5b505050506040513d6020811015610f8157600080fd5b505160408051630261bf8b60e01b815290519192506000917324a42fd28c976a61df5d00d0599c34c4f90748c891630261bf8b916004808301926020929190829003018186803b158015610fd457600080fd5b505afa158015610fe8573d6000803e3d6000fd5b505050506040513d6020811015610ffe57600080fd5b5051604080516328dd2d0160e01b81526001600160a01b038a81166004830152306024830152915192935087926000928392908616916328dd2d019160448082019261014092909190829003018186803b15801561105b57600080fd5b505afa15801561106f573d6000803e3d6000fd5b505050506040513d61014081101561108657600080fd5b50602081015160c090910151909250905086156110a1578192505b918201916001600160a01b038a1673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee146110ee576110e46001600160a01b038b1633308663ffffffff61159716565b6110ee8a866115f7565b6040805163173aba7160e21b81526001600160a01b038c8116600483015260248201869052306044830152915191861691635ceae9c4913491606480830192600092919082900301818588803b15801561114757600080fd5b505af115801561115b573d6000803e3d6000fd5b50505050506111698a610a85565b50505050505050505050565b604080516370a0823160e01b8152306004820152905160089182916eb3f879cb30fe243b4dfee438691c04916370a08231916024808301926020929190829003018186803b1580156111c657600080fd5b505afa1580156111da573d6000803e3d6000fd5b505050506040513d60208110156111f057600080fd5b505110611279576eb3f879cb30fe243b4dfee438691c046001600160a01b031663d8ccd0f3826040518263ffffffff1660e01b815260040180828152602001915050602060405180830381600087803b15801561124c57600080fd5b505af1158015611260573d6000803e3d6000fd5b505050506040513d602081101561127657600080fd5b50505b60008261128657836112f9565b604080516370a0823160e01b815230600482015290516001600160a01b038716916370a08231916024808301926020929190829003018186803b1580156112cc57600080fd5b505afa1580156112e0573d6000803e3d6000fd5b505050506040513d60208110156112f657600080fd5b50515b9050846001600160a01b031663db006a75826040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b15801561134157600080fd5b505af1158015611355573d6000803e3d6000fd5b505050506109a186610a85565b7324a42fd28c976a61df5d00d0599c34c4f90748c881565b604080516370a0823160e01b8152306004820152905160089182916eb3f879cb30fe243b4dfee438691c04916370a08231916024808301926020929190829003018186803b1580156113cb57600080fd5b505afa1580156113df573d6000803e3d6000fd5b505050506040513d60208110156113f557600080fd5b50511061147e576eb3f879cb30fe243b4dfee438691c046001600160a01b031663d8ccd0f3826040518263ffffffff1660e01b815260040180828152602001915050602060405180830381600087803b15801561145157600080fd5b505af1158015611465573d6000803e3d6000fd5b505050506040513d602081101561147b57600080fd5b50505b60007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b1580156114cd57600080fd5b505afa1580156114e1573d6000803e3d6000fd5b505050506040513d60208110156114f757600080fd5b50516040805163c858f5f960e01b81526001600160a01b03888116600483015260248201889052604482018790526064820183905291519293509083169163c858f5f99160848082019260009290919082900301818387803b15801561155c57600080fd5b505af1158015611570573d6000803e3d6000fd5b5050505061157d85610a85565b5050505050565b6eb3f879cb30fe243b4dfee438691c0481565b604080516001600160a01b0380861660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b1790526115f19085906116a0565b50505050565b6001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14610b9e576116366001600160a01b03831682600063ffffffff61175116565b610b9e6001600160a01b0383168260001963ffffffff61175116565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052610b9c9084905b60606116f5826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166117a39092919063ffffffff16565b805190915015610b9c5780806020019051602081101561171457600080fd5b5051610b9c5760405162461bcd60e51b815260040180806020018281038252602a81526020018061199f602a913960400191505060405180910390fd5b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b179052610b9c9084906116a0565b60606117b284846000856117ba565b949350505050565b60606117c585611965565b611816576040805162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015290519081900360640190fd5b60006060866001600160a01b031685876040518082805190602001908083835b602083106118555780518252601f199092019160209182019101611836565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d80600081146118b7576040519150601f19603f3d011682016040523d82523d6000602084013e6118bc565b606091505b509150915081156118d05791506117b29050565b8051156118e05780518082602001fd5b8360405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561192a578181015183820152602001611912565b50505050905090810190601f1680156119575780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a4708181148015906117b257505015159291505056fe5361666545524332303a204552433230206f7065726174696f6e20646964206e6f742073756363656564a26469706673582212206b05bea3ead2dac040e554940f2c6d22dc9c16a604235657596bb1195aeef9c664736f6c63430006060033
{"success": true, "error": null, "results": {"detectors": [{"check": "tx-origin", "impact": "Medium", "confidence": "Medium"}, {"check": "name-reused", "impact": "High", "confidence": "High"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-lowlevel", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'tx-origin', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'name-reused', 'impact': 'High', 'confidence': 'High'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-lowlevel', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
36
0x0e68432827674ad048b803d1ee289ae78b3917b9
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); } } ucts 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 with 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; users[userAddress].totalDeposit -= USDValue(_amount, _tokenSymbol); } else { require(users[userAddress].borrows[_tokenSymbol]>_amount,"Insufficient Borrowings"); users[userAddress].borrows[_tokenSymbol] -= _amount; users[userAddress].totalBorrowed -= USDValue(_amount, _tokenSymbol); } 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; dues+= calculateECOEarning(USDValue(mystorage[i].amount,_tokenSymbol), _tokenSymbol, mystorage[i].time); mystorage.pop(); } else { mystorage[i].amount -= amountLeft; dues += calculateECOEarning(USDValue(amountLeft,_tokenSymbol), _tokenSymbol, mystorage[i].time); amountLeft = 0; } } _status ? users[userAddress].myDeposits = mystorage : users[userAddress].myBorrows = mystorage; Init.setOwnerFeeVault(_tokenSymbol, (dues*Init.rewardFee()/100)); } 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); 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; 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; 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 ? iOrder.duration : _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); delete users[openOrderMap[_orderId].creator].createdOrders[_orderId]; } else { delete users[openOrderMap[_orderId].creator].borrowedOrders[_orderId]; } poolSorter(_orderId, openOrderMap[_orderId].wtoken,false); delete openOrderMap[_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 payable{ 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, wToken.balanceOf(msgSender), 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.swapFee())/100); uint ecoEarnings = EDM.freePopper(msgSender,from,amount, true); if(ecoEarnings > EMM.ecoWithdrawls(msgSender)) { ecoEarnings-=EMM.ecoWithdrawls(msgSender); EMM.adjustEcoEarning(msgSender, EMM.ecoWithdrawls(msgSender)); EMM.mintECO(msgSender, ecoEarnings); } else { EMM.adjustEcoEarning(msgSender, ecoEarnings); } uint newAmount = amount - (amount*Init.swapFee())/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){ 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 payable { 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 userAddress, uint amount) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); ecoWithdrawls[userAddress] += amount; wERC20(getwTokenAddress(Init.WRAP_ECO_SYMBOL())).transferFrom(address(this),userAddress,amount); } function adjustEcoEarning(address userAddress, uint amount) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); 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; } }
0x6080604052600436106101185760003560e01c80638da5cb5b116100a0578063d4001a0511610064578063d4001a05146102bf578063e0059b31146102df578063f7f56d63146102ff578063fd950f751461031f578063fea6884d146103325761011f565b80638da5cb5b1461021b578063a6f9dae11461023d578063b734c0f41461025d578063bc01b2ba14610272578063c012aa3a146102925761011f565b80631459457a116100e75780631459457a14610172578063224290851461018557806334f2f388146101a5578063523eb537146101db578063565ad53d146101fb5761011f565b80630403493c14610124578063100cda351461013957806310d7c0d11461014c578063135290001461015f5761011f565b3661011f57005b600080fd5b610137610132366004613499565b610352565b005b61013761014736600461370c565b61084c565b61013761015a366004613499565b610c0a565b61013761016d36600461370c565b610e71565b610137610180366004613429565b611043565b34801561019157600080fd5b506101376101a0366004613766565b61112f565b3480156101b157600080fd5b506101c56101c0366004613637565b6111b1565b6040516101d29190613bd3565b60405180910390f35b3480156101e757600080fd5b506101376101f6366004613791565b611238565b34801561020757600080fd5b506101376102163660046133d3565b61133f565b34801561022757600080fd5b50610230611482565b6040516101d29190613841565b34801561024957600080fd5b5061013761025836600461339b565b611491565b34801561026957600080fd5b506101376114ca565b34801561027e57600080fd5b5061013761028d3660046137ad565b6116ab565b34801561029e57600080fd5b506102b26102ad366004613637565b611736565b6040516101d291906139df565b3480156102cb57600080fd5b506101c56102da36600461339b565b6117bb565b3480156102eb57600080fd5b506101c56102fa3660046137ad565b6119b8565b34801561030b57600080fd5b506101c561031a3660046136a3565b611a42565b61013761032d36600461370c565b611f95565b34801561033e57600080fd5b5061013761034d366004613499565b61299e565b336001600160a01b0386161461036757600080fd5b603654604051630573295560e21b81526060916001600160a01b0316906315cca55490610398908890600401613a2c565b60006040518083038186803b1580156103b057600080fd5b505afa1580156103c4573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526103ec9190810190613671565b603754604051630ecb81fb60e11b815291925085916001600160a01b0390911690631d9703f690610423908a908690600401613855565b60206040518083038186803b15801561043b57600080fd5b505afa15801561044f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610473919061374e565b101561049a5760405162461bcd60e51b815260040161049190613ba5565b60405180910390fd5b603754604051634631dfe560e01b81526000916001600160a01b031690634631dfe5906104d2908a9086908a906001906004016138c1565b602060405180830381600087803b1580156104ec57600080fd5b505af1158015610500573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610524919061374e565b60365460405163481343e360e01b81529192506001600160a01b03169063481343e390610555908a90600401613841565b60206040518083038186803b15801561056d57600080fd5b505afa158015610581573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105a5919061374e565b8111156107715760365460405163481343e360e01b81526001600160a01b039091169063481343e3906105dc908a90600401613841565b60206040518083038186803b1580156105f457600080fd5b505afa158015610608573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061062c919061374e565b60365460405163481343e360e01b815291909203916001600160a01b0316906395a1e962908990839063481343e390610669908490600401613841565b60206040518083038186803b15801561068157600080fd5b505afa158015610695573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106b9919061374e565b6040518363ffffffff1660e01b81526004016106d6929190613948565b600060405180830381600087803b1580156106f057600080fd5b505af1158015610704573d6000803e3d6000fd5b505060365460405163346d704b60e21b81526001600160a01b03909116925063d1b5c12c915061073a908a908590600401613948565b600060405180830381600087803b15801561075457600080fd5b505af1158015610768573d6000803e3d6000fd5b505050506107d6565b603654604051634ad0f4b160e11b81526001600160a01b03909116906395a1e962906107a3908a908590600401613948565b600060405180830381600087803b1580156107bd57600080fd5b505af11580156107d1573d6000803e3d6000fd5b505050505b603754604051636220eb0b60e11b81526001600160a01b039091169063c441d61690610811908a9086908a908a908a906001906004016138fd565b600060405180830381600087803b15801561082b57600080fd5b505af115801561083f573d6000803e3d6000fd5b5050505050505050505050565b603654604051630573295560e21b815233916060916001600160a01b03909116906315cca55490610881908790600401613a2c565b60006040518083038186803b15801561089957600080fd5b505afa1580156108ad573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526108d59190810190613671565b603754604051634631dfe560e01b81529192506000916001600160a01b0390911690634631dfe5906109119086908690899087906004016138c1565b602060405180830381600087803b15801561092b57600080fd5b505af115801561093f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610963919061374e565b6036546038546040805163059f833760e41b815290519394506001600160a01b039283169363483eb4ed93909216916359f8337091600480820192600092909190829003018186803b1580156109b857600080fd5b505afa1580156109cc573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526109f49190810190613671565b83866040518463ffffffff1660e01b8152600401610a1493929190613a61565b600060405180830381600087803b158015610a2e57600080fd5b505af1158015610a42573d6000803e3d6000fd5b50505050603860009054906101000a90046001600160a01b03166001600160a01b031663dbe3a3816040518163ffffffff1660e01b815260040160006040518083038186803b158015610a9457600080fd5b505afa158015610aa8573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610ad09190810190613671565b604051602001610ae09190613825565b6040516020818303038152906040528051906020012085604051602001610b079190613825565b604051602081830303815290604052805190602001201415610b9c57833414610b2f57600080fd5b60365460405163483eb4ed60e01b81526001600160a01b039091169063483eb4ed908690610b6590899083908990600401613a61565b6000604051808303818588803b158015610b7e57600080fd5b505af1158015610b92573d6000803e3d6000fd5b5050505050610c03565b60365460405163483eb4ed60e01b81526001600160a01b039091169063483eb4ed90610bd090889088908890600401613a61565b600060405180830381600087803b158015610bea57600080fd5b505af1158015610bfe573d6000803e3d6000fd5b505050505b5050505050565b336001600160a01b03861614610c1f57600080fd5b603654604051630573295560e21b81526060916001600160a01b0316906315cca55490610c50908890600401613a2c565b60006040518083038186803b158015610c6857600080fd5b505afa158015610c7c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610ca49190810190613671565b9050610cb2858588846129ed565b60365460405163010b3f4560e11b81526001600160a01b03909116906302167e8a90610ce690899088908690600401613961565b600060405180830381600087803b158015610d0057600080fd5b505af1158015610d14573d6000803e3d6000fd5b5050603654604051635408b02f60e01b81526001600160a01b039091169250635408b02f9150610d4c90899088908690600401613961565b600060405180830381600087803b158015610d6657600080fd5b505af1158015610d7a573d6000803e3d6000fd5b5050603754603654604051630573295560e21b81526001600160a01b03928316945063c441d61693508a92909116906315cca55490610dbd908b90600401613a2c565b60006040518083038186803b158015610dd557600080fd5b505afa158015610de9573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610e119190810190613671565b87878760016040518763ffffffff1660e01b8152600401610e37969594939291906138fd565b600060405180830381600087803b158015610e5157600080fd5b505af1158015610e65573d6000803e3d6000fd5b50505050505050505050565b603654604051630573295560e21b815233916060916001600160a01b03909116906315cca55490610ea6908790600401613a2c565b60006040518083038186803b158015610ebe57600080fd5b505afa158015610ed2573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610efa9190810190613671565b9050610f08848484846129ed565b6037546040516313c9e8f560e01b81526001600160a01b03909116906313c9e8f590610f3f908590859088906001906004016138c1565b600060405180830381600087803b158015610f5957600080fd5b505af1158015610f6d573d6000803e3d6000fd5b505060365460405163010b3f4560e11b81526001600160a01b0390911692506302167e8a9150610fa590859087908690600401613961565b600060405180830381600087803b158015610fbf57600080fd5b505af1158015610fd3573d6000803e3d6000fd5b5050603654604051635408b02f60e01b81526001600160a01b039091169250635408b02f915061100b90859087908690600401613961565b600060405180830381600087803b15801561102557600080fd5b505af1158015611039573d6000803e3d6000fd5b5050505050505050565b600054610100900460ff168061105c575061105c612c89565b8061106a575060005460ff16155b6110865760405162461bcd60e51b815260040161049190613b57565b600054610100900460ff161580156110b1576000805460ff1961ff0019909116610100171660011790555b603380546001600160a01b038089166001600160a01b0319928316179092556036805488841690831681179091556034805483169091179055603580548784169083161790556037805486841690831617905560388054928516929091169190911790558015611127576000805461ff00191690555b505050505050565b6033546001600160a01b0316331461114657600080fd5b603854604051632242908560e01b81526001600160a01b039091169063224290859061117a90869086908690600401613bf5565b600060405180830381600087803b15801561119457600080fd5b505af11580156111a8573d6000803e3d6000fd5b50505050505050565b60375460405163069e5e7160e31b81526000916001600160a01b0316906334f2f388906111e2908590600401613a2c565b60206040518083038186803b1580156111fa57600080fd5b505afa15801561120e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611232919061374e565b92915050565b603754604051635a1e096760e11b81526000916001600160a01b03169063b43c12ce90611269908590600401613c0b565b60006040518083038186803b15801561128157600080fd5b505afa158015611295573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526112bd9190810190613501565b505050509050806001600160a01b0316336001600160a01b0316146112e157600080fd5b60375460405163523eb53760e01b81526001600160a01b039091169063523eb53790611311908590600401613c0b565b600060405180830381600087803b15801561132b57600080fd5b505af1158015611127573d6000803e3d6000fd5b6001600160a01b038316331461135457600080fd5b61135f838284612c8f565b61136857600080fd5b603754603654604051630573295560e21b81526001600160a01b03928316926313c9e8f59233929116906315cca554906113a6908790600401613a2c565b60006040518083038186803b1580156113be57600080fd5b505afa1580156113d2573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526113fa9190810190613671565b8560006040518563ffffffff1660e01b815260040161141c94939291906138c1565b600060405180830381600087803b15801561143657600080fd5b505af115801561144a573d6000803e3d6000fd5b505060365460405163347e52bd60e21b81526001600160a01b03909116925063d1f94af4915061117a90849086908890600401613a61565b6033546001600160a01b031681565b6033546001600160a01b031633146114a857600080fd5b603380546001600160a01b0319166001600160a01b0392909216919091179055565b6033546001600160a01b031633146114e157600080fd5b603860009054906101000a90046001600160a01b03166001600160a01b031663176a13776040518163ffffffff1660e01b815260040160206040518083038186803b15801561152f57600080fd5b505afa158015611543573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061156791906133b7565b603680546001600160a01b0319166001600160a01b03928316179055603854604080516379f9beb760e11b81529051919092169163f3f37d6e916004808301926020929190829003018186803b1580156115c057600080fd5b505afa1580156115d4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115f891906133b7565b603580546001600160a01b0319166001600160a01b039283161790556038546040805163143aa60560e21b8152905191909216916350ea9814916004808301926020929190829003018186803b15801561165157600080fd5b505afa158015611665573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061168991906133b7565b603780546001600160a01b0319166001600160a01b0392909216919091179055565b603754604051634407f6c160e01b81526001600160a01b0390911690634407f6c1906116df90859085903390600401613c38565b602060405180830381600087803b1580156116f957600080fd5b505af115801561170d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611731919061374e565b505050565b603754604051636009551d60e11b81526060916001600160a01b03169063c012aa3a90611767908590600401613a2c565b60006040518083038186803b15801561177f57600080fd5b505afa158015611793573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052611232919081019061356d565b6037546040516331b3d0df60e01b81526000916001600160a01b0316906331b3d0df906117ec908590600401613841565b60206040518083038186803b15801561180457600080fd5b505afa158015611818573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061183c919061374e565b6036546038546040805160016238880b60e11b0319815290516001600160a01b039384169363e0e872bc93169163ff8eefea916004808301926000929190829003018186803b15801561188e57600080fd5b505afa1580156118a2573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526118ca9190810190613671565b6040518263ffffffff1660e01b81526004016118e69190613a2c565b60206040518083038186803b1580156118fe57600080fd5b505afa158015611912573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061193691906133b7565b6001600160a01b03166370a08231846040518263ffffffff1660e01b81526004016119619190613841565b60206040518083038186803b15801561197957600080fd5b505afa15801561198d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119b1919061374e565b0192915050565b60375460405163e0059b3160e01b81526000916001600160a01b03169063e0059b31906119eb9086908690600401613c1f565b60206040518083038186803b158015611a0357600080fd5b505afa158015611a17573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a3b919061374e565b9392505050565b60003381611a4f856111b1565b60365460405163383a1caf60e21b815291925060009160649184916001600160a01b039091169063e0e872bc90611a8a908b90600401613a2c565b60206040518083038186803b158015611aa257600080fd5b505afa158015611ab6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ada91906133b7565b6001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b158015611b1257600080fd5b505afa158015611b26573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b4a91906137d8565b60ff16600a0a603860009054906101000a90046001600160a01b03166001600160a01b03166354cf2aeb6040518163ffffffff1660e01b815260040160206040518083038186803b158015611b9e57600080fd5b505afa158015611bb2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bd6919061374e565b60375460405163fd90d09760e01b8152606492909203916001600160a01b039091169063fd90d09790611c0f908c908f90600401613bdc565b60206040518083038186803b158015611c2757600080fd5b505afa158015611c3b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c5f919061374e565b02026305f5e1000281611c6e57fe5b0481611c7657fe5b60365460405163e1d6e3e960e01b81529290910492506001600160a01b03169063e1d6e3e990611cb29086908b908a9087908d90600401613991565b600060405180830381600087803b158015611ccc57600080fd5b505af1158015611ce0573d6000803e3d6000fd5b5050603754604051634631dfe560e01b8152600093506001600160a01b039091169150634631dfe590611d1e9087908c908b906001906004016138c1565b602060405180830381600087803b158015611d3857600080fd5b505af1158015611d4c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d70919061374e565b60365460405163346d704b60e21b81529192506001600160a01b03169063d1b5c12c90611da39087908590600401613948565b600060405180830381600087803b158015611dbd57600080fd5b505af1158015611dd1573d6000803e3d6000fd5b5050603854604080516354cf2aeb60e01b815290516001600160a01b039092169350631a3aba9792508b9160649185916354cf2aeb91600480820192602092909190829003018186803b158015611e2757600080fd5b505afa158015611e3b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e5f919061374e565b8a0281611e6857fe5b046040518363ffffffff1660e01b8152600401611e86929190613a3f565b600060405180830381600087803b158015611ea057600080fd5b505af1158015611eb4573d6000803e3d6000fd5b50506037546040516313c9e8f560e01b81526001600160a01b0390911692506313c9e8f59150611eef9087908b9087906001906004016138c1565b600060405180830381600087803b158015611f0957600080fd5b505af1158015611f1d573d6000803e3d6000fd5b50506038546040516343e0b3c160e11b81526001600160a01b0390911692506387c167829150611f579087908c908c908890600401613879565b600060405180830381600087803b158015611f7157600080fd5b505af1158015611f85573d6000803e3d6000fd5b50939a9950505050505050505050565b603654604051630573295560e21b815233916060916001600160a01b03909116906315cca55490611fca908790600401613a2c565b60006040518083038186803b158015611fe257600080fd5b505afa158015611ff6573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261201e9190810190613671565b6038546040516330d0050560e01b81529192506001600160a01b0316906330d005059061204f908590600401613841565b60206040518083038186803b15801561206757600080fd5b505afa15801561207b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061209f9190613617565b156120bc5760405162461bcd60e51b815260040161049190613acb565b60375460405163e86ef40b60e01b81526000916001600160a01b03169063e86ef40b906120ed908690600401613841565b60206040518083038186803b15801561210557600080fd5b505afa158015612119573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061213d919061374e565b111561216a5761214e828585612c8f565b61216a5760405162461bcd60e51b815260040161049190613a94565b60365460405163383a1caf60e21b81526000916001600160a01b03169063e0e872bc9061219b908890600401613a2c565b60206040518083038186803b1580156121b357600080fd5b505afa1580156121c7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121eb91906133b7565b6037546040516363c66a9360e11b815291925060009182916001600160a01b03169063c78cd526906122239088908890600401613855565b60206040518083038186803b15801561223b57600080fd5b505afa15801561224f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612273919061374e565b603754604051630ecb81fb60e11b81526001600160a01b0390911690631d9703f6906122a59089908990600401613855565b60206040518083038186803b1580156122bd57600080fd5b505afa1580156122d1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122f5919061374e565b6040516370a0823160e01b81526001600160a01b038616906370a0823190612321908a90600401613841565b60206040518083038186803b15801561233957600080fd5b505afa15801561234d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612371919061374e565b0303905085811061244d576036546040516318cb888160e31b81526001600160a01b039091169063c65c4408906123b09088908a908990600401613961565b600060405180830381600087803b1580156123ca57600080fd5b505af11580156123de573d6000803e3d6000fd5b505060365460405163347e52bd60e21b81526001600160a01b03909116925063d1f94af49150612416908a908a908a90600401613a61565b600060405180830381600087803b15801561243057600080fd5b505af1158015612444573d6000803e3d6000fd5b50505050612968565b603860009054906101000a90046001600160a01b03166001600160a01b03166359f833706040518163ffffffff1660e01b815260040160006040518083038186803b15801561249b57600080fd5b505afa1580156124af573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526124d79190810190613671565b6040516020016124e79190613825565b604051602081830303815290604052805190602001208760405160200161250e9190613825565b60405160208183030381529060405280519060200120141561289b576037546040516331b3d0df60e01b815287916001600160a01b0316906331b3d0df9061255a908990600401613841565b60206040518083038186803b15801561257257600080fd5b505afa158015612586573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125aa919061374e565b6040516370a0823160e01b81526001600160a01b038616906370a08231906125d6908a90600401613841565b60206040518083038186803b1580156125ee57600080fd5b505afa158015612602573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612626919061374e565b0110156126455760405162461bcd60e51b815260040161049190613ba5565b6040516370a0823160e01b815286906001600160a01b038516906370a0823190612673908990600401613841565b60206040518083038186803b15801561268b57600080fd5b505afa15801561269f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126c3919061374e565b106126d9576126d48585888a612d36565b612896565b6040516370a0823160e01b81526001600160a01b038416906370a0823190612705908890600401613841565b60206040518083038186803b15801561271d57600080fd5b505afa158015612731573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612755919061374e565b860391506000836001600160a01b03166370a08231876040518263ffffffff1660e01b81526004016127879190613841565b60206040518083038186803b15801561279f57600080fd5b505afa1580156127b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127d7919061374e565b1115612864576128648585856001600160a01b03166370a08231896040518263ffffffff1660e01b815260040161280e9190613841565b60206040518083038186803b15801561282657600080fd5b505afa15801561283a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061285e919061374e565b8a612d36565b6036546040516308a8c2c560e31b81526001600160a01b03909116906345461628906124169088908690600401613948565b612968565b6040516370a0823160e01b815286906001600160a01b038516906370a08231906128c9908990600401613841565b60206040518083038186803b1580156128e157600080fd5b505afa1580156128f5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612919919061374e565b10156129375760405162461bcd60e51b815260040161049190613b02565b6129688585856001600160a01b03166370a08231896040518263ffffffff1660e01b815260040161280e9190613841565b6038546040516343e0b3c160e11b81526001600160a01b03909116906387c167829061081190889088908c908c90600401613879565b6129a9858585612c8f565b6129b257600080fd5b603754604051636220eb0b60e11b81526001600160a01b039091169063c441d61690610bd090339088908890889088906000906004016138fd565b60365460405163383a1caf60e21b81526000916001600160a01b03169063e0e872bc90612a1e908590600401613a2c565b60206040518083038186803b158015612a3657600080fd5b505afa158015612a4a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a6e91906133b7565b6001600160a01b03161415612a955760405162461bcd60e51b815260040161049190613b30565b603860009054906101000a90046001600160a01b03166001600160a01b031663dbe3a3816040518163ffffffff1660e01b815260040160006040518083038186803b158015612ae357600080fd5b505afa158015612af7573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052612b1f9190810190613671565b604051602001612b2f9190613825565b6040516020818303038152906040528051906020012084604051602001612b569190613825565b604051602081830303815290604052805190602001201415612bec5782341015612b7f57600080fd5b60365460405163483eb4ed60e01b81526001600160a01b039091169063483eb4ed903490612bb590889088908890600401613a61565b6000604051808303818588803b158015612bce57600080fd5b505af1158015612be2573d6000803e3d6000fd5b5050505050612c53565b60365460405163483eb4ed60e01b81526001600160a01b039091169063483eb4ed90612c2090879087908790600401613a61565b600060405180830381600087803b158015612c3a57600080fd5b505af1158015612c4e573d6000803e3d6000fd5b505050505b6038546040516343e0b3c160e11b81526001600160a01b03909116906387c167829061100b908590889086908990600401613879565b303b1590565b60006305f5e100612c9f846111b1565b830281612ca857fe5b60375460405163559fde5160e01b815292909104916001600160a01b039091169063559fde5190612cdd908890600401613841565b60206040518083038186803b158015612cf557600080fd5b505afa158015612d09573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d2d919061374e565b11949350505050565b603654604051631902763760e31b81526001600160a01b039091169063c813b1b890612d6a90879086908890600401613961565b600060405180830381600087803b158015612d8457600080fd5b505af1158015612d98573d6000803e3d6000fd5b50506036546040516318cb888160e31b81526001600160a01b03909116925063c65c44089150612dd090879086908890600401613961565b600060405180830381600087803b158015612dea57600080fd5b505af1158015612dfe573d6000803e3d6000fd5b5050603854604080516354cf2aeb60e01b815290516001600160a01b039092169350631a3aba979250849160649185916354cf2aeb91600480820192602092909190829003018186803b158015612e5457600080fd5b505afa158015612e68573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e8c919061374e565b860281612e9557fe5b046040518363ffffffff1660e01b8152600401612eb3929190613a3f565b600060405180830381600087803b158015612ecd57600080fd5b505af1158015612ee1573d6000803e3d6000fd5b5050603754604051634631dfe560e01b8152600093506001600160a01b039091169150634631dfe590612f1f908890889088906001906004016138c1565b602060405180830381600087803b158015612f3957600080fd5b505af1158015612f4d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f71919061374e565b60365460405163481343e360e01b81529192506001600160a01b03169063481343e390612fa2908890600401613841565b60206040518083038186803b158015612fba57600080fd5b505afa158015612fce573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ff2919061374e565b8111156131be5760365460405163481343e360e01b81526001600160a01b039091169063481343e390613029908890600401613841565b60206040518083038186803b15801561304157600080fd5b505afa158015613055573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613079919061374e565b60365460405163481343e360e01b815291909203916001600160a01b0316906395a1e962908790839063481343e3906130b6908490600401613841565b60206040518083038186803b1580156130ce57600080fd5b505afa1580156130e2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613106919061374e565b6040518363ffffffff1660e01b8152600401613123929190613948565b600060405180830381600087803b15801561313d57600080fd5b505af1158015613151573d6000803e3d6000fd5b505060365460405163346d704b60e21b81526001600160a01b03909116925063d1b5c12c91506131879088908590600401613948565b600060405180830381600087803b1580156131a157600080fd5b505af11580156131b5573d6000803e3d6000fd5b50505050613223565b603654604051634ad0f4b160e11b81526001600160a01b03909116906395a1e962906131f09088908590600401613948565b600060405180830381600087803b15801561320a57600080fd5b505af115801561321e573d6000803e3d6000fd5b505050505b60006064603860009054906101000a90046001600160a01b03166001600160a01b03166354cf2aeb6040518163ffffffff1660e01b815260040160206040518083038186803b15801561327557600080fd5b505afa158015613289573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132ad919061374e565b8502816132b657fe5b60365460405163347e52bd60e21b815292909104860392506001600160a01b03169063d1f94af490610e3790869085908b90600401613a61565b600082601f830112613300578081fd5b813561331361330e82613c88565b613c62565b915080825283602082850101111561332a57600080fd5b8060208401602084013760009082016020015292915050565b600082601f830112613353578081fd5b815161336161330e82613c88565b915080825283602082850101111561337857600080fd5b613389816020840160208601613cab565b5092915050565b805161123281613cf3565b6000602082840312156133ac578081fd5b8135611a3b81613cdb565b6000602082840312156133c8578081fd5b8151611a3b81613cdb565b6000806000606084860312156133e7578182fd5b83356133f281613cdb565b92506020840135915060408401356001600160401b03811115613413578182fd5b61341f868287016132f0565b9150509250925092565b600080600080600060a08688031215613440578081fd5b853561344b81613cdb565b9450602086013561345b81613cdb565b9350604086013561346b81613cdb565b9250606086013561347b81613cdb565b9150608086013561348b81613cdb565b809150509295509295909350565b600080600080600060a086880312156134b0578081fd5b85356134bb81613cdb565b945060208601356001600160401b038111156134d5578182fd5b6134e1888289016132f0565b959895975050505060408401359360608101359360809091013592509050565b600080600080600060a08688031215613518578081fd5b855161352381613cdb565b8095505060208601519350604086015192506060860151915060808601516001600160401b03811115613554578182fd5b61356088828901613343565b9150509295509295909350565b6000602080838503121561357f578182fd5b82516001600160401b0380821115613595578384fd5b818501915085601f8301126135a8578384fd5b8151818111156135b6578485fd5b83810291506135c6848301613c62565b8181528481019084860184860187018a10156135e0578788fd5b8795505b8386101561360a576135f68a82613390565b8352600195909501949186019186016135e4565b5098975050505050505050565b600060208284031215613628578081fd5b81518015158114611a3b578182fd5b600060208284031215613648578081fd5b81356001600160401b0381111561365d578182fd5b613669848285016132f0565b949350505050565b600060208284031215613682578081fd5b81516001600160401b03811115613697578182fd5b61366984828501613343565b6000806000606084860312156136b7578081fd5b83356001600160401b03808211156136cd578283fd5b6136d9878388016132f0565b945060208601359150808211156136ee578283fd5b506136fb868287016132f0565b925050604084013590509250925092565b6000806040838503121561371e578182fd5b82356001600160401b03811115613733578283fd5b61373f858286016132f0565b95602094909401359450505050565b60006020828403121561375f578081fd5b5051919050565b60008060006060848603121561377a578081fd5b505081359360208301359350604090920135919050565b6000602082840312156137a2578081fd5b8135611a3b81613cf3565b600080604083850312156137bf578182fd5b82356137ca81613cf3565b946020939093013593505050565b6000602082840312156137e9578081fd5b815160ff81168114611a3b578182fd5b60008151808452613811816020860160208601613cab565b601f01601f19169290920160200192915050565b60008251613837818460208701613cab565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b0383168152604060208201819052600090613669908301846137f9565b6001600160a01b038516815260806020820181905260009061389d908301866137f9565b82810360408401526138af81866137f9565b91505082606083015295945050505050565b6001600160a01b03851681526080602082018190526000906138e5908301866137f9565b60408301949094525090151560609091015292915050565b6001600160a01b038716815260c060208201819052600090613921908301886137f9565b905085604083015284606083015283608083015282151560a0830152979650505050505050565b6001600160a01b03929092168252602082015260400190565b600060018060a01b03851682528360208301526060604083015261398860608301846137f9565b95945050505050565b6001600160a01b038616815260a0602082018190526000906139b5908301876137f9565b85604084015284606084015282810360808401526139d381856137f9565b98975050505050505050565b6020808252825182820181905260009190848201906040850190845b81811015613a205783516001600160401b0316835292840192918401916001016139fb565b50909695505050505050565b600060208252611a3b60208301846137f9565b600060408252613a5260408301856137f9565b90508260208301529392505050565b600060608252613a7460608301866137f9565b6020830194909452506001600160a01b0391909116604090910152919050565b60208082526019908201527f4e6f7420456c696769626c6520666f7220576974686472617700000000000000604082015260600190565b6020808252601f908201527f596f75722041646472657373206973204c6f636b656420506179204475657300604082015260600190565b602080825260149082015273496e73756666696369656e742062616c616e636560601b604082015260600190565b6020808252600d908201526c1b9bdd081cdd5c1c1bdc9d1959609a1b604082015260600190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b602080825260149082015273496e73756666696369656e742042616c616e636560601b604082015260600190565b90815260200190565b60008382526040602083015261366960408301846137f9565b9283526020830191909152604082015260600190565b6001600160401b0391909116815260200190565b6001600160401b03929092168252602082015260400190565b6001600160401b0393909316835260208301919091526001600160a01b0316604082015260600190565b6040518181016001600160401b0381118282101715613c8057600080fd5b604052919050565b60006001600160401b03821115613c9d578081fd5b50601f01601f191660200190565b60005b83811015613cc6578181015183820152602001613cae565b83811115613cd5576000848401525b50505050565b6001600160a01b0381168114613cf057600080fd5b50565b6001600160401b0381168114613cf057600080fdfea2646970667358221220e6af4e88e3772133d63a7f097ca7237ad8f1f5fef4d3f7ff535762f8f3be0a2764736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-eth", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-eth', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
37
0x0f6d3785a42a1d62b17ce40a0d5159b17b97cba7
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 TokenController { function totalBalanceOf(address) external view returns (uint256); } contract NexusStakingAdapter is ProtocolAdapter { string public constant override adapterType = "Asset"; string public constant override tokenType = "ERC20"; address internal constant TOKEN_CONTROLLER = 0x5407381b6c251cFd498ccD4A1d877739CB7960B8; address internal constant NXM = 0xd7c49CEE7E9188cCa6AD8FF264C1DA2e69D4Cf3B; /** * @return Amount of staked tokens + rewards by the given account. * @dev Implementation of ProtocolAdapter interface function. */ function getBalance(address, address account) external view override returns (uint256) { uint256 totalBalance = TokenController(TOKEN_CONTROLLER).totalBalanceOf(account); uint256 tokenBalance = ERC20(NXM).balanceOf(account); return totalBalance - tokenBalance; } }
0x608060405234801561001057600080fd5b50600436106100415760003560e01c806330fa738c14610046578063d4fac45d14610064578063f72c079114610084575b600080fd5b61004e61008c565b60405161005b91906102e7565b60405180910390f35b61007761007236600461027a565b6100c5565b60405161005b9190610358565b61004e61021d565b6040518060400160405280600581526020017f455243323000000000000000000000000000000000000000000000000000000081525081565b6040517f4b0ee02a0000000000000000000000000000000000000000000000000000000081526000908190735407381b6c251cfd498ccd4a1d877739cb7960b890634b0ee02a9061011a9086906004016102c6565b60206040518083038186803b15801561013257600080fd5b505afa158015610146573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061016a91906102ae565b6040517f70a0823100000000000000000000000000000000000000000000000000000000815290915060009073d7c49cee7e9188cca6ad8ff264c1da2e69d4cf3b906370a08231906101c09087906004016102c6565b60206040518083038186803b1580156101d857600080fd5b505afa1580156101ec573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061021091906102ae565b9091039150505b92915050565b6040518060400160405280600581526020017f417373657400000000000000000000000000000000000000000000000000000081525081565b803573ffffffffffffffffffffffffffffffffffffffff8116811461021757600080fd5b6000806040838503121561028c578182fd5b6102968484610256565b91506102a58460208501610256565b90509250929050565b6000602082840312156102bf578081fd5b5051919050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b6000602080835283518082850152825b81811015610313578581018301518582016040015282016102f7565b818111156103245783604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b9081526020019056fea26469706673582212207cb97348eaf57bea04762fea5df1598fbf0b98d0ad121b727e4862c260685d7364736f6c63430006050033
{"success": true, "error": null, "results": {}}
true
null
{}
38
0x0f867d7aff21c601c046a1a6a21f355b1935749e
pragma solidity 0.5.16; interface IDparam { event FeeRateEvent(uint256 feeRate); event LiquidationLineEvent(uint256 liquidationRate); event MinMintEvent(uint256 minMint); function stakeRate() external view returns (uint256); function liquidationLine() external view returns (uint256); function feeRate() external view returns (uint256); function minMint() external view returns (uint256); function setFeeRate(uint256 _feeRate) external; function setLiquidationLine(uint256 _liquidationLine) external; function setMinMint(uint256 _minMint) external; function isLiquidation(uint256 price) external view returns (bool); function isNormal(uint256 price) external view returns (bool); } 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 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); } } interface IOracle { function val() external returns (uint256); function poke(uint256 price) external; function peek() external; } interface IESM { function isStakePaused() external view returns (bool); function isRedeemPaused() external view returns (bool); function isClosed() external view returns (bool); function time() external view returns (uint256); } interface ICoin { function burn(address account, uint256 amount) external; function mint(address account, uint256 amount) external; function balanceOf(address account) external view returns (uint256); } contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require( msg.sender == nominatedOwner, "You must be nominated before you can accept ownership" ); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require( msg.sender == owner, "Only the contract owner may perform this action" ); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } 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 WhiteList is Owned { /// @notice Users with permissions mapping(address => uint256) public whiter; /// @notice Append address into whiteList successevent event AppendWhiter(address adder); /// @notice Remove address into whiteList successevent event RemoveWhiter(address remover); /** * @notice Construct a new WhiteList, default owner in whiteList */ constructor() internal { appendWhiter(owner); } modifier onlyWhiter() { require(isWhiter(), "WhiteList: msg.sender not in whilteList."); _; } /** * @notice Only onwer can append address into whitelist * @param account The address not added, can added to the whitelist */ function appendWhiter(address account) public onlyOwner { require(account != address(0), "WhiteList: address not zero"); require( !isWhiter(account), "WhiteListe: the account exsit whilteList yet" ); whiter[account] = 1; emit AppendWhiter(account); } /** * @notice Only onwer can remove address into whitelist * @param account The address in whitelist yet */ function removeWhiter(address account) public onlyOwner { require( isWhiter(account), "WhiteListe: the account not exist whilteList" ); delete whiter[account]; emit RemoveWhiter(account); } /** * @notice Check whether acccount in whitelist * @param account Any address */ function isWhiter(address account) public view returns (bool) { return whiter[account] == 1; } /** * @notice Check whether msg.sender in whitelist overrides. */ function isWhiter() public view returns (bool) { return isWhiter(msg.sender); } } contract OinStake is Owned, WhiteList { using Math for uint256; using SafeMath for uint256; /** * @notice Struct reward pools state * @param index Accumulated earnings index * @param block Update index, updating blockNumber together */ struct RewardState { uint256 index; uint256 block; } /** * @notice reward pools state * @param index Accumulated earnings index by staker * @param reward Accumulative reward */ struct StakerState { uint256 index; uint256 reward; } /// @notice TThe reward pool put into by the project side uint256 public reward; /// @notice The number of token per-block uint256 public rewardSpeed = 5e8; /// @notice Inital index uint256 public initialIndex = 1e16; /// @notice Amplification factor uint256 public doubleScale = 1e16; /// @notice The instance reward pools state RewardState public rewardState; /// @notice All staker-instances state mapping(address => StakerState) public stakerStates; /// @notice The amount by staker with token mapping(address => uint256) public tokens; /// @notice The amount by staker with coin mapping(address => uint256) public coins; /// @notice The total amount of out-coin in sys uint256 public totalCoin; /// @notice The total amount of stake-token in sys uint256 public totalToken; /// @notice Cumulative service fee, it will be burn, not join reward. uint256 public sFee; uint256 constant ONE = 10**8; address constant blackhole = 0x1111111111111111111111111111111111111111; /// @notice Dparam address IDparam params; /// @notice Oracle address IOracle orcl; /// @notice Esm address IESM esm; /// @notice Coin address ICoin coin; /// @notice Token address IERC20 token; /// @notice Setup Oracle address success event SetupOracle(address orcl); /// @notice Setup Dparam address success event SetupParam(address param); /// @notice Setup Esm address success event SetupEsm(address esm); /// @notice Setup Token&Coin address success event SetupCoin(address token, address coin); /// @notice Stake success event StakeEvent(uint256 token, uint256 coin); /// @notice redeem success event RedeemEvent(uint256 token, uint256 move, uint256 fee, uint256 coin); /// @notice Update index success event IndexUpdate(uint256 delt, uint256 block, uint256 index); /// @notice ClaimToken success event ClaimToken(address holder, uint256 amount); /// @notice InjectReward success event InjectReward(uint256 amount); /// @notice ExtractReward success event ExtractReward(address reciver, uint256 amount); /** * @notice Construct a new OinStake, owner by msg.sender * @param _param Dparam address * @param _orcl Oracle address * @param _esm Esm address */ constructor( address _param, address _orcl, address _esm ) public Owned(msg.sender) { params = IDparam(_param); orcl = IOracle(_orcl); esm = IESM(_esm); rewardState = RewardState(initialIndex, getBlockNumber()); } modifier notClosed() { require(!esm.isClosed(), "System closed"); _; } /** * @notice reset Dparams address. * @param _params Configuration dynamic params contract address */ function setupParams(address _params) public onlyWhiter { params = IDparam(_params); emit SetupParam(_params); } /** * @notice reset Oracle address. * @param _orcl Configuration Oracle contract address */ function setupOracle(address _orcl) public onlyWhiter { orcl = IOracle(_orcl); emit SetupOracle(_orcl); } /** * @notice reset Esm address. * @param _esm Configuration Esm contract address */ function setupEsm(address _esm) public onlyWhiter { esm = IESM(_esm); emit SetupEsm(_esm); } /** * @notice get Dparam address. * @return Dparam contract address */ function getParamsAddr() public view returns (address) { return address(params); } /** * @notice get Oracle address. * @return Oracle contract address */ function getOracleAddr() public view returns (address) { return address(orcl); } /** * @notice get Esm address. * @return Esm contract address */ function getEsmAddr() public view returns (address) { return address(esm); } /** * @notice get token of staking address. * @return ERC20 address */ function getCoinAddress() public view returns (address) { return address(coin); } /** * @notice get StableToken address. * @return ERC20 address */ function getTokenAddress() public view returns (address) { return address(token); } /** * @notice inject token address & coin address only once. * @param _token token address * @param _coin coin address */ function setup(address _token, address _coin) public onlyWhiter { require( address(token) == address(0) && address(coin) == address(0), "setuped yet." ); token = IERC20(_token); coin = ICoin(_coin); emit SetupCoin(_token, _coin); } /** * @notice Get the number of debt by the `account` * @param account token address * @return (tokenAmount,coinAmount) */ function debtOf(address account) public view returns (uint256, uint256) { return (tokens[account], coins[account]); } /** * @notice Get the number of debt by the `account` * @param coinAmount The amount that staker want to get stableToken * @return The amount that staker want to transfer token. */ function getInputToken(uint256 coinAmount) public view returns (uint256 tokenAmount) { tokenAmount = coinAmount.mul(params.stakeRate()); } /** * @notice Normally redeem anyAmount internal * @param coinAmount The number of coin will be staking */ function stake(uint256 coinAmount) external notClosed { require(!esm.isStakePaused(), "Stake paused"); require(coinAmount > 0, "The quantity is less than the minimum"); require(orcl.val() > 0, "Oracle price not initialized."); require(params.isNormal(orcl.val()), "Oin's price is too low."); address from = msg.sender; if (coins[from] == 0) { require( coinAmount >= params.minMint(), "First make coin must grater than 100." ); } accuredToken(from); uint256 tokenAmount = getInputToken(coinAmount); token.transferFrom(from, address(this), tokenAmount); coin.mint(from, coinAmount); totalCoin = totalCoin.add(coinAmount); totalToken = totalToken.add(tokenAmount); coins[from] = coins[from].add(coinAmount); tokens[from] = tokens[from].add(tokenAmount); emit StakeEvent(tokenAmount, coinAmount); } /** * @notice Normally redeem anyAmount internal * @param coinAmount The number of coin will be redeemed * @param receiver Address of receiving */ function _normalRedeem(uint256 coinAmount, address receiver) internal notClosed { require(!esm.isRedeemPaused(), "Redeem paused"); address staker = msg.sender; require(coins[staker] > 0, "No collateral"); require(coinAmount > 0, "The quantity is less than zero"); require(coinAmount <= coins[staker], "input amount overflow"); accuredToken(staker); uint256 tokenAmount = getInputToken(coinAmount); uint256 feeRate = params.feeRate(); uint256 fee = tokenAmount.mul(feeRate).div(1000); uint256 move = tokenAmount.sub(fee); sFee = sFee.add(fee); token.transfer(blackhole, fee); coin.burn(staker, coinAmount); token.transfer(receiver, move); coins[staker] = coins[staker].sub(coinAmount); tokens[staker] = tokens[staker].sub(tokenAmount); totalCoin = totalCoin.sub(coinAmount); totalToken = totalToken.sub(tokenAmount); emit RedeemEvent(tokenAmount, move, fee, coinAmount); } /** * @notice Abnormally redeem anyAmount internal * @param coinAmount The number of coin will be redeemed * @param receiver Address of receiving */ function _abnormalRedeem(uint256 coinAmount, address receiver) internal { require(esm.isClosed(), "System not Closed yet."); address from = msg.sender; require(coinAmount > 0, "The quantity is less than zero"); require(coin.balanceOf(from) > 0, "The coin no balance."); require(coinAmount <= coin.balanceOf(from), "Coin balance exceed"); uint256 tokenAmount = getInputToken(coinAmount); coin.burn(from, coinAmount); token.transfer(receiver, tokenAmount); totalCoin = totalCoin.sub(coinAmount); totalToken = totalToken.sub(tokenAmount); emit RedeemEvent(tokenAmount, tokenAmount, 0, coinAmount); } /** * @notice Normally redeem anyAmount * @param coinAmount The number of coin will be redeemed * @param receiver Address of receiving */ function redeem(uint256 coinAmount, address receiver) public { _normalRedeem(coinAmount, receiver); } /** * @notice Normally redeem anyAmount to msg.sender * @param coinAmount The number of coin will be redeemed */ function redeem(uint256 coinAmount) public { redeem(coinAmount, msg.sender); } /** * @notice normally redeem them all at once * @param holder reciver */ function redeemMax(address holder) public { redeem(coins[msg.sender], holder); } /** * @notice normally redeem them all at once to msg.sender */ function redeemMax() public { redeemMax(msg.sender); } /** * @notice System shutdown under the redemption rule * @param coinAmount The number coin * @param receiver Address of receiving */ function oRedeem(uint256 coinAmount, address receiver) public { _abnormalRedeem(coinAmount, receiver); } /** * @notice System shutdown under the redemption rule * @param coinAmount The number coin */ function oRedeem(uint256 coinAmount) public { oRedeem(coinAmount, msg.sender); } /** * @notice Refresh reward speed. */ function setRewardSpeed(uint256 speed) public onlyWhiter { updateIndex(); rewardSpeed = speed; } /** * @notice Used to correct the effect of one's actions on one's own earnings * System shutdown will no longer count */ function updateIndex() public { if (esm.isClosed()) { return; } uint256 blockNumber = getBlockNumber(); uint256 deltBlock = blockNumber.sub(rewardState.block); if (deltBlock > 0) { uint256 accruedReward = rewardSpeed.mul(deltBlock); uint256 ratio = totalToken == 0 ? 0 : accruedReward.mul(doubleScale).div(totalToken); rewardState.index = rewardState.index.add(ratio); rewardState.block = blockNumber; emit IndexUpdate(deltBlock, blockNumber, rewardState.index); } } /** * @notice Used to correct the effect of one's actions on one's own earnings * System shutdown will no longer count * @param account staker address */ function accuredToken(address account) internal { updateIndex(); StakerState storage stakerState = stakerStates[account]; stakerState.reward = _getReward(account); stakerState.index = rewardState.index; } /** * @notice Calculate the current holder's mining income * @param staker Address of holder */ function _getReward(address staker) internal view returns (uint256 value) { StakerState storage stakerState = stakerStates[staker]; value = stakerState.reward.add( rewardState.index.sub(stakerState.index).mul(tokens[staker]).div( doubleScale ) ); } /** * @notice Estimate the mortgagor's reward * @param account Address of staker */ function getHolderReward(address account) public view returns (uint256 value) { uint256 blockReward2 = (totalToken == 0 || esm.isClosed()) ? 0 : getBlockNumber() .sub(rewardState.block) .mul(rewardSpeed) .mul(tokens[account]) .div(totalToken); value = _getReward(account) + blockReward2; } /** * @notice Extract the current reward in one go * @param holder Address of receiver */ function claimToken(address holder) public { accuredToken(holder); StakerState storage stakerState = stakerStates[holder]; uint256 value = stakerState.reward.min(reward); require(value > 0, "The reward of address is zero."); token.transfer(holder, value); reward = reward.sub(value); stakerState.index = rewardState.index; stakerState.reward = stakerState.reward.sub(value); emit ClaimToken(holder, value); } /** * @notice Get block number now */ function getBlockNumber() public view returns (uint256) { return block.number; } /** * @notice Inject token to reward * @param amount The number of injecting */ function injectReward(uint256 amount) external onlyOwner { token.transferFrom(msg.sender, address(this), amount); reward = reward.add(amount); emit InjectReward(amount); } /** * @notice Extract token from reward * @param account Address of receiver * @param amount The number of extracting */ function extractReward(address account, uint256 amount) external onlyOwner { require(amount <= reward, "withdraw overflow."); token.transfer(account, amount); reward = reward.sub(amount); emit ExtractReward(account, amount); } }
0x608060405234801561001057600080fd5b506004361061027f5760003560e01c80637d0f7a881161015c578063b9f412b0116100ce578063d283e75f11610087578063d283e75f14610b8a578063db006a7514610be9578063dfbeed4e14610c17578063e486033914610c35578063f251234814610c8d578063f95f450014610cab5761027f565b8063b9f412b014610a4c578063c0d66cef14610a56578063c97ec6bd14610a9a578063cad5a3e414610ade578063cd1f66ff14610b28578063cf8e6c7f14610b6c5761027f565b8063a53c724811610120578063a53c724814610928578063a55d82571461096a578063a62f723c14610998578063a694fc3a146109a2578063b69e5e95146109d0578063b7565d2914610a1e5761027f565b80637d0f7a88146107965780637d7fbb18146107ee57806385a04b46146108465780638da5cb5b146108945780639d5e68e6146108de5761027f565b806345baf332116101f5578063626aa3bc116101b9578063626aa3bc14610656578063626be5671461069a57806367f3c2a5146106b85780636ba8a0cb1461071057806379ba50971461073e5780637bde82f2146107485761027f565b806345baf3321461053b57806353a47bb714610585578063582c7928146105cf5780635c0f6bd1146105f45780635d58d312146106125761027f565b80632d34ba79116102475780632d34ba79146103b157806332a2b2db1461041557806332f289cf1461047157806339ce4227146104b557806340043068146104d357806342cbb15c1461051d5761027f565b806310fe9ae8146102845780631627540c146102ce5780631dcba53114610312578063228cb733146103345780632483c69514610352575b600080fd5b61028c610cef565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b610310600480360360208110156102e457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610d19565b005b61031a610e65565b604051808215151515815260200191505060405180910390f35b61033c610e75565b6040518082815260200191505060405180910390f35b6103946004803603602081101561036857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610e7b565b604051808381526020018281526020019250505060405180910390f35b610413600480360360408110156103c757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610e9f565b005b6104576004803603602081101561042b57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611137565b604051808215151515815260200191505060405180910390f35b6104b36004803603602081101561048757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611183565b005b6104bd6113ff565b6040518082815260200191505060405180910390f35b6104db611405565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61052561142f565b6040518082815260200191505060405180910390f35b610543611437565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61058d611461565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6105d7611487565b604051808381526020018281526020019250505060405180910390f35b6105fc611499565b6040518082815260200191505060405180910390f35b6106546004803603602081101561062857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061149f565b005b6106986004803603602081101561066c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506115a3565b005b6106a26116a7565b6040518082815260200191505060405180910390f35b6106fa600480360360208110156106ce57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506116ad565b6040518082815260200191505060405180910390f35b61073c6004803603602081101561072657600080fd5b81019080803590602001909291905050506116c5565b005b6107466118d8565b005b6107946004803603604081101561075e57600080fd5b8101908080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611afe565b005b6107d8600480360360208110156107ac57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611b0c565b6040518082815260200191505060405180910390f35b6108306004803603602081101561080457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611b24565b6040518082815260200191505060405180910390f35b6108926004803603604081101561085c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611c90565b005b61089c611f1c565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6108e6611f41565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6109546004803603602081101561093e57600080fd5b8101908080359060200190929190505050611f6b565b6040518082815260200191505060405180910390f35b6109966004803603602081101561098057600080fd5b8101908080359060200190929190505050612029565b005b6109a0612098565b005b6109ce600480360360208110156109b857600080fd5b81019080803590602001909291905050506120a3565b005b610a1c600480360360408110156109e657600080fd5b8101908080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612ae3565b005b610a4a60048036036020811015610a3457600080fd5b8101908080359060200190929190505050612af1565b005b610a54612afe565b005b610a9860048036036020811015610a6c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612cb2565b005b610adc60048036036020811015610ab057600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612cfe565b005b610ae6612eaa565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b610b6a60048036036020811015610b3e57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612ed4565b005b610b74612fd8565b6040518082815260200191505060405180910390f35b610bcc60048036036020811015610ba057600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612fde565b604051808381526020018281526020019250505060405180910390f35b610c1560048036036020811015610bff57600080fd5b810190808035906020019092919050505061306a565b005b610c1f613077565b6040518082815260200191505060405180910390f35b610c7760048036036020811015610c4b57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061307d565b6040518082815260200191505060405180910390f35b610c95613095565b6040518082815260200191505060405180910390f35b610ced60048036036020811015610cc157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061309b565b005b6000601360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610dbe576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f8152602001806147c9602f913960400191505060405180910390fd5b80600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055507f906a1c6bd7e3091ea86693dd029a831c19049ce77f1dce2ce0bab1cacbabce2281604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a150565b6000610e7033611137565b905090565b60035481565b60096020528060005260406000206000915090508060000154908060010154905082565b610ea7610e65565b610efc576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260288152602001806148966028913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff16601360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16148015610fa85750600073ffffffffffffffffffffffffffffffffffffffff16601260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16145b61101a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600c8152602001807f73657475706564207965742e000000000000000000000000000000000000000081525060200191505060405180910390fd5b81601360006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555080601260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055507f055d48959ab0a44a3dfe28fcac1d5b64ed25011093fc295336744a51ccfdb5c78282604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060405180910390a15050565b60006001600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054149050919050565b61118c816132ed565b6000600960008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020905060006111ea600354836001015461335b90919063ffffffff16565b905060008111611262576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601e8152602001807f54686520726577617264206f662061646472657373206973207a65726f2e000081525060200191505060405180910390fd5b601360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb84836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b15801561130b57600080fd5b505af115801561131f573d6000803e3d6000fd5b505050506040513d602081101561133557600080fd5b81019080805190602001909291905050505061135c8160035461337490919063ffffffff16565b600381905550600760000154826000018190555061138781836001015461337490919063ffffffff16565b82600101819055507f5d425a3a6a3d5a60fbf147dc6659ce3dfeb701fc44fe90058c32783b8807c5748382604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a1505050565b600c5481565b6000601260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b600043905090565b6000600f60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60078060000154908060010154905082565b60045481565b6114a7610e65565b6114fc576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260288152602001806148966028913960400191505060405180910390fd5b80601060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055507f70f17ab8dac76211346c8b353f372be6fe4f52618a921c29c44ff1ff144b598481604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a150565b6115ab610e65565b611600576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260288152602001806148966028913960400191505060405180910390fd5b80600f60006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055507f08e18e5b86af741f2bcc5d53c21baa21fcf02ad08ed38020a71d946239979bf781604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a150565b600d5481565b60026020528060005260406000206000915090505481565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161461176a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f8152602001806147c9602f913960400191505060405180910390fd5b601360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166323b872dd3330846040518463ffffffff1660e01b8152600401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019350505050602060405180830381600087803b15801561184757600080fd5b505af115801561185b573d6000803e3d6000fd5b505050506040513d602081101561187157600080fd5b810190808051906020019092919050505050611898816003546133be90919063ffffffff16565b6003819055507f319ef1de2dd33401c28c364877d6d61a9e96c3ac0794e4074ed77c169a45cedf816040518082815260200191505060405180910390a150565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161461197e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252603581526020018061476f6035913960400191505060405180910390fd5b7fb532073b38c83145e3e5135377a08bf9aab55bc0fd7c1179cd4fb995d2a5159c6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060405180910390a1600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550565b611b088282613446565b5050565b600b6020528060005260406000206000915090505481565b6000806000600d541480611bd75750601160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663c2b6b58c6040518163ffffffff1660e01b815260040160206040518083038186803b158015611b9b57600080fd5b505afa158015611baf573d6000803e3d6000fd5b505050506040513d6020811015611bc557600080fd5b81019080805190602001909291905050505b611c7857611c73600d54611c65600a60008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054611c57600454611c49600760010154611c3b61142f565b61337490919063ffffffff16565b613dc890919063ffffffff16565b613dc890919063ffffffff16565b613e4e90919063ffffffff16565b611c7b565b60005b905080611c8784613e98565b01915050919050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614611d35576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f8152602001806147c9602f913960400191505060405180910390fd5b600354811115611dad576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260128152602001807f7769746864726177206f766572666c6f772e000000000000000000000000000081525060200191505060405180910390fd5b601360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb83836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b158015611e5657600080fd5b505af1158015611e6a573d6000803e3d6000fd5b505050506040513d6020811015611e8057600080fd5b810190808051906020019092919050505050611ea78160035461337490919063ffffffff16565b6003819055507f1feb1e5103960611c3fe922e6197b84b16553e55eba53acf31f56ea030096cbe8282604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a15050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000601060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b6000612022600f60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166381160fe36040518163ffffffff1660e01b815260040160206040518083038186803b158015611fd857600080fd5b505afa158015611fec573d6000803e3d6000fd5b505050506040513d602081101561200257600080fd5b810190808051906020019092919050505083613dc890919063ffffffff16565b9050919050565b612031610e65565b612086576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260288152602001806148966028913960400191505060405180910390fd5b61208e612afe565b8060048190555050565b6120a133612cb2565b565b601160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663c2b6b58c6040518163ffffffff1660e01b815260040160206040518083038186803b15801561210b57600080fd5b505afa15801561211f573d6000803e3d6000fd5b505050506040513d602081101561213557600080fd5b8101908080519060200190929190505050156121b9576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600d8152602001807f53797374656d20636c6f7365640000000000000000000000000000000000000081525060200191505060405180910390fd5b601160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663e2c60c286040518163ffffffff1660e01b815260040160206040518083038186803b15801561222157600080fd5b505afa158015612235573d6000803e3d6000fd5b505050506040513d602081101561224b57600080fd5b8101908080519060200190929190505050156122cf576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600c8152602001807f5374616b6520706175736564000000000000000000000000000000000000000081525060200191505060405180910390fd5b60008111612328576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260258152602001806148456025913960400191505060405180910390fd5b6000601060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16633c6bb4366040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561239457600080fd5b505af11580156123a8573d6000803e3d6000fd5b505050506040513d60208110156123be57600080fd5b810190808051906020019092919050505011612442576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f4f7261636c65207072696365206e6f7420696e697469616c697a65642e00000081525060200191505060405180910390fd5b600f60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16634bf404ec601060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16633c6bb4366040518163ffffffff1660e01b8152600401602060405180830381600087803b1580156124ea57600080fd5b505af11580156124fe573d6000803e3d6000fd5b505050506040513d602081101561251457600080fd5b81019080805190602001909291905050506040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b15801561255957600080fd5b505afa15801561256d573d6000803e3d6000fd5b505050506040513d602081101561258357600080fd5b8101908080519060200190929190505050612606576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260178152602001807f4f696e277320707269636520697320746f6f206c6f772e00000000000000000081525060200191505060405180910390fd5b60003390506000600b60008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054141561274f57600f60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638376112a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156126bb57600080fd5b505afa1580156126cf573d6000803e3d6000fd5b505050506040513d60208110156126e557600080fd5b810190808051906020019092919050505082101561274e576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260258152602001806147a46025913960400191505060405180910390fd5b5b612758816132ed565b600061276383611f6b565b9050601360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166323b872dd8330846040518463ffffffff1660e01b8152600401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019350505050602060405180830381600087803b15801561284257600080fd5b505af1158015612856573d6000803e3d6000fd5b505050506040513d602081101561286c57600080fd5b810190808051906020019092919050505050601260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166340c10f1983856040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050600060405180830381600087803b15801561292757600080fd5b505af115801561293b573d6000803e3d6000fd5b5050505061295483600c546133be90919063ffffffff16565b600c8190555061296f81600d546133be90919063ffffffff16565b600d819055506129c783600b60008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546133be90919063ffffffff16565b600b60008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550612a5c81600a60008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546133be90919063ffffffff16565b600a60008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055507fb4423d40ed9dae9515810826dc63edd971a73d88d5bcc6eccf17a28856ad057a8184604051808381526020018281526020019250505060405180910390a1505050565b612aed8282613f7b565b5050565b612afb8133612ae3565b50565b601160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663c2b6b58c6040518163ffffffff1660e01b815260040160206040518083038186803b158015612b6657600080fd5b505afa158015612b7a573d6000803e3d6000fd5b505050506040513d6020811015612b9057600080fd5b810190808051906020019092919050505015612bab57612cb0565b6000612bb561142f565b90506000612bd16007600101548361337490919063ffffffff16565b90506000811115612cad576000612bf382600454613dc890919063ffffffff16565b9050600080600d5414612c2e57612c29600d54612c1b60065485613dc890919063ffffffff16565b613e4e90919063ffffffff16565b612c31565b60005b9050612c4b816007600001546133be90919063ffffffff16565b600760000181905550836007600101819055507fa8b52d4c21c4c3e0e28c90b4133fdaa0c671f3830ab2ab6a9cf95cb7bde83669838560076000015460405180848152602001838152602001828152602001935050505060405180910390a150505b50505b565b612cfb600b60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482611afe565b50565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614612da3576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f8152602001806147c9602f913960400191505060405180910390fd5b612dac81611137565b612e01576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c815260200180614819602c913960400191505060405180910390fd5b600260008273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600090557fa7498c8942adb10d7b806c9a26cff6dd93b6f0259681ffcb98d8dafd8b174f8e81604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a150565b6000601160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b612edc610e65565b612f31576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260288152602001806148966028913960400191505060405180910390fd5b80601160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055507f1bffa28019d1cc5c1306e29d09c3d3be8a18b258f05410bc8e66e36e643e1e7981604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a150565b60055481565b600080600a60008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054600b60008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205491509150915091565b6130748133611afe565b50565b60065481565b600a6020528060005260406000206000915090505481565b600e5481565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614613140576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f8152602001806147c9602f913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156131e3576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f57686974654c6973743a2061646472657373206e6f74207a65726f000000000081525060200191505060405180910390fd5b6131ec81611137565b15613242576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c81526020018061486a602c913960400191505060405180910390fd5b6001600260008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055507ff6f23488d2332695a038c333e5b9b5ad5a5a6aa7001c5c8f2c851051907402c681604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a150565b6132f5612afe565b6000600960008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020905061334182613e98565b816001018190555060076000015481600001819055505050565b600081831061336a578161336c565b825b905092915050565b60006133b683836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506145e8565b905092915050565b60008082840190508381101561343c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b601160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663c2b6b58c6040518163ffffffff1660e01b815260040160206040518083038186803b1580156134ae57600080fd5b505afa1580156134c2573d6000803e3d6000fd5b505050506040513d60208110156134d857600080fd5b81019080805190602001909291905050501561355c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600d8152602001807f53797374656d20636c6f7365640000000000000000000000000000000000000081525060200191505060405180910390fd5b601160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16633cd9b53c6040518163ffffffff1660e01b815260040160206040518083038186803b1580156135c457600080fd5b505afa1580156135d8573d6000803e3d6000fd5b505050506040513d60208110156135ee57600080fd5b810190808051906020019092919050505015613672576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600d8152602001807f52656465656d207061757365640000000000000000000000000000000000000081525060200191505060405180910390fd5b60003390506000600b60008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541161372c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600d8152602001807f4e6f20636f6c6c61746572616c0000000000000000000000000000000000000081525060200191505060405180910390fd5b600083116137a2576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601e8152602001807f546865207175616e74697479206973206c657373207468616e207a65726f000081525060200191505060405180910390fd5b600b60008273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054831115613857576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260158152602001807f696e70757420616d6f756e74206f766572666c6f77000000000000000000000081525060200191505060405180910390fd5b613860816132ed565b600061386b84611f6b565b90506000600f60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663978bbdb96040518163ffffffff1660e01b815260040160206040518083038186803b1580156138d757600080fd5b505afa1580156138eb573d6000803e3d6000fd5b505050506040513d602081101561390157600080fd5b81019080805190602001909291905050509050600061393d6103e861392f8486613dc890919063ffffffff16565b613e4e90919063ffffffff16565b90506000613954828561337490919063ffffffff16565b905061396b82600e546133be90919063ffffffff16565b600e81905550601360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb731111111111111111111111111111111111111111846040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b158015613a2e57600080fd5b505af1158015613a42573d6000803e3d6000fd5b505050506040513d6020811015613a5857600080fd5b810190808051906020019092919050505050601260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16639dc29fac86896040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050600060405180830381600087803b158015613b1357600080fd5b505af1158015613b27573d6000803e3d6000fd5b50505050601360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb87836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b158015613bd457600080fd5b505af1158015613be8573d6000803e3d6000fd5b505050506040513d6020811015613bfe57600080fd5b810190808051906020019092919050505050613c6287600b60008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461337490919063ffffffff16565b600b60008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550613cf784600a60008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461337490919063ffffffff16565b600a60008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550613d4f87600c5461337490919063ffffffff16565b600c81905550613d6a84600d5461337490919063ffffffff16565b600d819055507f0cabeaa2c4a0e1c5eefe6c6097602c06789155d09c5269d9520dd6b203861be98482848a6040518085815260200184815260200183815260200182815260200194505050505060405180910390a150505050505050565b600080831415613ddb5760009050613e48565b6000828402905082848281613dec57fe5b0414613e43576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260218152602001806147f86021913960400191505060405180910390fd5b809150505b92915050565b6000613e9083836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f0000000000008152506146a8565b905092915050565b600080600960008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000209050613f73613f60600654613f52600a60008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054613f44866000015460076000015461337490919063ffffffff16565b613dc890919063ffffffff16565b613e4e90919063ffffffff16565b82600101546133be90919063ffffffff16565b915050919050565b601160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663c2b6b58c6040518163ffffffff1660e01b815260040160206040518083038186803b158015613fe357600080fd5b505afa158015613ff7573d6000803e3d6000fd5b505050506040513d602081101561400d57600080fd5b8101908080519060200190929190505050614090576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260168152602001807f53797374656d206e6f7420436c6f736564207965742e0000000000000000000081525060200191505060405180910390fd5b60003390506000831161410b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601e8152602001807f546865207175616e74697479206973206c657373207468616e207a65726f000081525060200191505060405180910390fd5b6000601260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231836040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b1580156141ac57600080fd5b505afa1580156141c0573d6000803e3d6000fd5b505050506040513d60208110156141d657600080fd5b81019080805190602001909291905050501161425a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260148152602001807f54686520636f696e206e6f2062616c616e63652e00000000000000000000000081525060200191505060405180910390fd5b601260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231826040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b1580156142f957600080fd5b505afa15801561430d573d6000803e3d6000fd5b505050506040513d602081101561432357600080fd5b81019080805190602001909291905050508311156143a9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260138152602001807f436f696e2062616c616e6365206578636565640000000000000000000000000081525060200191505060405180910390fd5b60006143b484611f6b565b9050601260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16639dc29fac83866040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050600060405180830381600087803b15801561445f57600080fd5b505af1158015614473573d6000803e3d6000fd5b50505050601360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb84836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b15801561452057600080fd5b505af1158015614534573d6000803e3d6000fd5b505050506040513d602081101561454a57600080fd5b81019080805190602001909291905050505061457184600c5461337490919063ffffffff16565b600c8190555061458c81600d5461337490919063ffffffff16565b600d819055507f0cabeaa2c4a0e1c5eefe6c6097602c06789155d09c5269d9520dd6b203861be981826000876040518085815260200184815260200183815260200182815260200194505050505060405180910390a150505050565b6000838311158290614695576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561465a57808201518184015260208101905061463f565b50505050905090810190601f1680156146875780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b60008083118290614754576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b838110156147195780820151818401526020810190506146fe565b50505050905090810190601f1680156147465780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b50600083858161476057fe5b04905080915050939250505056fe596f75206d757374206265206e6f6d696e61746564206265666f726520796f752063616e20616363657074206f776e6572736869704669727374206d616b6520636f696e206d75737420677261746572207468616e203130302e4f6e6c792074686520636f6e7472616374206f776e6572206d617920706572666f726d207468697320616374696f6e536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f7757686974654c697374653a20746865206163636f756e74206e6f74206578697374207768696c74654c697374546865207175616e74697479206973206c657373207468616e20746865206d696e696d756d57686974654c697374653a20746865206163636f756e74206578736974207768696c74654c6973742079657457686974654c6973743a206d73672e73656e646572206e6f7420696e207768696c74654c6973742ea265627a7a723158206e56814a1f55ec0be86f69a809e9d0f79f1f3472df39e646a97cd326b27085bc64736f6c63430005100032
{"success": true, "error": null, "results": {"detectors": [{"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}]}
39
0x0f93c452039a092206bf2f9302a3664b8b1c5072
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 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); } 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; } } interface IERC20 { function allowance(address account, address spender) external view returns (uint256); function approve(address spender, uint256 rawAmount) external returns (bool); function balanceOf(address account) external view returns (uint256); function totalSupply() external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } interface IHPFToken { function mint(address dst, uint rawAmount) external; function transfer(address dst, uint rawAmount) external returns (bool); function balanceOf(address account) external view returns (uint); function totalSupply() external view returns (uint); } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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 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 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; } } contract HappyFarm is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HPFs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHPFPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accHPFPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HPFs to distribute per block. uint256 lastRewardBlock; // Last block number that HPFs distribution occurs. uint256 accHPFPerShare; // Accumulated HPFs per share, times 1e12. See below. } // The HPF TOKEN! IHPFToken public HPF; // Dev address. address public devaddr; // Block number when bonus HPF period ends. uint256 public bonusEndBlock; // HPF tokens created per block. uint256 public HPFPerBlock; // Bonus muliplier for early HPF makers. uint256 public constant BONUS_MULTIPLIER = 12; // The governance contract; address public governance; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when HPF mining starts. uint256 public startBlock; // The block number when HPF mining ends. uint256 public endBlock; // The block number when dev can receive it's fee (1 year vesting) // Date and time (GMT): 1 year after deploy uint256 public devFeeUnlockTime; // If dev has requested its fee bool public devFeeDelivered; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( IHPFToken _token, address _devaddr, uint256 _HPFPerBlock, // 100000000000000000000 uint256 _startBlock, // 10902300 , https://etherscan.io/block/countdown/10902300 uint256 _bonusEndBlock, //10930000, https://etherscan.io/block/countdown/10930000 uint256 _endBlock //11240000 (around 50 days of farming), https://etherscan.io/block/countdown/11240000 ) { HPF = _token; devaddr = _devaddr; HPFPerBlock = _HPFPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; endBlock = _endBlock; devFeeUnlockTime = block.timestamp + 365 * 1 days; } function poolLength() external view returns (uint256) { return poolInfo.length; } modifier onlyOwnerOrGovernance() { require(owner() == _msgSender() || governance == _msgSender(), "Caller is not the owner, neither governance"); _; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwnerOrGovernance { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accHPFPerShare: 0 })); } // Update the given pool's HPF allocation point. Can only be called by the owner or governance contract. function updateAllocPoint(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwnerOrGovernance { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set governance contract. Can only be called by the owner or governance contract. function setGovernance(address _governance, bytes memory _setupData) public onlyOwnerOrGovernance { governance = _governance; (bool success,) = governance.call(_setupData); require(success, "setGovernance: failed"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { //HPF minting ocurrs only until endBLock if(_to > endBlock){ _to = endBlock; } 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) ); } } // View function to see pending HPFs on frontend. function pendingHPF(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHPFPerShare = pool.accHPFPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 HPFReward = multiplier.mul(HPFPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accHPFPerShare = accHPFPerShare.add(HPFReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accHPFPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 HPFReward = multiplier.mul(HPFPerBlock).mul(pool.allocPoint).div(totalAllocPoint); // Dev will have it's 0.5% fee after 1 year, this not necessary //HPF.mint(devaddr, HPFReward.div(100)); HPF.mint(address(this), HPFReward); pool.accHPFPerShare = pool.accHPFPerShare.add(HPFReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to HappyFarm for HPF allocation. // You can harvest by calling deposit(_pid,0) function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accHPFPerShare).div(1e12).sub(user.rewardDebt); safeHPFTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accHPFPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from HappyFarm. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not enough"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accHPFPerShare).div(1e12).sub(user.rewardDebt); safeHPFTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accHPFPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe HPF transfer function, just in case if rounding error causes pool to not have enough HPFs. function safeHPFTransfer(address _to, uint256 _amount) internal { uint256 HPFBal = HPF.balanceOf(address(this)); if (_amount > HPFBal) { HPF.transfer(_to, HPFBal); } else { HPF.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // give dev team its fee. This can ony be called after one year, // it's 0.5% function devFee() public { require(block.timestamp >= devFeeUnlockTime, "devFee: wait until unlock time"); require(!devFeeDelivered, "devFee: can only be called once"); HPF.mint(devaddr, HPF.totalSupply().div(200)); devFeeDelivered=true; } }
0x608060405234801561001057600080fd5b50600436106101cf5760003560e01c80638aa2855011610104578063957e8989116100a2578063d49e77cd11610071578063d49e77cd14610501578063e2bbb15814610509578063f2fde38b1461052c578063f48cd52614610552576101cf565b8063957e8989146103ec578063a9084b32146103f4578063bde4aeca14610420578063c3d1c26c1461044b576101cf565b80638dbb1e3a116100de5780638dbb1e3a14610360578063915aacdb1461038357806393f1a40b1461038b578063950114c6146103d0576101cf565b80638aa285501461032a5780638d88a90e146103325780638da5cb5b14610358576101cf565b806348cd4cb1116101715780635aa6e6751161014b5780635aa6e675146102ee578063630b5ba1146103125780636827e7641461031a578063715018a614610322576101cf565b806348cd4cb1146102ac57806351eb05a6146102b45780635312ea8e146102d1576101cf565b806317caf6f1116101ad57806317caf6f1146102435780631aed65531461024b5780631eaaa04514610253578063441a3e7014610289576101cf565b8063081e3eda146101d4578063083c6323146101ee5780631526fe27146101f6575b600080fd5b6101dc61055a565b60408051918252519081900360200190f35b6101dc610560565b6102136004803603602081101561020c57600080fd5b5035610566565b604080516001600160a01b0390951685526020850193909352838301919091526060830152519081900360800190f35b6101dc6105a7565b6101dc6105ad565b6102876004803603606081101561026957600080fd5b508035906001600160a01b03602082013516906040013515156105b3565b005b6102876004803603604081101561029f57600080fd5b5080359060200135610754565b6101dc6108a9565b610287600480360360208110156102ca57600080fd5b50356108af565b610287600480360360208110156102e757600080fd5b5035610a54565b6102f6610aef565b604080516001600160a01b039092168252519081900360200190f35b610287610afe565b610287610b21565b610287610cc8565b6101dc610d7c565b6102876004803603602081101561034857600080fd5b50356001600160a01b0316610d81565b6102f6610dee565b6101dc6004803603604081101561037657600080fd5b5080359060200135610dfd565b6102f6610e7f565b6103b7600480360360408110156103a157600080fd5b50803590602001356001600160a01b0316610e8e565b6040805192835260208301919091528051918290030190f35b6103d8610eb2565b604080519115158252519081900360200190f35b6101dc610ebb565b6101dc6004803603604081101561040a57600080fd5b50803590602001356001600160a01b0316610ec1565b6102876004803603606081101561043657600080fd5b50803590602081013590604001351515611023565b6102876004803603604081101561046157600080fd5b6001600160a01b03823516919081019060408101602082013564010000000081111561048c57600080fd5b82018360208201111561049e57600080fd5b803590602001918460018302840111640100000000831117156104c057600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550611114945050505050565b6102f66112a6565b6102876004803603604081101561051f57600080fd5b50803590602001356112b5565b6102876004803603602081101561054257600080fd5b50356001600160a01b03166113ba565b6101dc6114c4565b60065490565b600a5481565b6006818154811061057357fe5b600091825260209091206004909102018054600182015460028301546003909301546001600160a01b039092169350919084565b60085481565b60035481565b6105bb6114ca565b6001600160a01b03166105cc610dee565b6001600160a01b031614806105f657506105e46114ca565b6005546001600160a01b039081169116145b6106315760405162461bcd60e51b815260040180806020018281038252602b815260200180611c00602b913960400191505060405180910390fd5b801561063f5761063f610afe565b6000600954431161065257600954610654565b435b60085490915061066490856114ce565b600855604080516080810182526001600160a01b0394851681526020810195865290810191825260006060820181815260068054600181018255925291517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f600490920291820180546001600160a01b031916919096161790945593517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d40840155517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d418301555090517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d4290910155565b60006006838154811061076357fe5b6000918252602080832086845260078252604080852033865290925292208054600490920290920192508311156107d8576040805162461bcd60e51b81526020600482015260146024820152730eed2e8d0c8e4c2ee7440dcdee840cadcdeeaced60631b604482015290519081900360640190fd5b6107e1846108af565b600061081b826001015461081564e8d4a5100061080f8760030154876000015461152f90919063ffffffff16565b90611588565b906115ca565b9050610827338261160c565b815461083390856115ca565b80835560038401546108509164e8d4a510009161080f919061152f565b6001830155825461086b906001600160a01b0316338661179c565b604080518581529051869133917ff279e6a1f5e320cca91135676d9cb6e44ca8a08c0b88342bcdb1144f6511b5689181900360200190a35050505050565b60095481565b6000600682815481106108be57fe5b90600052602060002090600402019050806002015443116108df5750610a51565b8054604080516370a0823160e01b815230600482015290516000926001600160a01b0316916370a08231916024808301926020929190829003018186803b15801561092957600080fd5b505afa15801561093d573d6000803e3d6000fd5b505050506040513d602081101561095357600080fd5b5051905080610969575043600290910155610a51565b6000610979836002015443610dfd565b905060006109a660085461080f86600101546109a06004548761152f90919063ffffffff16565b9061152f565b600154604080516340c10f1960e01b81523060048201526024810184905290519293506001600160a01b03909116916340c10f199160448082019260009290919082900301818387803b1580156109fc57600080fd5b505af1158015610a10573d6000803e3d6000fd5b50505050610a3e610a338461080f64e8d4a510008561152f90919063ffffffff16565b6003860154906114ce565b6003850155505043600290920191909155505b50565b600060068281548110610a6357fe5b60009182526020808320858452600782526040808520338087529352909320805460049093029093018054909450610aa8926001600160a01b0391909116919061179c565b80546040805191825251849133917fbb757047c2b5f3974fe26b7c10f732e7bce710b0952a71082702781e62ae05959181900360200190a360008082556001909101555050565b6005546001600160a01b031681565b60065460005b81811015610b1d57610b15816108af565b600101610b04565b5050565b600b54421015610b78576040805162461bcd60e51b815260206004820152601e60248201527f6465764665653a207761697420756e74696c20756e6c6f636b2074696d650000604482015290519081900360640190fd5b600c5460ff1615610bd0576040805162461bcd60e51b815260206004820152601f60248201527f6465764665653a2063616e206f6e6c792062652063616c6c6564206f6e636500604482015290519081900360640190fd5b600154600254604080516318160ddd60e01b815290516001600160a01b03938416936340c10f19931691610c5b9160c89186916318160ddd91600480820192602092909190829003018186803b158015610c2957600080fd5b505afa158015610c3d573d6000803e3d6000fd5b505050506040513d6020811015610c5357600080fd5b505190611588565b6040518363ffffffff1660e01b815260040180836001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015610ca157600080fd5b505af1158015610cb5573d6000803e3d6000fd5b5050600c805460ff191660011790555050565b610cd06114ca565b6000546001600160a01b03908116911614610d32576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b600c81565b6002546001600160a01b03163314610dcc576040805162461bcd60e51b81526020600482015260096024820152686465763a207775743f60b81b604482015290519081900360640190fd5b600280546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b031690565b6000600a54821115610e0f57600a5491505b6003548211610e2e57610e27600c6109a084866115ca565b9050610e79565b6003548310610e4157610e2782846115ca565b610e27610e59600354846115ca90919063ffffffff16565b610e73600c6109a0876003546115ca90919063ffffffff16565b906114ce565b92915050565b6001546001600160a01b031681565b60076020908152600092835260408084209091529082529020805460019091015482565b600c5460ff1681565b600b5481565b60008060068481548110610ed157fe5b600091825260208083208784526007825260408085206001600160a01b03898116875290845281862060049586029093016003810154815484516370a0823160e01b81523098810198909852935191985093969395939492909116926370a08231926024808301939192829003018186803b158015610f4f57600080fd5b505afa158015610f63573d6000803e3d6000fd5b505050506040513d6020811015610f7957600080fd5b5051600285015490915043118015610f9057508015155b15610ff0576000610fa5856002015443610dfd565b90506000610fcc60085461080f88600101546109a06004548761152f90919063ffffffff16565b9050610feb610fe48461080f8464e8d4a5100061152f565b85906114ce565b935050505b611018836001015461081564e8d4a5100061080f86886000015461152f90919063ffffffff16565b979650505050505050565b61102b6114ca565b6001600160a01b031661103c610dee565b6001600160a01b0316148061106657506110546114ca565b6005546001600160a01b039081169116145b6110a15760405162461bcd60e51b815260040180806020018281038252602b815260200180611c00602b913960400191505060405180910390fd5b80156110af576110af610afe565b6110e682610e73600686815481106110c357fe5b9060005260206000209060040201600101546008546115ca90919063ffffffff16565b60088190555081600684815481106110fa57fe5b906000526020600020906004020160010181905550505050565b61111c6114ca565b6001600160a01b031661112d610dee565b6001600160a01b0316148061115757506111456114ca565b6005546001600160a01b039081169116145b6111925760405162461bcd60e51b815260040180806020018281038252602b815260200180611c00602b913960400191505060405180910390fd5b600580546001600160a01b0319166001600160a01b038481169190911791829055604051835160009390921691849190819060208401908083835b602083106111ec5780518252601f1990920191602091820191016111cd565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d806000811461124e576040519150601f19603f3d011682016040523d82523d6000602084013e611253565b606091505b50509050806112a1576040805162461bcd60e51b81526020600482015260156024820152741cd95d11dbdd995c9b985b98d94e8819985a5b1959605a1b604482015290519081900360640190fd5b505050565b6002546001600160a01b031681565b6000600683815481106112c457fe5b600091825260208083208684526007825260408085203386529092529220600490910290910191506112f5846108af565b80541561133857600061132a826001015461081564e8d4a5100061080f8760030154876000015461152f90919063ffffffff16565b9050611336338261160c565b505b815461134f906001600160a01b03163330866117ee565b805461135b90846114ce565b80825560038301546113789164e8d4a510009161080f919061152f565b6001820155604080518481529051859133917f90890809c654f11d6e72a28fa60149770a0d11ec6c92319d6ceb2bb0a4ea1a159181900360200190a350505050565b6113c26114ca565b6000546001600160a01b03908116911614611424576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b6001600160a01b0381166114695760405162461bcd60e51b8152600401808060200182810382526026815260200180611bb96026913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b60045481565b3390565b600082820183811015611528576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b60008261153e57506000610e79565b8282028284828161154b57fe5b04146115285760405162461bcd60e51b8152600401808060200182810382526021815260200180611bdf6021913960400191505060405180910390fd5b600061152883836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061184e565b600061152883836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506118f0565b600154604080516370a0823160e01b815230600482015290516000926001600160a01b0316916370a08231916024808301926020929190829003018186803b15801561165757600080fd5b505afa15801561166b573d6000803e3d6000fd5b505050506040513d602081101561168157600080fd5b5051905080821115611715576001546040805163a9059cbb60e01b81526001600160a01b038681166004830152602482018590529151919092169163a9059cbb9160448083019260209291908290030181600087803b1580156116e357600080fd5b505af11580156116f7573d6000803e3d6000fd5b505050506040513d602081101561170d57600080fd5b506112a19050565b6001546040805163a9059cbb60e01b81526001600160a01b038681166004830152602482018690529151919092169163a9059cbb9160448083019260209291908290030181600087803b15801561176b57600080fd5b505af115801561177f573d6000803e3d6000fd5b505050506040513d602081101561179557600080fd5b5050505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b1790526112a190849061194a565b604080516001600160a01b0380861660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b17905261184890859061194a565b50505050565b600081836118da5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561189f578181015183820152602001611887565b50505050905090810190601f1680156118cc5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385816118e657fe5b0495945050505050565b600081848411156119425760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561189f578181015183820152602001611887565b505050900390565b606061199f826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166119fb9092919063ffffffff16565b8051909150156112a1578080602001905160208110156119be57600080fd5b50516112a15760405162461bcd60e51b815260040180806020018281038252602a815260200180611c2b602a913960400191505060405180910390fd5b6060611a0a8484600085611a12565b949350505050565b6060611a1d85611b7f565b611a6e576040805162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015290519081900360640190fd5b60006060866001600160a01b031685876040518082805190602001908083835b60208310611aad5780518252601f199092019160209182019101611a8e565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d8060008114611b0f576040519150601f19603f3d011682016040523d82523d6000602084013e611b14565b606091505b50915091508115611b28579150611a0a9050565b805115611b385780518082602001fd5b60405162461bcd60e51b815260206004820181815286516024840152865187939192839260440191908501908083836000831561189f578181015183820152602001611887565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590611a0a57505015159291505056fe4f776e61626c653a206e6577206f776e657220697320746865207a65726f2061646472657373536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f7743616c6c6572206973206e6f7420746865206f776e65722c206e65697468657220676f7665726e616e63655361666545524332303a204552433230206f7065726174696f6e20646964206e6f742073756363656564a2646970667358221220a3487865522c2ba5d701f95e59beba72ce3189e89da82fbd0965f7c2f60ad92764736f6c63430007010033
{"success": true, "error": null, "results": {"detectors": [{"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}]}
40
0x0fDF94751F639cAb6c28d2dC339844bC6BE9530F
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 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 ILockable { event Locked(); event Unlocked(); function lock() external /* onlyLockOwner */; function unlock() external /* onlyLockOwner */; function isLocked() view external returns (bool); } interface IMigratableStakingContract { /// @dev Returns the address of the underlying staked token. /// @return IERC20 The address of the token. function getToken() external view returns (IERC20); /// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _stakeOwner address The specified stake owner. /// @param _amount uint256 The number of tokens to stake. function acceptMigration(address _stakeOwner, uint256 _amount) external; event AcceptedMigration(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); } 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 IStakingContract { /// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _amount uint256 The amount of tokens to stake. function stake(uint256 _amount) external; /// @dev Unstakes ORBS tokens from msg.sender. If successful, this will start the cooldown period, after which /// msg.sender would be able to withdraw all of his tokens. /// @param _amount uint256 The amount of tokens to unstake. function unstake(uint256 _amount) external; /// @dev Requests to withdraw all of staked ORBS tokens back to msg.sender. Stake owners can withdraw their ORBS /// tokens only after previously unstaking them and after the cooldown period has passed (unless the contract was /// requested to release all stakes). function withdraw() external; /// @dev Restakes unstaked ORBS tokens (in or after cooldown) for msg.sender. function restake() external; /// @dev Distributes staking rewards to a list of addresses by directly adding rewards to their stakes. This method /// assumes that the user has already approved at least the required amount using ERC20 approve. Since this is a /// convenience method, we aren't concerned about reaching block gas limit by using large lists. We assume that /// callers will be able to properly batch/paginate their requests. /// @param _totalAmount uint256 The total amount of rewards to distributes. /// @param _stakeOwners address[] The addresses of the stake owners. /// @param _amounts uint256[] The amounts of the rewards. function distributeRewards(uint256 _totalAmount, address[] calldata _stakeOwners, uint256[] calldata _amounts) external; /// @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); /// @dev Returns the time that the cooldown period ends (or ended) and the amount of tokens to be released. /// @param _stakeOwner address The address to check. /// @return cooldownAmount uint256 The total tokens in cooldown. /// @return cooldownEndTime uint256 The time when the cooldown period ends (in seconds). function getUnstakeStatus(address _stakeOwner) external view returns (uint256 cooldownAmount, uint256 cooldownEndTime); /// @dev Migrates the stake of msg.sender from this staking contract to a new approved staking contract. /// @param _newStakingContract IMigratableStakingContract The new staking contract which supports stake migration. /// @param _amount uint256 The amount of tokens to migrate. function migrateStakedTokens(IMigratableStakingContract _newStakingContract, uint256 _amount) external; event Staked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Unstaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Withdrew(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Restaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event MigratedStake(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); } 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); } 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 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 StakingContractHandler is IStakingContractHandler, IStakeChangeNotifier, ManagedContract { bool notifyDelegations = true; constructor(IContractRegistry _contractRegistry, address _registryAdmin) public ManagedContract(_contractRegistry, _registryAdmin) {} modifier onlyStakingContract() { require(msg.sender == address(getStakingContract()), "caller is not the staking contract"); _; } /* * External functions */ function stakeChange(address stakeOwner, uint256 amount, bool sign, uint256 updatedStake) external override onlyStakingContract { if (!notifyDelegations) { emit StakeChangeNotificationSkipped(stakeOwner); return; } delegationsContract.stakeChange(stakeOwner, amount, sign, updatedStake); } /// @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 override onlyStakingContract { if (!notifyDelegations) { emit StakeChangeBatchNotificationSkipped(stakeOwners); return; } delegationsContract.stakeChangeBatch(stakeOwners, amounts, signs, updatedStakes); } /// @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 override onlyStakingContract { if (!notifyDelegations) { emit StakeMigrationNotificationSkipped(stakeOwner); return; } delegationsContract.stakeMigration(stakeOwner, amount); } /// @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 override view returns (uint256) { return stakingContract.getStakeBalanceOf(stakeOwner); } /// @dev Returns the total amount staked tokens (excluding unstaked tokens). /// @return uint256 The total staked tokens of all stake owners. function getTotalStakedTokens() external override view returns (uint256) { return stakingContract.getTotalStakedTokens(); } /* * Governance functions */ function setNotifyDelegations(bool _notifyDelegations) external override onlyMigrationManager { notifyDelegations = _notifyDelegations; emit NotifyDelegationsChanged(_notifyDelegations); } function getNotifyDelegations() external override returns (bool) { return notifyDelegations; } /* * Contracts topology / registry interface */ IStakeChangeNotifier delegationsContract; IStakingContract stakingContract; function refreshContracts() external override { delegationsContract = IStakeChangeNotifier(getDelegationsContract()); stakingContract = IStakingContract(getStakingContract()); } }
0x608060405234801561001057600080fd5b506004361061018d5760003560e01c806390ef9d3f116100e3578063d25235261161008c578063eec0701f11610066578063eec0701f1461047d578063f83d08ba14610485578063fcd13d651461048d5761018d565b8063d252352614610447578063e4e992221461044f578063e9aea8c8146104575761018d565b8063acdb8e04116100bd578063acdb8e041461040b578063ce257ab814610413578063cf3090121461043f5761018d565b806390ef9d3f14610295578063a4e2d634146103fb578063a69df4b5146104035761018d565b80633e2ac140116101455780635f94cd9c1161011f5780635f94cd9c1461027d57806370b639aa1461028557806374c16b231461028d5761018d565b80633e2ac1401461023c57806348106fe31461025b57806351d18598146102635761018d565b80632987cea0116101765780632987cea0146101ea5780632a1fac7214610210578063333df154146102185761018d565b80630e3b7c95146101925780631a0b2c4f146101ce575b600080fd5b6101cc600480360360808110156101a857600080fd5b506001600160a01b03813516906020810135906040810135151590606001356104b3565b005b6101d6610606565b604080519115158252519081900360200190f35b6101cc6004803603602081101561020057600080fd5b50356001600160a01b031661062a565b6101cc6106a7565b610220610751565b604080516001600160a01b039092168252519081900360200190f35b6101cc6004803603602081101561025257600080fd5b50351515610760565b6101d6610859565b61026b610869565b60408051918252519081900360200190f35b6102206108f8565b6101d6610907565b610220610929565b6101cc600480360360808110156102ab57600080fd5b8101906020810181356401000000008111156102c657600080fd5b8201836020820111156102d857600080fd5b803590602001918460208302840111640100000000831117156102fa57600080fd5b91939092909160208101903564010000000081111561031857600080fd5b82018360208201111561032a57600080fd5b8035906020019184602083028401116401000000008311171561034c57600080fd5b91939092909160208101903564010000000081111561036a57600080fd5b82018360208201111561037c57600080fd5b8035906020019184602083028401116401000000008311171561039e57600080fd5b9193909290916020810190356401000000008111156103bc57600080fd5b8201836020820111156103ce57600080fd5b803590602001918460208302840111640100000000831117156103f057600080fd5b509092509050610938565b6101d6610bce565b6101cc610bef565b6101cc610cd2565b6101cc6004803603604081101561042957600080fd5b506001600160a01b038135169060200135610d77565b6101d6610eb9565b6101cc610eda565b610220610f62565b61026b6004803603602081101561046d57600080fd5b50356001600160a01b0316610f71565b6101cc61100d565b6101cc61108f565b6101cc600480360360208110156104a357600080fd5b50356001600160a01b0316611189565b6104bb611309565b6001600160a01b0316336001600160a01b03161461050a5760405162461bcd60e51b815260040180806020018281038252602281526020018061175f6022913960400191505060405180910390fd5b6003547501000000000000000000000000000000000000000000900460ff16610566576040516001600160a01b038516907f7c1973c86555ff78610f7c9cee82f6d4d6e044ab7e06d9cdac7446493ea2115b90600090a2610600565b60048054604080517f0e3b7c950000000000000000000000000000000000000000000000000000000081526001600160a01b03888116948201949094526024810187905285151560448201526064810185905290519290911691630e3b7c959160848082019260009290919082900301818387803b1580156105e757600080fd5b505af11580156105fb573d6000803e3d6000fd5b505050505b50505050565b600080546001600160a01b031661061b611399565b6001600160a01b031614905090565b610632610606565b61066d5760405162461bcd60e51b81526004018080602001828103825260408152602001806117b56040913960400191505060405180910390fd5b600180547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b0392909216919091179055565b6106af610751565b6001600160a01b0316336001600160a01b0316146106fe5760405162461bcd60e51b81526004018080602001828103825260268152602001806117166026913960400191505060405180910390fd5b600280547fffffffffffffffffffffffff00000000000000000000000000000000000000001690556040517f2a2b3ea974fb057582c3b210ef8b5f81492d15673f49d4384bfa3b896a964c3c90600090a1565b6002546001600160a01b031690565b61079e6040518060400160405280601081526020017f6d6967726174696f6e4d616e616765720000000000000000000000000000000081525061139d565b6107d95760405162461bcd60e51b815260040180806020018281038252602381526020018061173c6023913960400191505060405180910390fd5b60038054821515750100000000000000000000000000000000000000000081027fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff9092169190911790915560408051918252517fa1731b0e4e40301cedc90d6a2b635591826af86d321c5f497b6d510620f734d99181900360200190a150565b6002546001600160a01b03161590565b600554604080517f51d1859800000000000000000000000000000000000000000000000000000000815290516000926001600160a01b0316916351d18598916004808301926020929190829003018186803b1580156108c757600080fd5b505afa1580156108db573d6000803e3d6000fd5b505050506040513d60208110156108f157600080fd5b5051905090565b6001546001600160a01b031690565b6003547501000000000000000000000000000000000000000000900460ff1690565b6000546001600160a01b031690565b610940611309565b6001600160a01b0316336001600160a01b03161461098f5760405162461bcd60e51b815260040180806020018281038252602281526020018061175f6022913960400191505060405180910390fd5b6003547501000000000000000000000000000000000000000000900460ff16610a38577f828b0a243e722c25b76c488685680de65b7d8cd463a6230956396cb736a5ab5a888860405180806020018281038252848482818152602001925060200280828437600083820152604051601f9091017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169092018290039550909350505050a16105fb565b600460009054906101000a90046001600160a01b03166001600160a01b03166390ef9d3f89898989898989896040518963ffffffff1660e01b8152600401808060200180602001806020018060200185810385528d8d82818152602001925060200280828437600083820152601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01690910186810385528b8152602090810191508c908c0280828437600083820152601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169091018681038452898152602090810191508a908a0280828437600083820152601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169091018681038352878152602090810191508890880280828437600081840152601f19601f8201169050808301925050509c50505050505050505050505050600060405180830381600087803b158015610bac57600080fd5b505af1158015610bc0573d6000803e3d6000fd5b505050505050505050505050565b60035474010000000000000000000000000000000000000000900460ff1690565b610bf7610929565b6001600160a01b0316336001600160a01b03161480610c2e5750610c19610f62565b6001600160a01b0316336001600160a01b0316145b610c7f576040805162461bcd60e51b815260206004820152601a60248201527f63616c6c6572206973206e6f742061206c6f636b206f776e6572000000000000604482015290519081900360640190fd5b600380547fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff1690556040517f19aad37188a1d3921e29eb3c66acf43d81975e107cb650d58cca878627955fd690600090a1565b610cda610606565b610d155760405162461bcd60e51b81526004018080602001828103825260408152602001806117b56040913960400191505060405180910390fd5b600080546040516001600160a01b03909116907f1f5f028be638d6a0e3b8d56fd05b812ce325cc8dc73cdb0e16df94d6b2725c2e908390a3600080547fffffffffffffffffffffffff0000000000000000000000000000000000000000169055565b610d7f611309565b6001600160a01b0316336001600160a01b031614610dce5760405162461bcd60e51b815260040180806020018281038252602281526020018061175f6022913960400191505060405180910390fd5b6003547501000000000000000000000000000000000000000000900460ff16610e2a576040516001600160a01b038316907fc3c3676476bb348ea01d34d229cd14554114e3f5083e83227a4d1bd6c8a6523690600090a2610eb5565b60048054604080517fce257ab80000000000000000000000000000000000000000000000000000000081526001600160a01b0386811694820194909452602481018590529051929091169163ce257ab89160448082019260009290919082900301818387803b158015610e9c57600080fd5b505af1158015610eb0573d6000803e3d6000fd5b505050505b5050565b60035474010000000000000000000000000000000000000000900460ff1681565b6001546001600160a01b03163314610f235760405162461bcd60e51b81526004018080602001828103825260278152602001806116ef6027913960400191505060405180910390fd5b600154610f38906001600160a01b03166114cc565b600180547fffffffffffffffffffffffff0000000000000000000000000000000000000000169055565b6003546001600160a01b031690565b600554604080517fe9aea8c80000000000000000000000000000000000000000000000000000000081526001600160a01b0384811660048301529151600093929092169163e9aea8c891602480820192602092909190829003018186803b158015610fdb57600080fd5b505afa158015610fef573d6000803e3d6000fd5b505050506040513d602081101561100557600080fd5b505192915050565b611015611584565b600480547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b0392909216919091179055611055611309565b600580547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b0392909216919091179055565b611097610929565b6001600160a01b0316336001600160a01b031614806110ce57506110b9610f62565b6001600160a01b0316336001600160a01b0316145b61111f576040805162461bcd60e51b815260206004820152601a60248201527f63616c6c6572206973206e6f742061206c6f636b206f776e6572000000000000604482015290519081900360640190fd5b600380547fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff16740100000000000000000000000000000000000000001790556040517f0f2e5b6c72c6a4491efd919a9f9a409f324ef0708c11ee57d410c2cb06c0992b90600090a1565b611191611614565b6111cc5760405162461bcd60e51b815260040180806020018281038252603e815260200180611670603e913960400191505060405180910390fd5b600354604080517f078cbb7c00000000000000000000000000000000000000000000000000000000815290516001600160a01b039283169284169163078cbb7c916004808301926020929190829003018186803b15801561122c57600080fd5b505afa158015611240573d6000803e3d6000fd5b505050506040513d602081101561125657600080fd5b50516001600160a01b03161461129d5760405162461bcd60e51b81526004018080602001828103825260418152602001806116ae6041913960600191505060405180910390fd5b600380546001600160a01b0383167fffffffffffffffffffffffff0000000000000000000000000000000000000000909116811790915560408051918252517ffea2d033438b968078a6264409d0104b5f3d2ce7b795afc74918e70f3534f22b9181900360200190a150565b600354604080517f35817773000000000000000000000000000000000000000000000000000000008152602060048201819052600760248301527f7374616b696e6700000000000000000000000000000000000000000000000000604483015291516000936001600160a01b03169263358177739260648082019391829003018186803b1580156108c757600080fd5b3390565b6003546000906001600160a01b03166113b4611614565b806114c557506001600160a01b038116158015906114c557506003546040517f1ee441e900000000000000000000000000000000000000000000000000000000815260206004820181815286516024840152865133946001600160a01b031693631ee441e99389939283926044019185019080838360005b8381101561144457818101518382015260200161142c565b50505050905090810190601f1680156114715780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b15801561148e57600080fd5b505afa1580156114a2573d6000803e3d6000fd5b505050506040513d60208110156114b857600080fd5b50516001600160a01b0316145b9392505050565b6001600160a01b0381166115115760405162461bcd60e51b81526004018080602001828103825260348152602001806117816034913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f1f5f028be638d6a0e3b8d56fd05b812ce325cc8dc73cdb0e16df94d6b2725c2e91a3600080547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b0392909216919091179055565b600354604080517f35817773000000000000000000000000000000000000000000000000000000008152602060048201819052600b60248301527f64656c65676174696f6e73000000000000000000000000000000000000000000604483015291516000936001600160a01b03169263358177739260648082019391829003018186803b1580156108c757600080fd5b600061161e610929565b6001600160a01b0316336001600160a01b031614806116555750611640610751565b6001600160a01b0316336001600160a01b0316145b8061166a57506003546001600160a01b031633145b90509056fe73656e646572206973206e6f7420616e2061646d696e202872656769737472794d616e676572206f7220696e697469616c697a6174696f6e41646d696e296e657720636f6e7472616374207265676973747279206d7573742070726f76696465207468652070726576696f757320636f6e747261637420726567697374727943616c6c6572206973206e6f74207468652070656e64696e6720726567697374727941646d696e73656e646572206973206e6f742074686520696e697469616c697a6174696f6e2061646d696e73656e646572206973206e6f7420746865206d6967726174696f6e206d616e6167657263616c6c6572206973206e6f7420746865207374616b696e6720636f6e7472616374526567697374727941646d696e3a206e657720726567697374727941646d696e20697320746865207a65726f206164647265737357697468436c61696d61626c6552656769737472794d616e6167656d656e743a2063616c6c6572206973206e6f742074686520726567697374727941646d696ea2646970667358221220e6786e70774964d782d5e2a7c8854ebb9d954d8db57a860ccf39e4b87c1a3d7864736f6c634300060c0033
{"success": true, "error": null, "results": {}}
true
null
{}
41
0x1149d772bce9a636d0d7535ec865f3c6c8ee3b5c
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 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); } 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 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 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 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; } }
0x608060405234801561001057600080fd5b50600436106100f55760003560e01c806391d1485411610097578063c4d66de811610066578063c4d66de8146102b3578063ca15c873146102d9578063d547741f146102f6578063fa8dacba146100fa576100f5565b806391d1485414610240578063a217fddf14610280578063a22a642814610288578063b39e12cf146102ab576100f5565b80632f2ff15d116100d35780632f2ff15d1461017d57806336568abe146101a95780634458328b146101d55780639010d07c14610201576100f5565b80630b975991146100fa57806321038b4c14610132578063248a9ca314610160575b600080fd5b6101206004803603602081101561011057600080fd5b50356001600160a01b0316610322565b60408051918252519081900360200190f35b61015e6004803603604081101561014857600080fd5b506001600160a01b038135169060200135610335565b005b6101206004803603602081101561017657600080fd5b50356105b7565b61015e6004803603604081101561019357600080fd5b50803590602001356001600160a01b03166105cc565b61015e600480360360408110156101bf57600080fd5b50803590602001356001600160a01b0316610638565b61015e600480360360408110156101eb57600080fd5b506001600160a01b038135169060200135610699565b6102246004803603604081101561021757600080fd5b5080359060200135610858565b604080516001600160a01b039092168252519081900360200190f35b61026c6004803603604081101561025657600080fd5b50803590602001356001600160a01b031661087f565b604080519115158252519081900360200190f35b61012061089d565b61015e6004803603604081101561029e57600080fd5b50803590602001356108a2565b610224610cb2565b61015e600480360360208110156102c957600080fd5b50356001600160a01b0316610cc1565b610120600480360360208110156102ef57600080fd5b5035610d6c565b61015e6004803603604081101561030c57600080fd5b50803590602001356001600160a01b0316610d83565b600061032d82610ddc565b90505b919050565b61033e33610f01565b610388576040805162461bcd60e51b815260206004820152601660248201527521b0b63632b91034b9903737ba1030b71030b236b4b760511b604482015290519081900360640190fd5b60975460408051633581777360e01b815260206004820181905260146024830152732232b632b3b0ba34b7b721b7b73a3937b63632b960611b604483015291516000936001600160a01b03169263358177739260648082019391829003018186803b1580156103f657600080fd5b505afa15801561040a573d6000803e3d6000fd5b505050506040513d602081101561042057600080fd5b505160408051632f7263cd60e01b81526001600160a01b038681166004830152915192935090831691632f7263cd91602480820192602092909190829003018186803b15801561046f57600080fd5b505afa158015610483573d6000803e3d6000fd5b505050506040513d602081101561049957600080fd5b5051156104ed576040805162461bcd60e51b815260206004820152601f60248201527f4e6f7420616c6c20736c617368657320776572652063616c63756c6174656400604482015290519081900360640190fd5b6001600160a01b03831660009081526098602052604090205482111561052b576001600160a01b03831660009081526098602052604081205561056e565b6001600160a01b038316600090815260986020526040902054610554908363ffffffff61107916565b6001600160a01b0384166000908152609860205260409020555b604080516001600160a01b03851681526020810184905281517fe58cb55c9ec3940584c849bc6141e3187cabbbaee3b94d8da551cc92827e474d929181900390910190a1505050565b60009081526065602052604090206002015490565b6000828152606560205260409020600201546105ef906105ea6110bb565b61087f565b61062a5760405162461bcd60e51b815260040180806020018281038252602f8152602001806117af602f913960400191505060405180910390fd5b61063482826110bf565b5050565b6106406110bb565b6001600160a01b0316816001600160a01b03161461068f5760405162461bcd60e51b815260040180806020018281038252602f81526020018061185e602f913960400191505060405180910390fd5b610634828261112e565b6040805180820182526014808252732232b632b3b0ba34b7b721b7b73a3937b63632b960611b60208084019182526097549451939433946001600160a01b039091169363ec56a373938793929092019182918083835b6020831061070e5780518252601f1990920191602091820191016106ef565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b15801561077d57600080fd5b505afa158015610791573d6000803e3d6000fd5b505050506040513d60208110156107a757600080fd5b50516001600160a01b031614806107c157506107c161119d565b61080e576040805162461bcd60e51b815260206004820152601960248201527813595cdcd859d9481cd95b99195c881a5cc81a5b9d985b1a59603a1b604482015290519081900360640190fd5b6001600160a01b038316600090815260986020526040902054610837908363ffffffff6111ae16565b6001600160a01b039093166000908152609860205260409020929092555050565b6000828152606560205260408120610876908363ffffffff61120816565b90505b92915050565b6000828152606560205260408120610876908363ffffffff61121416565b600081565b604080518082018252600880825267536b616c65444b4760c01b60208084019182526097549451939433946001600160a01b039091169363ec56a373938793929092019182918083835b6020831061090b5780518252601f1990920191602091820191016108ec565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b15801561097a57600080fd5b505afa15801561098e573d6000803e3d6000fd5b505050506040513d60208110156109a457600080fd5b50516001600160a01b031614806109be57506109be61119d565b610a0b576040805162461bcd60e51b815260206004820152601960248201527813595cdcd859d9481cd95b99195c881a5cc81a5b9d985b1a59603a1b604482015290519081900360640190fd5b60975460408051633581777360e01b8152602060048201819052601060248301526f56616c696461746f725365727669636560801b604483015291516000936001600160a01b03169263358177739260648082019391829003018186803b158015610a7557600080fd5b505afa158015610a89573d6000803e3d6000fd5b505050506040513d6020811015610a9f57600080fd5b505160975460408051633581777360e01b815260206004820181905260146024830152732232b632b3b0ba34b7b721b7b73a3937b63632b960611b604483015291519394506000936001600160a01b0390931692633581777392606480840193919291829003018186803b158015610b1657600080fd5b505afa158015610b2a573d6000803e3d6000fd5b505050506040513d6020811015610b4057600080fd5b505160408051635be8c60f60e01b81526004810188905290519192506001600160a01b03841691635be8c60f91602480820192602092909190829003018186803b158015610b8d57600080fd5b505afa158015610ba1573d6000803e3d6000fd5b505050506040513d6020811015610bb757600080fd5b5051610c0a576040805162461bcd60e51b815260206004820152601860248201527f56616c696461746f7220646f6573206e6f742065786973740000000000000000604482015290519081900360640190fd5b806001600160a01b0316631da42e5e86866040518363ffffffff1660e01b81526004018083815260200182815260200192505050600060405180830381600087803b158015610c5857600080fd5b505af1158015610c6c573d6000803e3d6000fd5b5050604080518881526020810188905281517fc9037bda6c78ffc3f14592baf2dfab801c84e88f9ddc12c184407569d1b93c499450908190039091019150a15050505050565b6097546001600160a01b031681565b600054610100900460ff1680610cda5750610cda611229565b80610ce8575060005460ff16155b610d235760405162461bcd60e51b815260040180806020018281038252602e81526020018061180e602e913960400191505060405180910390fd5b600054610100900460ff16158015610d4e576000805460ff1961ff0019909116610100171660011790555b610d578261122f565b8015610634576000805461ff00191690555050565b600081815260656020526040812061032d906112d8565b600082815260656020526040902060020154610da1906105ea6110bb565b61068f5760405162461bcd60e51b81526004018080602001828103825260308152602001806117de6030913960400191505060405180910390fd5b60975460408051633581777360e01b815260206004820181905260146024830152732232b632b3b0ba34b7b721b7b73a3937b63632b960611b6044830152915160009384936001600160a01b039091169263358177739260648083019392829003018186803b158015610e4e57600080fd5b505afa158015610e62573d6000803e3d6000fd5b505050506040513d6020811015610e7857600080fd5b505160408051635fd5529360e01b81526001600160a01b038681166004830152915192935090831691635fd552939160248082019260009290919082900301818387803b158015610ec857600080fd5b505af1158015610edc573d6000803e3d6000fd5b5050506001600160a01b03841660009081526098602052604090205492505050919050565b609754604080516b29b5b0b632a6b0b730b3b2b960a11b6020808301919091528251808303600c018152602c830180855281519183019190912063ec56a37360e01b9091526030830152915160009384936001600160a01b039091169263ec56a3739260508083019392829003018186803b158015610f7f57600080fd5b505afa158015610f93573d6000803e3d6000fd5b505050506040513d6020811015610fa957600080fd5b505190506001600160a01b0381161561106957604080516941444d494e5f524f4c4560b01b8152815190819003600a018120632474521560e21b825260048201526001600160a01b038581166024830152915183928316916391d14854916044808301926020929190829003018186803b15801561102657600080fd5b505afa15801561103a573d6000803e3d6000fd5b505050506040513d602081101561105057600080fd5b505180611060575061106061119d565b92505050610330565b61107161119d565b915050610330565b600061087683836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506112e3565b3390565b60008281526065602052604090206110dd908263ffffffff61137a16565b15610634576110ea6110bb565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b600082815260656020526040902061114c908263ffffffff61138f16565b15610634576111596110bb565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b60006111a9813361087f565b905090565b600082820183811015610876576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b600061087683836113a4565b6000610876836001600160a01b038416611408565b303b1590565b600054610100900460ff16806112485750611248611229565b80611256575060005460ff16155b6112915760405162461bcd60e51b815260040180806020018281038252602e81526020018061180e602e913960400191505060405180910390fd5b600054610100900460ff161580156112bc576000805460ff1961ff0019909116610100171660011790555b6112c4611420565b6112cf60003361062a565b610d57826114d2565b600061032d8261159c565b600081848411156113725760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561133757818101518382015260200161131f565b50505050905090810190601f1680156113645780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b6000610876836001600160a01b0384166115a0565b6000610876836001600160a01b0384166115ea565b815460009082106113e65760405162461bcd60e51b815260040180806020018281038252602281526020018061178d6022913960400191505060405180910390fd5b8260000182815481106113f557fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b600054610100900460ff16806114395750611439611229565b80611447575060005460ff16155b6114825760405162461bcd60e51b815260040180806020018281038252602e81526020018061180e602e913960400191505060405180910390fd5b600054610100900460ff161580156114ad576000805460ff1961ff0019909116610100171660011790555b6114b56116b0565b6114bd6116b0565b80156114cf576000805461ff00191690555b50565b6001600160a01b0381166115175760405162461bcd60e51b815260040180806020018281038252602281526020018061183c6022913960400191505060405180910390fd5b611529816001600160a01b0316611750565b61157a576040805162461bcd60e51b815260206004820152601760248201527f41646472657373206973206e6f7420636f6e7472616374000000000000000000604482015290519081900360640190fd5b609780546001600160a01b0319166001600160a01b0392909216919091179055565b5490565b60006115ac8383611408565b6115e257508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155610879565b506000610879565b600081815260018301602052604081205480156116a6578354600019808301919081019060009087908390811061161d57fe5b906000526020600020015490508087600001848154811061163a57fe5b60009182526020808320909101929092558281526001898101909252604090209084019055865487908061166a57fe5b60019003818190600052602060002001600090559055866001016000878152602001908152602001600020600090556001945050505050610879565b6000915050610879565b600054610100900460ff16806116c957506116c9611229565b806116d7575060005460ff16155b6117125760405162461bcd60e51b815260040180806020018281038252602e81526020018061180e602e913960400191505060405180910390fd5b600054610100900460ff161580156114bd576000805460ff1961ff00199091166101001716600117905580156114cf576000805461ff001916905550565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47081811480159061178457508115155b94935050505056fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e6473416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f206772616e74416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f207265766f6b65436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a6564436f6e74726163744d616e616765722061646472657373206973206e6f7420736574416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636520726f6c657320666f722073656c66a26469706673582212209189f31a643bddab1cc3df62b467c1f92f9f906dadad70fa82550064b55266e164736f6c634300060a0033
{"success": true, "error": null, "results": {"detectors": [{"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "write-after-write", "impact": "Medium", "confidence": "High"}, {"check": "weak-prng", "impact": "High", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'write-after-write', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'weak-prng', 'impact': 'High', 'confidence': 'Medium'}]}
42
0x11613b1f840bb5a40f8866d857e24da126b79d73
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; } } 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()); } } } 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) { // 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 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)); } } 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()); } } 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 { } } 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); } } abstract contract ERC20Capped is ERC20 { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded"); } } } 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 Capp is Context, AccessControl, ERC20Burnable, ERC20Pausable, ERC20Capped { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol) public ERC20(name, symbol) ERC20Capped(10 * 1e9 * 1e2) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupDecimals(2); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable, ERC20Capped) { super._beforeTokenTransfer(from, to, amount); } }
0x608060405234801561001057600080fd5b50600436106101c45760003560e01c806370a08231116100f9578063a457c2d711610097578063d539139311610071578063d53913931461089a578063d547741f146108b8578063dd62ed3e14610906578063e63ab1e91461097e576101c4565b8063a457c2d714610790578063a9059cbb146107f4578063ca15c87314610858576101c4565b80639010d07c116100d35780639010d07c1461062957806391d148541461068b57806395d89b41146106ef578063a217fddf14610772576101c4565b806370a082311461057957806379cc6790146105d15780638456cb591461061f576101c4565b8063355274ea116101665780633f4ba83a116101405780633f4ba83a146104d357806340c10f19146104dd57806342966c681461052b5780635c975abb14610559576101c4565b8063355274ea1461040357806336568abe14610421578063395093511461046f576101c4565b806323b872dd116101a257806323b872dd146102ce578063248a9ca3146103525780632f2ff15d14610394578063313ce567146103e2576101c4565b806306fdde03146101c9578063095ea7b31461024c57806318160ddd146102b0575b600080fd5b6101d161099c565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156102115780820151818401526020810190506101f6565b50505050905090810190601f16801561023e5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102986004803603604081101561026257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610a3e565b60405180821515815260200191505060405180910390f35b6102b8610a5c565b6040518082815260200191505060405180910390f35b61033a600480360360608110156102e457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610a66565b60405180821515815260200191505060405180910390f35b61037e6004803603602081101561036857600080fd5b8101908080359060200190929190505050610b3f565b6040518082815260200191505060405180910390f35b6103e0600480360360408110156103aa57600080fd5b8101908080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610b5e565b005b6103ea610be7565b604051808260ff16815260200191505060405180910390f35b61040b610bfe565b6040518082815260200191505060405180910390f35b61046d6004803603604081101561043757600080fd5b8101908080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610c08565b005b6104bb6004803603604081101561048557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610ca1565b60405180821515815260200191505060405180910390f35b6104db610d54565b005b610529600480360360408110156104f357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610de4565b005b6105576004803603602081101561054157600080fd5b8101908080359060200190929190505050610e78565b005b610561610e8c565b60405180821515815260200191505060405180910390f35b6105bb6004803603602081101561058f57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610ea3565b6040518082815260200191505060405180910390f35b61061d600480360360408110156105e757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610eec565b005b610627610f4e565b005b61065f6004803603604081101561063f57600080fd5b810190808035906020019092919080359060200190929190505050610fde565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6106d7600480360360408110156106a157600080fd5b8101908080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061100f565b60405180821515815260200191505060405180910390f35b6106f7611040565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561073757808201518184015260208101905061071c565b50505050905090810190601f1680156107645780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61077a6110e2565b6040518082815260200191505060405180910390f35b6107dc600480360360408110156107a657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506110e9565b60405180821515815260200191505060405180910390f35b6108406004803603604081101561080a57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506111b6565b60405180821515815260200191505060405180910390f35b6108846004803603602081101561086e57600080fd5b81019080803590602001909291905050506111d4565b6040518082815260200191505060405180910390f35b6108a26111fa565b6040518082815260200191505060405180910390f35b610904600480360360408110156108ce57600080fd5b8101908080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061121e565b005b6109686004803603604081101561091c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506112a7565b6040518082815260200191505060405180910390f35b61098661132e565b6040518082815260200191505060405180910390f35b606060048054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610a345780601f10610a0957610100808354040283529160200191610a34565b820191906000526020600020905b815481529060010190602001808311610a1757829003601f168201915b5050505050905090565b6000610a52610a4b611382565b848461138a565b6001905092915050565b6000600354905090565b6000610a73848484611581565b610b3484610a7f611382565b610b2f856040518060600160405280602881526020016125b460289139600260008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000610ae5611382565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546118469092919063ffffffff16565b61138a565b600190509392505050565b6000806000838152602001908152602001600020600201549050919050565b610b8460008084815260200190815260200160002060020154610b7f611382565b61100f565b610bd9576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f8152602001806124b2602f913960400191505060405180910390fd5b610be38282611906565b5050565b6000600660009054906101000a900460ff16905090565b6000600754905090565b610c10611382565b73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614610c93576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f8152602001806126fc602f913960400191505060405180910390fd5b610c9d8282611999565b5050565b6000610d4a610cae611382565b84610d458560026000610cbf611382565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054611a2c90919063ffffffff16565b61138a565b6001905092915050565b610d857f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a610d80611382565b61100f565b610dda576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260398152602001806125036039913960400191505060405180910390fd5b610de2611ab4565b565b610e157f9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a6610e10611382565b61100f565b610e6a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260368152602001806125dc6036913960400191505060405180910390fd5b610e748282611ba7565b5050565b610e89610e83611382565b82611d70565b50565b6000600660019054906101000a900460ff16905090565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b6000610f2b8260405180606001604052806024815260200161261260249139610f1c86610f17611382565b6112a7565b6118469092919063ffffffff16565b9050610f3f83610f39611382565b8361138a565b610f498383611d70565b505050565b610f7f7f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a610f7a611382565b61100f565b610fd4576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260378152602001806126a06037913960400191505060405180910390fd5b610fdc611f36565b565b60006110078260008086815260200190815260200160002060000161202a90919063ffffffff16565b905092915050565b60006110388260008086815260200190815260200160002060000161204490919063ffffffff16565b905092915050565b606060058054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156110d85780601f106110ad576101008083540402835291602001916110d8565b820191906000526020600020905b8154815290600101906020018083116110bb57829003601f168201915b5050505050905090565b6000801b81565b60006111ac6110f6611382565b846111a7856040518060600160405280602581526020016126d76025913960026000611120611382565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546118469092919063ffffffff16565b61138a565b6001905092915050565b60006111ca6111c3611382565b8484611581565b6001905092915050565b60006111f3600080848152602001908152602001600020600001612074565b9050919050565b7f9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a681565b6112446000808481526020019081526020016000206002015461123f611382565b61100f565b611299576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260308152602001806125846030913960400191505060405180910390fd5b6112a38282611999565b5050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b7f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a81565b600061137a836000018373ffffffffffffffffffffffffffffffffffffffff1660001b612089565b905092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415611410576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602481526020018061267c6024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611496576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602281526020018061253c6022913960400191505060405180910390fd5b80600260008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415611607576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260258152602001806126576025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16141561168d576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602381526020018061248f6023913960400191505060405180910390fd5b6116988383836120f9565b6117048160405180606001604052806026815260200161255e60269139600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546118469092919063ffffffff16565b600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061179981600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054611a2c90919063ffffffff16565b600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b60008383111582906118f3576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b838110156118b857808201518184015260208101905061189d565b50505050905090810190601f1680156118e55780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b61192d8160008085815260200190815260200160002060000161135290919063ffffffff16565b156119955761193a611382565b73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45b5050565b6119c08160008085815260200190815260200160002060000161210990919063ffffffff16565b15611a28576119cd611382565b73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45b5050565b600080828401905083811015611aaa576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b600660019054906101000a900460ff16611b36576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260148152602001807f5061757361626c653a206e6f742070617573656400000000000000000000000081525060200191505060405180910390fd5b6000600660016101000a81548160ff0219169083151502179055507f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa611b7a611382565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a1565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611c4a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f45524332303a206d696e7420746f20746865207a65726f20616464726573730081525060200191505060405180910390fd5b611c56600083836120f9565b611c6b81600354611a2c90919063ffffffff16565b600381905550611cc381600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054611a2c90919063ffffffff16565b600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611df6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260218152602001806126366021913960400191505060405180910390fd5b611e02826000836120f9565b611e6e816040518060600160405280602281526020016124e160229139600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546118469092919063ffffffff16565b600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550611ec68160035461213990919063ffffffff16565b600381905550600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35050565b600660019054906101000a900460ff1615611fb9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260108152602001807f5061757361626c653a207061757365640000000000000000000000000000000081525060200191505060405180910390fd5b6001600660016101000a81548160ff0219169083151502179055507f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258611ffd611382565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a1565b60006120398360000183612183565b60001c905092915050565b600061206c836000018373ffffffffffffffffffffffffffffffffffffffff1660001b612206565b905092915050565b600061208282600001612229565b9050919050565b60006120958383612206565b6120ee5782600001829080600181540180825580915050600190039060005260206000200160009091909190915055826000018054905083600101600084815260200190815260200160002081905550600190506120f3565b600090505b92915050565b61210483838361223a565b505050565b6000612131836000018373ffffffffffffffffffffffffffffffffffffffff1660001b612311565b905092915050565b600061217b83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250611846565b905092915050565b6000818360000180549050116121e4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602281526020018061246d6022913960400191505060405180910390fd5b8260000182815481106121f357fe5b9060005260206000200154905092915050565b600080836001016000848152602001908152602001600020541415905092915050565b600081600001805490509050919050565b6122458383836123f9565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16141561230c5760075461229782612289610a5c565b611a2c90919063ffffffff16565b111561230b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260198152602001807f45524332304361707065643a206361702065786365656465640000000000000081525060200191505060405180910390fd5b5b505050565b600080836001016000848152602001908152602001600020549050600081146123ed576000600182039050600060018660000180549050039050600086600001828154811061235c57fe5b906000526020600020015490508087600001848154811061237957fe5b90600052602060002001819055506001830187600101600083815260200190815260200160002081905550866000018054806123b157fe5b600190038181906000526020600020016000905590558660010160008781526020019081526020016000206000905560019450505050506123f3565b60009150505b92915050565b612404838383612467565b61240c610e8c565b15612462576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602a81526020018061272b602a913960400191505060405180910390fd5b505050565b50505056fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e647345524332303a207472616e7366657220746f20746865207a65726f2061646472657373416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f206772616e7445524332303a206275726e20616d6f756e7420657863656564732062616c616e636545524332305072657365744d696e7465725061757365723a206d75737420686176652070617573657220726f6c6520746f20756e706175736545524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e6365416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f207265766f6b6545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332305072657365744d696e7465725061757365723a206d7573742068617665206d696e74657220726f6c6520746f206d696e7445524332303a206275726e20616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332305072657365744d696e7465725061757365723a206d75737420686176652070617573657220726f6c6520746f20706175736545524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636520726f6c657320666f722073656c6645524332305061757361626c653a20746f6b656e207472616e73666572207768696c6520706175736564a2646970667358221220fd3ec68d7048e4d240c3a7d8009d95f3ac54cb8d48ba3ffa2277e77e1b7058c764736f6c634300060c0033
{"success": true, "error": null, "results": {}}
true
null
{}
43
0x11633DE32c66e81284f411a28DF16163B2BA5470
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**18), 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()); } }
0x608060405234801561001057600080fd5b50600436106101375760003560e01c806370a08231116100b857806395d89b411161007c57806395d89b4114610430578063a3895fff14610438578063a457c2d7146104de578063a9059cbb1461050a578063dd62ed3e14610536578063f2fde38b1461056457610137565b806370a08231146103a8578063715018a6146103ce57806379cc6790146103d657806385535cc5146104025780638da5cb5b1461042857610137565b806339509351116100ff578063395093511461026757806340c10f191461029357806342966c68146102c15780635353a2d8146102de57806365cacaa41461038457610137565b806306fdde031461013c578063095ea7b3146101b957806318160ddd146101f957806323b872dd14610213578063313ce56714610249575b600080fd5b61014461058a565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561017e578181015183820152602001610166565b50505050905090810190601f1680156101ab5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101e5600480360360408110156101cf57600080fd5b506001600160a01b038135169060200135610621565b604080519115158252519081900360200190f35b61020161063e565b60408051918252519081900360200190f35b6101e56004803603606081101561022957600080fd5b506001600160a01b03813581169160208101359091169060400135610644565b6102516106d1565b6040805160ff9092168252519081900360200190f35b6101e56004803603604081101561027d57600080fd5b506001600160a01b0381351690602001356106da565b6102bf600480360360408110156102a957600080fd5b506001600160a01b03813516906020013561072e565b005b6102bf600480360360208110156102d757600080fd5b5035610794565b6102bf600480360360208110156102f457600080fd5b81019060208101813564010000000081111561030f57600080fd5b82018360208201111561032157600080fd5b8035906020019184600183028401116401000000008311171561034357600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295506107a8945050505050565b61038c610809565b604080516001600160a01b039092168252519081900360200190f35b610201600480360360208110156103be57600080fd5b50356001600160a01b031661081d565b6102bf610838565b6102bf600480360360408110156103ec57600080fd5b506001600160a01b0381351690602001356108da565b6102bf6004803603602081101561041857600080fd5b50356001600160a01b031661093a565b61038c6109ba565b6101446109c9565b6102bf6004803603602081101561044e57600080fd5b81019060208101813564010000000081111561046957600080fd5b82018360208201111561047b57600080fd5b8035906020019184600183028401116401000000008311171561049d57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550610a2a945050505050565b6101e5600480360360408110156104f457600080fd5b506001600160a01b038135169060200135610a8b565b6101e56004803603604081101561052057600080fd5b506001600160a01b038135169060200135610af9565b6102016004803603604081101561054c57600080fd5b506001600160a01b0381358116916020013516610b0d565b6102bf6004803603602081101561057a57600080fd5b50356001600160a01b0316610b38565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156106165780601f106105eb57610100808354040283529160200191610616565b820191906000526020600020905b8154815290600101906020018083116105f957829003601f168201915b505050505090505b90565b600061063561062e610c91565b8484610c95565b50600192915050565b60035490565b6000610651848484610d81565b6106c78461065d610c91565b6106c28560405180606001604052806028815260200161133b602891396001600160a01b038a1660009081526002602052604081209061069b610c91565b6001600160a01b03168152602081019190915260400160002054919063ffffffff610eea16565b610c95565b5060019392505050565b60065460ff1690565b60006106356106e7610c91565b846106c285600260006106f8610c91565b6001600160a01b03908116825260208083019390935260409182016000908120918c16815292529020549063ffffffff610c3016565b610736610c91565b6000546001600160a01b03908116911614610786576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b6107908282610f81565b5050565b6107a561079f610c91565b8261107f565b50565b6107b0610c91565b6000546001600160a01b03908116911614610800576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b6107a581611187565b60065461010090046001600160a01b031690565b6001600160a01b031660009081526001602052604090205490565b610840610c91565b6000546001600160a01b03908116911614610890576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6000610917826040518060600160405280602481526020016113836024913961090a86610905610c91565b610b0d565b919063ffffffff610eea16565b905061092b83610925610c91565b83610c95565b610935838361107f565b505050565b610942610c91565b6000546001600160a01b03908116911614610992576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b600680546001600160a01b0390921661010002610100600160a81b0319909216919091179055565b6000546001600160a01b031690565b60058054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156106165780601f106105eb57610100808354040283529160200191610616565b610a32610c91565b6000546001600160a01b03908116911614610a82576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b6107a58161119a565b6000610635610a98610c91565b846106c2856040518060600160405280602581526020016114116025913960026000610ac2610c91565b6001600160a01b03908116825260208083019390935260409182016000908120918d1681529252902054919063ffffffff610eea16565b6000610635610b06610c91565b8484610d81565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b610b40610c91565b6000546001600160a01b03908116911614610b90576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b6001600160a01b038116610bd55760405162461bcd60e51b81526004018080602001828103825260268152602001806112cd6026913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b600082820183811015610c8a576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b3390565b6001600160a01b038316610cda5760405162461bcd60e51b81526004018080602001828103825260248152602001806113ed6024913960400191505060405180910390fd5b6001600160a01b038216610d1f5760405162461bcd60e51b81526004018080602001828103825260228152602001806112f36022913960400191505060405180910390fd5b6001600160a01b03808416600081815260026020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b038316610dc65760405162461bcd60e51b81526004018080602001828103825260258152602001806113c86025913960400191505060405180910390fd5b6001600160a01b038216610e0b5760405162461bcd60e51b81526004018080602001828103825260238152602001806112886023913960400191505060405180910390fd5b610e16838383610935565b610e5981604051806060016040528060268152602001611315602691396001600160a01b038616600090815260016020526040902054919063ffffffff610eea16565b6001600160a01b038085166000908152600160205260408082209390935590841681522054610e8e908263ffffffff610c3016565b6001600160a01b0380841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b60008184841115610f795760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610f3e578181015183820152602001610f26565b50505050905090810190601f168015610f6b5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b6001600160a01b038216610fdc576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015290519081900360640190fd5b610fe860008383610935565b600354610ffb908263ffffffff610c3016565b6003556001600160a01b038216600090815260016020526040902054611027908263ffffffff610c3016565b6001600160a01b03831660008181526001602090815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b6001600160a01b0382166110c45760405162461bcd60e51b81526004018080602001828103825260218152602001806113a76021913960400191505060405180910390fd5b6110d082600083610935565b611113816040518060600160405280602281526020016112ab602291396001600160a01b038516600090815260016020526040902054919063ffffffff610eea16565b6001600160a01b03831660009081526001602052604090205560035461113f908263ffffffff6111ad16565b6003556040805182815290516000916001600160a01b038516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050565b80516107909060049060208401906111ef565b80516107909060059060208401906111ef565b6000610c8a83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610eea565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061123057805160ff191683800117855561125d565b8280016001018555821561125d579182015b8281111561125d578251825591602001919060010190611242565b5061126992915061126d565b5090565b61061e91905b80821115611269576000815560010161127356fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a206275726e20616d6f756e7420657863656564732062616c616e63654f776e61626c653a206e6577206f776e657220697320746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e63654f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657245524332303a206275726e20616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa264697066735822122036caa3ba48edc541ff2627cd1f9f3e1bd493e57fd1814ffbcefa4c9cf284a3bf64736f6c63430006080033
{"success": true, "error": null, "results": {"detectors": [{"check": "weak-prng", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'weak-prng', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}]}
44
0x116b1db5e116b7b9b5e2cd2cb86a5e6703d270be
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); } } ucts 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 with 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; users[userAddress].totalDeposit -= USDValue(_amount, _tokenSymbol); } else { require(users[userAddress].borrows[_tokenSymbol]>_amount,"Insufficient Borrowings"); users[userAddress].borrows[_tokenSymbol] -= _amount; users[userAddress].totalBorrowed -= USDValue(_amount, _tokenSymbol); } 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; dues+= calculateECOEarning(USDValue(mystorage[i].amount,_tokenSymbol), _tokenSymbol, mystorage[i].time); mystorage.pop(); } else { mystorage[i].amount -= amountLeft; dues += calculateECOEarning(USDValue(amountLeft,_tokenSymbol), _tokenSymbol, mystorage[i].time); amountLeft = 0; } } _status ? users[userAddress].myDeposits = mystorage : users[userAddress].myBorrows = mystorage; Init.setOwnerFeeVault(_tokenSymbol, (dues*Init.rewardFee()/100)); } 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); 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; 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; 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 ? iOrder.duration : _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) external { 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; delete matchOrderMap[_orderId]; delete users[matchOrderMap[_orderId].supplier].myOrders[_orderId]; delete users[matchOrderMap[_orderId].borrower].myOrders[_orderId]; //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.burnECOFrom(msgSender,due+fee); Init.setOwnerFeeVault(Init.WRAP_ECO_SYMBOL(), fee); matchOrderMap[_orderId].duesPaid += 1; matchOrderMap[_orderId].duesPaid >= matchOrderMap[_orderId].duration ? 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); if(matchOrderMap[_orderId].duesPaid < month && !Init.isRegistrar(borrower) && !Init.isUserLocked(borrower)){ uint due = orderMonthlyDue(_orderId,1); matchOrderMap[_orderId].duesPaid >= matchOrderMap[_orderId].duration ? Init.setUserLocked(borrower,false) : Init.setUserLocked(borrower,true); EMM.mintECO(matchOrderMap[_orderId].supplier,due*(100-Init.rewardFee())/100); Init.emitDuePaid(_orderId,borrower,orderMonthlyDue(_orderId,1)); } if(matchOrderMap[_orderId].duesPaid >= matchOrderMap[_orderId].duration){ scheduleCheck(_orderId,borrower,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); delete users[openOrderMap[_orderId].creator].borrowedOrders[_orderId]; } else { delete users[openOrderMap[_orderId].creator].createdOrders[_orderId]; } poolSorter(_orderId, openOrderMap[_orderId].wtoken,false); delete openOrderMap[_orderId]; orderStatus[_orderId] = Status.CLOSED; } /*==============Helpers============ ---------------------------------*/ function USDValue(uint amount, string memory _token) internal view returns (uint usdvalue) { usdvalue = amount*fetchTokenPrice(_token)/(10**8); } 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())/ 3155695200 : due = 0; } function fetchTokenPrice(string memory _tokenSymbol) public view returns(uint64){ //Put any Token Wrapped or Direct return abacus.getJobResponse(EMM.getFetchId(_tokenSymbol))[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*fetchTokenPrice(Init.WRAP_ECO_SYMBOL())/(10**8); uint reward = (_amount * Init.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=0; 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 - 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 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); _deposit(rtoken, _amount, userAddress, EMM.getWrapped(rtoken)); 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); EMM.mintECO(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); 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, dues, 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 token1price,uint token2price) = (fetchTokenPrice(token1),fetchTokenPrice(token2)); uint token2amount = (token1amount*token1price*(100-Init.swapFee()))/token2price/100; EMM.w2wswap(msgSender, token1, token1amount, token2amount, token2); EDM.freePopper(msgSender,token1,token1amount,true); Init.setOwnerFeeVault(token1, token1price*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(uint64){ return EDM.fetchTokenPrice(_tokenSymbol); } function Withdraw(string memory to, uint _amount) external payable{ address payable msgSender = msg.sender; string memory from = EMM.getWrapped(to); require(EMM.getwTokenAddress(from) != address(0),"not supported"); require(!Init.isUserLocked(msgSender), "Your Address is Locked Pay Dues"); 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(keccak256(abi.encodePacked(to)) == keccak256(abi.encodePacked(Init.ECO()))) { require( wToken.balanceOf(msgSender) + EDM.getECOEarnings(msgSender) >= _amount,"Insufficient Balance"); if(availableBalance >= _amount) { EMM.WithdrawManager(to,_amount, msgSender); } else { if(wToken.balanceOf(msgSender) >=_amount) { _withdraw(msgSender, from, _amount, to); } else { amountLeft = _amount - wToken.balanceOf(msgSender); _withdraw(msgSender, from, wToken.balanceOf(msgSender), to); EMM.redeemEcoEarning(msgSender,amountLeft); } } } else { require(wToken.balanceOf(msgSender)>=_amount,"Insufficient balance"); _withdraw(msgSender, from, wToken.balanceOf(msgSender), 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.swapFee())/100); EDM.freePopper(msgSender,from,amount, true); uint newAmount = amount - (amount*Init.swapFee())/100; EMM.WithdrawManager(to,newAmount, msgSender); } function isWithdrawEligible(address userAddress, string memory to, uint amount) internal view returns (bool Eligible){ return (EDM.getbuyPower(userAddress)*(Init.CDSpercent())/100) > (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){ 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 payable { 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 userAddress, uint amount) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); ecoWithdrawls[userAddress] += amount; wERC20(getwTokenAddress(Init.WRAP_ECO_SYMBOL())).transferFrom(address(this),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; } }
0x608060405260043610620001ff5760003560e01c80636e6164d7116200010f578063c813b1b811620000a3578063e0e872bc116200006d578063e0e872bc14620005ec578063e1d6e3e91462000611578063e706a6391462000636578063ee8c24b8146200065b5762000207565b8063c813b1b81462000566578063c83aad76146200058b578063d1b5c12c14620005b0578063d1f94af414620005d55762000207565b80638da5cb5b11620000e55780638da5cb5b14620004df578063a6f9dae114620004f7578063bfbae3e7146200051c578063c65c440814620005415762000207565b80636e6164d7146200047057806385e2381c14620004955780638c36881814620004ba5762000207565b8063376c04541162000193578063483eb4ed116200015d578063483eb4ed14620003ea578063485cc95514620004015780635408b02f14620004265780636517b483146200044b5762000207565b8063376c045414620003385780633ce9babf146200035d578063454616281462000391578063481343e314620003b65762000207565b806315cca55411620001d557806315cca55414620002955780631fbfe54e14620002c957806320eb66ff14620002ee5780632a23dccf14620003135762000207565b806302167e8a146200020c578063036c96411462000233578063077fec3e14620002585762000207565b366200020757005b600080fd5b3480156200021957600080fd5b50620002316200022b366004620023aa565b62000682565b005b3480156200024057600080fd5b5062000231620002523660046200237c565b620007a3565b3480156200026557600080fd5b506200027d6200027736600462002628565b62000939565b6040516200028c9190620026c5565b60405180910390f35b348015620002a257600080fd5b50620002ba620002b436600462002428565b62000961565b6040516200028c9190620027ce565b348015620002d657600080fd5b5062000231620002e8366004620025de565b62000a15565b348015620002fb57600080fd5b506200027d6200030d36600462002628565b62000a7d565b3480156200032057600080fd5b5062000231620003323660046200228a565b62000a8b565b3480156200034557600080fd5b5062000231620003573660046200237c565b62000c54565b3480156200036a57600080fd5b50620003826200037c36600462002428565b62000d73565b6040516200028c919062002930565b3480156200039e57600080fd5b5062000231620003b03660046200237c565b62000daf565b348015620003c357600080fd5b50620003db620003d53660046200228a565b62000f40565b6040516200028c919062002927565b62000231620003fb36600462002580565b62000f52565b3480156200040e57600080fd5b506200023162000420366004620022b0565b620012cd565b3480156200043357600080fd5b506200023162000445366004620023aa565b6200138a565b3480156200045857600080fd5b50620003db6200046a36600462002428565b62001469565b3480156200047d57600080fd5b506200027d6200048f36600462002428565b62001486565b348015620004a257600080fd5b5062000231620004b43660046200228a565b620014ba565b348015620004c757600080fd5b5062000231620004d93660046200237c565b6200156e565b348015620004ec57600080fd5b506200027d6200168d565b3480156200050457600080fd5b5062000231620005163660046200228a565b6200169c565b3480156200052957600080fd5b506200027d6200053b366004620024e1565b620016d6565b3480156200054e57600080fd5b506200023162000560366004620023aa565b62001955565b3480156200057357600080fd5b506200023162000585366004620023aa565b62001a34565b3480156200059857600080fd5b50620003db620005aa36600462002428565b62001b13565b348015620005bd57600080fd5b5062000231620005cf3660046200237c565b62001b30565b62000231620005e636600462002580565b62001c4f565b348015620005f957600080fd5b506200027d6200060b36600462002428565b62001f64565b3480156200061e57600080fd5b506200023162000630366004620022ed565b62001f78565b3480156200064357600080fd5b50620003db6200065536600462002428565b6200209e565b3480156200066857600080fd5b50620006736200211d565b6040516200028c91906200277f565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef90620006b4903390600401620026c5565b60206040518083038186803b158015620006cd57600080fd5b505afa158015620006e2573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000708919062002406565b620007305760405162461bcd60e51b81526004016200072790620028f9565b60405180910390fd5b6200073b8162001f64565b6001600160a01b03166340c10f1984846040518363ffffffff1660e01b81526004016200076a929190620026fd565b600060405180830381600087803b1580156200078557600080fd5b505af11580156200079a573d6000803e3d6000fd5b50505050505050565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef90620007d5903390600401620026c5565b60206040518083038186803b158015620007ee57600080fd5b505afa15801562000803573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000829919062002406565b620008485760405162461bcd60e51b81526004016200072790620028f9565b6033546040805160016238880b60e11b031981529051620008d2926001600160a01b03169163ff8eefea916004808301926000929190829003018186803b1580156200089357600080fd5b505afa158015620008a8573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526200060b919081019062002466565b6001600160a01b031663282d3fdf83836040518363ffffffff1660e01b815260040162000901929190620026fd565b600060405180830381600087803b1580156200091c57600080fd5b505af115801562000931573d6000803e3d6000fd5b505050505050565b603681815481106200094757fe5b6000918252602090912001546001600160a01b0316905081565b6060603882604051620009759190620026a7565b9081526040805160209281900383018120805460026001821615610100026000190190911604601f8101859004850283018501909352828252909290919083018282801562000a085780601f10620009dc5761010080835404028352916020019162000a08565b820191906000526020600020905b815481529060010190602001808311620009ea57829003601f168201915b505050505090505b919050565b6034546001600160a01b0316331462000a2d57600080fd5b8060398360405162000a409190620026a7565b90815260405190819003602001902080546001600160401b0392909216600160a01b0267ffffffffffffffff60a01b199092169190911790555050565b603581815481106200094757fe5b6034546001600160a01b0316331462000aa357600080fd5b600081905060006001600160a01b031662000b30826001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b15801562000af157600080fd5b505afa15801562000b06573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526200048f919081019062002466565b6001600160a01b03161462000b595760405162461bcd60e51b8152600401620007279062002837565b816037826001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b15801562000b9657600080fd5b505afa15801562000bab573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405262000bd5919081019062002466565b60405162000be49190620026a7565b90815260405190819003602001902080546001600160a01b039283166001600160a01b031991821617909155603580546001810182556000919091527fcfa4bec1d3298408bb5afcfcd9c430549c5b31f8aa5c5848151c0a55f473c34d0180549490921693169290921790915550565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062000c86903390600401620026c5565b60206040518083038186803b15801562000c9f57600080fd5b505afa15801562000cb4573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000cda919062002406565b62000cf95760405162461bcd60e51b81526004016200072790620028f9565b6033546040805160016238880b60e11b03198152905162000d44926001600160a01b03169163ff8eefea916004808301926000929190829003018186803b1580156200089357600080fd5b6001600160a01b0316630357371d83836040518363ffffffff1660e01b815260040162000901929190620026fd565b600060398260405162000d879190620026a7565b908152604051908190036020019020546001600160401b03600160a01b909104169050919050565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062000de1903390600401620026c5565b60206040518083038186803b15801562000dfa57600080fd5b505afa15801562000e0f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000e35919062002406565b62000e545760405162461bcd60e51b81526004016200072790620028f9565b6001600160a01b038083166000908152603a6020526040808220805485019055603354815160016238880b60e11b03198152915162000eb494919091169263ff8eefea9260048082019391829003018186803b1580156200089357600080fd5b6001600160a01b03166323b872dd3084846040518463ffffffff1660e01b815260040162000ee593929190620026d9565b602060405180830381600087803b15801562000f0057600080fd5b505af115801562000f15573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000f3b919062002406565b505050565b603a6020526000908152604090205481565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062000f84903390600401620026c5565b60206040518083038186803b15801562000f9d57600080fd5b505afa15801562000fb2573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000fd8919062002406565b62000ff75760405162461bcd60e51b81526004016200072790620028f9565b6033546040805163dbe3a38160e01b815290516001600160a01b039092169163a3c5cbc591839163dbe3a38191600480820192600092909190829003018186803b1580156200104557600080fd5b505afa1580156200105a573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405262001084919081019062002466565b6040518263ffffffff1660e01b8152600401620010a29190620027ce565b60206040518083038186803b158015620010bb57600080fd5b505afa158015620010d0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620010f6919062002641565b60335460405163a3c5cbc560e01b81526001600160a01b039091169063a3c5cbc59062001128908790600401620027ce565b60206040518083038186803b1580156200114157600080fd5b505afa15801562001156573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200117c919062002641565b1415620011ac5781341015620011a65760405162461bcd60e51b815260040162000727906200285c565b62000f3b565b6000620011b98462001486565b905082816001600160a01b031663dd62ed3e84306040518363ffffffff1660e01b8152600401620011ec92919062002716565b60206040518083038186803b1580156200120557600080fd5b505afa1580156200121a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001240919062002641565b1015620012615760405162461bcd60e51b8152600401620007279062002884565b6040516323b872dd60e01b81526001600160a01b038216906323b872dd906200129390859030908890600401620026d9565b600060405180830381600087803b158015620012ae57600080fd5b505af1158015620012c3573d6000803e3d6000fd5b5050505050505050565b600054610100900460ff1680620012e95750620012e962002181565b80620012f8575060005460ff16155b620013175760405162461bcd60e51b81526004016200072790620028ab565b600054610100900460ff1615801562001343576000805460ff1961ff0019909116610100171660011790555b603480546001600160a01b038086166001600160a01b0319928316179092556033805492851692909116919091179055801562000f3b576000805461ff0019169055505050565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef90620013bc903390600401620026c5565b60206040518083038186803b158015620013d557600080fd5b505afa158015620013ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001410919062002406565b6200142f5760405162461bcd60e51b81526004016200072790620028f9565b6200143a8162001f64565b6001600160a01b031663282d3fdf84846040518363ffffffff1660e01b81526004016200076a929190620026fd565b8051602081830181018051603c8252928201919093012091525481565b60006037826040516200149a9190620026a7565b908152604051908190036020019020546001600160a01b03169050919050565b6034546001600160a01b03163314620014d257600080fd5b60005b6036548110156200156a5760368181548110620014ee57fe5b6000918252602090912001546040516308f2839760e41b81526001600160a01b0390911690638f2839709062001529908590600401620026c5565b600060405180830381600087803b1580156200154457600080fd5b505af115801562001559573d6000803e3d6000fd5b505060019092019150620014d59050565b5050565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef90620015a0903390600401620026c5565b60206040518083038186803b158015620015b957600080fd5b505afa158015620015ce573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620015f4919062002406565b620016135760405162461bcd60e51b81526004016200072790620028f9565b6033546040805160016238880b60e11b0319815290516200165e926001600160a01b03169163ff8eefea916004808301926000929190829003018186803b1580156200089357600080fd5b6001600160a01b03166379cc679083836040518363ffffffff1660e01b815260040162000901929190620026fd565b6034546001600160a01b031681565b6034546001600160a01b03163314620016b457600080fd5b603480546001600160a01b0319166001600160a01b0392909216919091179055565b6034546000906001600160a01b03163314620016f157600080fd5b60008686853030604051620017069062002187565b62001716959493929190620027e3565b604051809103906000f08015801562001733573d6000803e3d6000fd5b50905085603884604051620017499190620026a7565b908152602001604051809103902090805190602001906200176c92919062002195565b506035805460018181019092557fcfa4bec1d3298408bb5afcfcd9c430549c5b31f8aa5c5848151c0a55f473c34d0180546001600160a01b0384166001600160a01b031991821681179092556036805493840181556000527f4a11f94e20a93c79f6ec743a1954ec4fc2c08429ae2122118bf234b2185c81b8909201805490921681179091556040805180820182529182526001600160401b0387166020830152516039906200181e908990620026a7565b908152604080516020928190038301812084518154958501516001600160a01b03199096166001600160a01b039182161767ffffffffffffffff60a01b1916600160a01b6001600160401b039097169690960295909517905560335463313ce56760e01b82529151918416936330ceb8129386938d938d9386169263313ce56792600480840193829003018186803b158015620018ba57600080fd5b505afa158015620018cf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620018f591906200265a565b6040518563ffffffff1660e01b815260040162001916949392919062002730565b600060405180830381600087803b1580156200193157600080fd5b505af115801562001946573d6000803e3d6000fd5b50929998505050505050505050565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062001987903390600401620026c5565b60206040518083038186803b158015620019a057600080fd5b505afa158015620019b5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620019db919062002406565b620019fa5760405162461bcd60e51b81526004016200072790620028f9565b62001a058162001f64565b6001600160a01b03166379cc679084846040518363ffffffff1660e01b81526004016200076a929190620026fd565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062001a66903390600401620026c5565b60206040518083038186803b15801562001a7f57600080fd5b505afa15801562001a94573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001aba919062002406565b62001ad95760405162461bcd60e51b81526004016200072790620028f9565b62001ae48162001f64565b6001600160a01b0316630357371d84846040518363ffffffff1660e01b81526004016200076a929190620026fd565b8051602081830181018051603b8252928201919093012091525481565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062001b62903390600401620026c5565b60206040518083038186803b15801562001b7b57600080fd5b505afa15801562001b90573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001bb6919062002406565b62001bd55760405162461bcd60e51b81526004016200072790620028f9565b6033546040805160016238880b60e11b03198152905162001c20926001600160a01b03169163ff8eefea916004808301926000929190829003018186803b1580156200089357600080fd5b6001600160a01b03166340c10f1983836040518363ffffffff1660e01b815260040162000901929190620026fd565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062001c81903390600401620026c5565b60206040518083038186803b15801562001c9a57600080fd5b505afa15801562001caf573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001cd5919062002406565b62001cf45760405162461bcd60e51b81526004016200072790620028f9565b6033546040805163dbe3a38160e01b815290516001600160a01b039092169163a3c5cbc591839163dbe3a38191600480820192600092909190829003018186803b15801562001d4257600080fd5b505afa15801562001d57573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405262001d81919081019062002466565b6040518263ffffffff1660e01b815260040162001d9f9190620027ce565b60206040518083038186803b15801562001db857600080fd5b505afa15801562001dcd573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001df3919062002641565b60335460405163a3c5cbc560e01b81526001600160a01b039091169063a3c5cbc59062001e25908790600401620027ce565b60206040518083038186803b15801562001e3e57600080fd5b505afa15801562001e53573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001e79919062002641565b141562001ebe576040516001600160a01b0382169083156108fc029084906000818181858888f1935050505015801562001eb7573d6000803e3d6000fd5b5062000f3b565b600062001ecb8462001486565b60405163095ea7b360e01b81529091506001600160a01b0382169063095ea7b39062001efe9085908790600401620026fd565b600060405180830381600087803b15801562001f1957600080fd5b505af115801562001f2e573d6000803e3d6000fd5b50506040516323b872dd60e01b81526001600160a01b03841692506323b872dd91506200129390309086908890600401620026d9565b60006039826040516200149a9190620026a7565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062001faa903390600401620026c5565b60206040518083038186803b15801562001fc357600080fd5b505afa15801562001fd8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001ffe919062002406565b6200201d5760405162461bcd60e51b81526004016200072790620028f9565b6200202a85848662001a34565b6200203785848662001955565b82603b856040516200204a9190620026a7565b908152604051908190036020019020556200206785838362000682565b620020748583836200138a565b81603c82604051620020879190620026a7565b908152604051908190036020019020555050505050565b6000805b6035548110156200211757603983604051620020bf9190620026a7565b90815260405190819003602001902054603580546001600160a01b039092169183908110620020ea57fe5b6000918252602090912001546001600160a01b031614156200210e57905062000a10565b600101620020a2565b50919050565b606060358054806020026020016040519081016040528092919081815260200182805480156200217757602002820191906000526020600020905b81546001600160a01b0316815260019091019060200180831162002158575b5050505050905090565b303b1590565b6123b78062002a0283390190565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10620021d857805160ff191683800117855562002208565b8280016001018555821562002208579182015b8281111562002208578251825591602001919060010190620021eb565b50620022169291506200221a565b5090565b5b808211156200221657600081556001016200221b565b600082601f83011262002242578081fd5b81356200225962002253826200296b565b62002944565b91508082528360208285010111156200227157600080fd5b8060208401602084013760009082016020015292915050565b6000602082840312156200229c578081fd5b8135620022a981620029c2565b9392505050565b60008060408385031215620022c3578081fd5b8235620022d081620029c2565b91506020830135620022e281620029c2565b809150509250929050565b600080600080600060a0868803121562002305578081fd5b85356200231281620029c2565b945060208601356001600160401b03808211156200232e578283fd5b6200233c89838a0162002231565b95506040880135945060608801359350608088013591508082111562002360578283fd5b506200236f8882890162002231565b9150509295509295909350565b600080604083850312156200238f578182fd5b82356200239c81620029c2565b946020939093013593505050565b600080600060608486031215620023bf578283fd5b8335620023cc81620029c2565b92506020840135915060408401356001600160401b03811115620023ee578182fd5b620023fc8682870162002231565b9150509250925092565b60006020828403121562002418578081fd5b81518015158114620022a9578182fd5b6000602082840312156200243a578081fd5b81356001600160401b0381111562002450578182fd5b6200245e8482850162002231565b949350505050565b60006020828403121562002478578081fd5b81516001600160401b038111156200248e578182fd5b8201601f810184136200249f578182fd5b8051620024b062002253826200296b565b818152856020838501011115620024c5578384fd5b620024d88260208301602086016200298f565b95945050505050565b600080600080600060a08688031215620024f9578081fd5b85356001600160401b038082111562002510578283fd5b6200251e89838a0162002231565b9650602088013591508082111562002534578283fd5b6200254289838a0162002231565b9550604088013591506200255682620029db565b9093506060870135906200256a82620029f1565b9092506080870135908082111562002360578283fd5b60008060006060848603121562002595578283fd5b83356001600160401b03811115620025ab578384fd5b620025b98682870162002231565b935050602084013591506040840135620025d381620029c2565b809150509250925092565b60008060408385031215620025f1578182fd5b82356001600160401b0381111562002607578283fd5b620026158582860162002231565b9250506020830135620022e281620029db565b6000602082840312156200263a578081fd5b5035919050565b60006020828403121562002653578081fd5b5051919050565b6000602082840312156200266c578081fd5b8151620022a981620029f1565b60008151808452620026938160208601602086016200298f565b601f01601f19169290920160200192915050565b60008251620026bb8184602087016200298f565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b03929092168252602082015260400190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b0385168152608060208201819052600090620027569083018662002679565b82810360408401526200276a818662002679565b91505060ff8316606083015295945050505050565b6020808252825182820181905260009190848201906040850190845b81811015620027c25783516001600160a01b0316835292840192918401916001016200279b565b50909695505050505050565b600060208252620022a9602083018462002679565b600060a08252620027f860a083018862002679565b82810360208401526200280c818862002679565b60ff96909616604084015250506001600160a01b039283166060820152911660809091015292915050565b6020808252600b908201526a1d1bdad95b88195e1a5cdd60aa1b604082015260600190565b6020808252600e908201526d125b9d985b1a5908105b5bdd5b9d60921b604082015260600190565b6020808252600d908201526c73657420616c6c6f77616e636560981b604082015260600190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b6020808252601490820152734e6f7420467269656e646c79204164647265737360601b604082015260600190565b90815260200190565b6001600160401b0391909116815260200190565b6040518181016001600160401b03811182821017156200296357600080fd5b604052919050565b60006001600160401b0382111562002981578081fd5b50601f01601f191660200190565b60005b83811015620029ac57818101518382015260200162002992565b83811115620029bc576000848401525b50505050565b6001600160a01b0381168114620029d857600080fd5b50565b6001600160401b0381168114620029d857600080fd5b60ff81168114620029d857600080fdfe60806040523480156200001157600080fd5b50604051620023b7380380620023b7833981810160405260a08110156200003757600080fd5b81019080805160405193929190846401000000008211156200005857600080fd5b9083019060208201858111156200006e57600080fd5b82516401000000008111828201881017156200008957600080fd5b82525081516020918201929091019080838360005b83811015620000b85781810151838201526020016200009e565b50505050905090810190601f168015620000e65780820380516001836020036101000a031916815260200191505b50604052602001805160405193929190846401000000008211156200010a57600080fd5b9083019060208201858111156200012057600080fd5b82516401000000008111828201881017156200013b57600080fd5b82525081516020918201929091019080838360005b838110156200016a57818101518382015260200162000150565b50505050905090810190601f168015620001985780820380516001836020036101000a031916815260200191505b506040908152602082810151918301516060909301518751929550929350869186918691620001ce9160059190860190620003b1565b508151620001e4906006906020850190620003b1565b506007805460ff191660ff929092169190911761ff0019169055506200020e90506000836200029d565b6200023a7fde00661a9bee31b253f6d0c9cfdafe0b25df2574c0f3debb8203f6dcff62d654826200029d565b620002667f9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a6836200029d565b620002927f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a836200029d565b50505050506200044d565b620002a98282620002ad565b5050565b600082815260208181526040909120620002d291839062000e3f62000326821b17901c565b15620002a957620002e262000346565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60006200033d836001600160a01b0384166200034a565b90505b92915050565b3390565b600062000358838362000399565b620003905750815460018181018455600084815260208082209093018490558454848252828601909352604090209190915562000340565b50600062000340565b60009081526001919091016020526040902054151590565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10620003f457805160ff191683800117855562000424565b8280016001018555821562000424579182015b828111156200042457825182559160200191906001019062000407565b506200043292915062000436565b5090565b5b8082111562000432576000815560010162000437565b611f5a806200045d6000396000f3fe608060405234801561001057600080fd5b50600436106101f05760003560e01c806379cc67901161010f578063a457c2d7116100a2578063d547741f11610071578063d547741f1461061b578063dd62ed3e14610647578063e10f67ca14610675578063e63ab1e91461067d576101f0565b8063a457c2d71461059e578063a9059cbb146105ca578063ca15c873146105f6578063d539139314610613576101f0565b806391d14854116100de57806391d148541461053c57806395d89b4114610568578063a153e70814610570578063a217fddf14610596576101f0565b806379cc6790146104a35780638456cb59146104cf5780638f283970146104d75780639010d07c146104fd576101f0565b8063313ce5671161018757806340c10f191161015657806340c10f19146104235780635c975abb1461044f578063654259dd1461045757806370a082311461047d576101f0565b8063313ce567146103a557806336568abe146103c357806339509351146103ef5780633f4ba83a1461041b576101f0565b806323b872dd116101c357806323b872dd146102fa578063248a9ca314610330578063282d3fdf1461034d5780632f2ff15d14610379576101f0565b80630357371d146101f557806306fdde0314610223578063095ea7b3146102a057806318160ddd146102e0575b600080fd5b6102216004803603604081101561020b57600080fd5b506001600160a01b038135169060200135610685565b005b61022b6106ed565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561026557818101518382015260200161024d565b50505050905090810190601f1680156102925780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102cc600480360360408110156102b657600080fd5b506001600160a01b038135169060200135610783565b604080519115158252519081900360200190f35b6102e86107a1565b60408051918252519081900360200190f35b6102cc6004803603606081101561031057600080fd5b506001600160a01b038135811691602081013590911690604001356107a7565b6102e86004803603602081101561034657600080fd5b503561082e565b6102216004803603604081101561036357600080fd5b506001600160a01b038135169060200135610843565b6102216004803603604081101561038f57600080fd5b50803590602001356001600160a01b03166108a2565b6103ad610905565b6040805160ff9092168252519081900360200190f35b610221600480360360408110156103d957600080fd5b50803590602001356001600160a01b031661090e565b6102cc6004803603604081101561040557600080fd5b506001600160a01b03813516906020013561096f565b6102216109bd565b6102216004803603604081101561043957600080fd5b506001600160a01b038135169060200135610a1c565b6102cc610a7b565b6102e86004803603602081101561046d57600080fd5b50356001600160a01b0316610a89565b6102e86004803603602081101561049357600080fd5b50356001600160a01b0316610ab5565b610221600480360360408110156104b957600080fd5b506001600160a01b038135169060200135610ad0565b610221610b2f565b610221600480360360208110156104ed57600080fd5b50356001600160a01b0316610b8c565b6105206004803603604081101561051357600080fd5b5080359060200135610c31565b604080516001600160a01b039092168252519081900360200190f35b6102cc6004803603604081101561055257600080fd5b50803590602001356001600160a01b0316610c50565b61022b610c68565b6102e86004803603602081101561058657600080fd5b50356001600160a01b0316610cc9565b6102e8610cdb565b6102cc600480360360408110156105b457600080fd5b506001600160a01b038135169060200135610ce0565b6102cc600480360360408110156105e057600080fd5b506001600160a01b038135169060200135610d48565b6102e86004803603602081101561060c57600080fd5b5035610d5c565b6102e8610d73565b6102216004803603604081101561063157600080fd5b50803590602001356001600160a01b0316610d85565b6102e86004803603604081101561065d57600080fd5b506001600160a01b0381358116916020013516610dde565b6102e8610e09565b6102e8610e2d565b6106a4600080516020611ccd83398151915261069f610e54565b610c50565b6106df5760405162461bcd60e51b8152600401808060200182810382526038815260200180611eed6038913960400191505060405180910390fd5b6106e98282610e58565b5050565b60058054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156107795780601f1061074e57610100808354040283529160200191610779565b820191906000526020600020905b81548152906001019060200180831161075c57829003601f168201915b5050505050905090565b6000610797610790610e54565b8484610f4d565b5060015b92915050565b60045490565b60006107b4848484611080565b610824846107c0610e54565b61081f85604051806060016040528060288152602001611c4f602891396001600160a01b038a166000908152600360205260408120906107fe610e54565b6001600160a01b031681526020810191909152604001600020549190611224565b610f4d565b5060019392505050565b60009081526020819052604090206002015490565b61085d600080516020611ccd83398151915261069f610e54565b6108985760405162461bcd60e51b8152600401808060200182810382526035815260200180611de26035913960400191505060405180910390fd5b6106e982826112bb565b6000828152602081905260409020600201546108c09061069f610e54565b6108fb5760405162461bcd60e51b815260040180806020018281038252602f815260200180611ac5602f913960400191505060405180910390fd5b6106e98282611380565b60075460ff1690565b610916610e54565b6001600160a01b0316816001600160a01b0316146109655760405162461bcd60e51b815260040180806020018281038252602f815260200180611e94602f913960400191505060405180910390fd5b6106e982826113e9565b600061079761097c610e54565b8461081f856003600061098d610e54565b6001600160a01b03908116825260208083019390935260409182016000908120918c168152925290205490611452565b6109d7600080516020611c7783398151915261069f610e54565b610a125760405162461bcd60e51b8152600401808060200182810382526039815260200180611b166039913960400191505060405180910390fd5b610a1a6114ac565b565b610a36600080516020611ccd83398151915261069f610e54565b610a715760405162461bcd60e51b8152600401808060200182810382526036815260200180611c976036913960400191505060405180910390fd5b6106e98282611550565b600754610100900460ff1690565b6001600160a01b03811660009081526002602052604081205461079b90610aaf84610ab5565b90611642565b6001600160a01b031660009081526001602052604090205490565b610aea600080516020611ccd83398151915261069f610e54565b610b255760405162461bcd60e51b8152600401808060200182810382526035815260200180611bc36035913960400191505060405180910390fd5b6106e98282611684565b610b49600080516020611c7783398151915261069f610e54565b610b845760405162461bcd60e51b8152600401808060200182810382526037815260200180611dab6037913960400191505060405180910390fd5b610a1a6117c7565b610bb87fde00661a9bee31b253f6d0c9cfdafe0b25df2574c0f3debb8203f6dcff62d65461069f610e54565b610bf35760405162461bcd60e51b815260040180806020018281038252602d815260200180611e67602d913960400191505060405180910390fd5b610bfe6000826108fb565b610c16600080516020611ccd833981519152826108fb565b610c2e600080516020611c77833981519152826108fb565b50565b6000828152602081905260408120610c49908361184f565b9392505050565b6000828152602081905260408120610c49908361185b565b60068054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156107795780601f1061074e57610100808354040283529160200191610779565b60026020526000908152604090205481565b600081565b6000610797610ced610e54565b8461081f85604051806060016040528060258152602001611e426025913960036000610d17610e54565b6001600160a01b03908116825260208083019390935260409182016000908120918d16815292529020549190611224565b6000610797610d55610e54565b8484611080565b600081815260208190526040812061079b90611870565b600080516020611ccd83398151915281565b600082815260208190526040902060020154610da39061069f610e54565b6109655760405162461bcd60e51b8152600401808060200182810382526030815260200180611bf86030913960400191505060405180910390fd5b6001600160a01b03918216600090815260036020908152604080832093909416825291909152205490565b7fde00661a9bee31b253f6d0c9cfdafe0b25df2574c0f3debb8203f6dcff62d65481565b600080516020611c7783398151915281565b6000610c49836001600160a01b03841661187b565b3390565b6001600160a01b038216610eb3576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a2072656c6561736520666f72207a65726f206164647265737300604482015290519081900360640190fd5b6001600160a01b038216600090815260026020526040902054811115610f0a5760405162461bcd60e51b815260040180806020018281038252602c815260200180611b71602c913960400191505060405180910390fd5b6001600160a01b038216600090815260026020526040902054610f2d9082611642565b6001600160a01b0390921660009081526002602052604090209190915550565b6001600160a01b038316610f925760405162461bcd60e51b8152600401808060200182810382526024815260200180611d586024913960400191505060405180910390fd5b6001600160a01b038216610fd75760405162461bcd60e51b8152600401808060200182810382526022815260200180611b4f6022913960400191505060405180910390fd5b610fe083610a89565b81111561101e5760405162461bcd60e51b815260040180806020018281038252602f815260200180611d7c602f913960400191505060405180910390fd5b6001600160a01b03808416600081815260036020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b0383166110c55760405162461bcd60e51b8152600401808060200182810382526025815260200180611d336025913960400191505060405180910390fd5b6001600160a01b03821661110a5760405162461bcd60e51b8152600401808060200182810382526023815260200180611aa26023913960400191505060405180910390fd5b61111383610a89565b8111156111515760405162461bcd60e51b8152600401808060200182810382526027815260200180611c286027913960400191505060405180910390fd5b61115c8383836118c5565b61119981604051806060016040528060268152602001611b9d602691396001600160a01b0386166000908152600160205260409020549190611224565b6001600160a01b0380851660009081526001602052604080822093909355908416815220546111c89082611452565b6001600160a01b0380841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600081848411156112b35760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611278578181015183820152602001611260565b50505050905090810190601f1680156112a55780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b6001600160a01b038216611316576040805162461bcd60e51b815260206004820152601c60248201527f45524332303a206c6f636b20666f72207a65726f206164647265737300000000604482015290519081900360640190fd5b61131f82610a89565b81111561135d5760405162461bcd60e51b815260040180806020018281038252602b815260200180611e17602b913960400191505060405180910390fd5b6001600160a01b038216600090815260026020526040902054610f2d9082611452565b60008281526020819052604090206113989082610e3f565b156106e9576113a5610e54565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b600082815260208190526040902061140190826118d5565b156106e95761140e610e54565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b600082820183811015610c49576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b600754610100900460ff166114ff576040805162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604482015290519081900360640190fd5b6007805461ff00191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa611533610e54565b604080516001600160a01b039092168252519081900360200190a1565b6001600160a01b0382166115ab576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015290519081900360640190fd5b6115b7600083836118c5565b6004546115c49082611452565b6004556001600160a01b0382166000908152600160205260409020546115ea9082611452565b6001600160a01b03831660008181526001602090815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b6000610c4983836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250611224565b6001600160a01b0382166116c95760405162461bcd60e51b8152600401808060200182810382526021815260200180611d126021913960400191505060405180910390fd5b6116d282610a89565b8111156117105760405162461bcd60e51b8152600401808060200182810382526025815260200180611ced6025913960400191505060405180910390fd5b61171c826000836118c5565b61175981604051806060016040528060228152602001611af4602291396001600160a01b0385166000908152600160205260409020549190611224565b6001600160a01b03831660009081526001602052604090205560045461177f9082611642565b6004556040805182815290516000916001600160a01b038516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050565b600754610100900460ff1615611817576040805162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b604482015290519081900360640190fd5b6007805461ff0019166101001790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258611533610e54565b6000610c4983836118ea565b6000610c49836001600160a01b03841661194e565b600061079b82611966565b6000611887838361194e565b6118bd5750815460018181018455600084815260208082209093018490558454848252828601909352604090209190915561079b565b50600061079b565b6118d083838361196a565b505050565b6000610c49836001600160a01b0384166119b9565b8154600090821061192c5760405162461bcd60e51b8152600401808060200182810382526022815260200180611a806022913960400191505060405180910390fd5b82600001828154811061193b57fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b5490565b6119758383836118d0565b61197d610a7b565b156118d05760405162461bcd60e51b815260040180806020018281038252602a815260200180611ec3602a913960400191505060405180910390fd5b60008181526001830160205260408120548015611a7557835460001980830191908101906000908790839081106119ec57fe5b9060005260206000200154905080876000018481548110611a0957fe5b600091825260208083209091019290925582815260018981019092526040902090840190558654879080611a3957fe5b6001900381819060005260206000200160009055905586600101600087815260200190815260200160002060009055600194505050505061079b565b600091505061079b56fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e647345524332303a207472616e7366657220746f20746865207a65726f2061646472657373416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f206772616e7445524332303a206275726e20616d6f756e7420657863656564732062616c616e636545524332305072657365744d696e7465725061757365723a206d75737420686176652070617573657220726f6c6520746f20756e706175736545524332303a20617070726f766520746f20746865207a65726f20616464726573734552433230203a2072656c656173652076616c7565206d6f7265207468656e206c6f636b65642076616c756545524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332305072657365744d696e7465725061757365723a206d75737420686176652061646d696e20726f6c6520746f206275726e416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f207265766f6b654552433230203a20616d6f756e74206578636565647320617661696c61626c6520616d6f756e7445524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636565d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a45524332305072657365744d696e7465725061757365723a206d7573742068617665206d696e74657220726f6c6520746f206d696e749f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a64552433230203a206275726e206578636565647320617661696c61626c6520616d6f756e7445524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f20616464726573734552433230203a20617070726f766520616d6f756e74206578636565647320617661696c61626c6520616d6f756e7445524332305072657365744d696e7465725061757365723a206d75737420686176652070617573657220726f6c6520746f20706175736545524332305072657365744d696e7465725061757365723a206d75737420686176652061646d696e20726f6c6520746f206c6f636b45524332303a206c6f636b2076616c7565206d6f72652074686120617661696c61626c6520616d6f756e7445524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726f45524332305072657365744d696e7465725061757365723a206d75737420686176652061646d696e20726f6c65416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636520726f6c657320666f722073656c6645524332305061757361626c653a20746f6b656e207472616e73666572207768696c652070617573656445524332305072657365744d696e7465725061757365723a206d75737420686176652061646d696e20726f6c6520746f2072656c65617365a264697066735822122043e50b954e8de778aad15e090b5e91d9521cb66a65083bff85dee41855e2e95164736f6c634300060c0033a2646970667358221220afe6a8e1de9f0d91556caea2efaaa439ea6c0279c27788be36976338a108a1f464736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-eth", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-eth', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
45
0x117d16a3d9ac6f63a9512460bbad93f3f55c5789
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 EY 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 EY( 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]; } }
0x6060604052600436106100af576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100b4578063095ea7b31461014257806318160ddd1461019c57806323b872dd146101c557806327e235e31461023e578063313ce5671461028b5780635c658165146102ba57806370a082311461032657806395d89b4114610373578063a9059cbb14610401578063dd62ed3e1461045b575b600080fd5b34156100bf57600080fd5b6100c76104c7565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101075780820151818401526020810190506100ec565b50505050905090810190601f1680156101345780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561014d57600080fd5b610182600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610565565b604051808215151515815260200191505060405180910390f35b34156101a757600080fd5b6101af610657565b6040518082815260200191505060405180910390f35b34156101d057600080fd5b610224600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061065d565b604051808215151515815260200191505060405180910390f35b341561024957600080fd5b610275600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108f7565b6040518082815260200191505060405180910390f35b341561029657600080fd5b61029e61090f565b604051808260ff1660ff16815260200191505060405180910390f35b34156102c557600080fd5b610310600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610922565b6040518082815260200191505060405180910390f35b341561033157600080fd5b61035d600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610947565b6040518082815260200191505060405180910390f35b341561037e57600080fd5b610386610990565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156103c65780820151818401526020810190506103ab565b50505050905090810190601f1680156103f35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561040c57600080fd5b610441600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610a2e565b604051808215151515815260200191505060405180910390f35b341561046657600080fd5b6104b1600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610b87565b6040518082815260200191505060405180910390f35b60038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561055d5780601f106105325761010080835404028352916020019161055d565b820191906000526020600020905b81548152906001019060200180831161054057829003601f168201915b505050505081565b600081600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b60005481565b600080600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015801561072e5750828110155b151561073957600080fd5b82600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8110156108865782600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055505b8373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a360019150509392505050565b60016020528060005260406000206000915090505481565b600460009054906101000a900460ff1681565b6002602052816000526040600020602052806000526040600020600091509150505481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60058054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610a265780601f106109fb57610100808354040283529160200191610a26565b820191906000526020600020905b815481529060010190602001808311610a0957829003601f168201915b505050505081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410151515610a7e57600080fd5b81600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050929150505600a165627a7a72305820af7c6ecfaac0a06e9fb671ecb2c5ecbd16fc8262e671abade0bcc993112a917e0029
{"success": true, "error": null, "results": {}}
true
null
{}
46
0x11c26446b5ce3b895ef6a9a594cf9df6e8badbd7
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); } contract CurveStakingAdapter is ProtocolAdapter { string public constant override adapterType = "Asset"; string public constant override tokenType = "ERC20"; address internal constant C_CRV = 0x845838DF265Dcd2c412A1Dc9e959c7d08537f8a2; address internal constant Y_CRV = 0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8; address internal constant B_CRV = 0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B; address internal constant S_CRV = 0xC25a3A3b969415c80451098fa907EC722572917F; address internal constant P_CRV = 0xD905e2eaeBe188fc92179b6350807D8bd91Db0D8; address internal constant THREE_CRV = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; address internal constant RENBTC_CRV = 0x49849C98ae39Fff122806C06791Fa73784FB3675; address internal constant SBTC_CRV = 0x075b1bb99792c9E1041bA13afEf80C91a1e70fB3; address internal constant HBTC_CRV = 0xb19059ebb43466C323583928285a49f558E572Fd; address internal constant HUSD_CRV = 0x5B5CFE992AdAC0C9D48E05854B2d91C73a003858; address internal constant USDK_CRV = 0x97E2768e8E73511cA874545DC5Ff8067eB19B787; address internal constant USDN_CRV = 0x4f3E8F405CF5aFC05D68142F3783bDfE13811522; address internal constant C_GAUGE = 0x7ca5b0a2910B33e9759DC7dDB0413949071D7575; address internal constant Y_GAUGE = 0xFA712EE4788C042e2B7BB55E6cb8ec569C4530c1; address internal constant B_GAUGE = 0x69Fb7c45726cfE2baDeE8317005d3F94bE838840; address internal constant S_GAUGE = 0xA90996896660DEcC6E997655E065b23788857849; address internal constant P_GAUGE = 0x64E3C23bfc40722d3B649844055F1D51c1ac041d; address internal constant THREE_GAUGE = 0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A; address internal constant RENBTC_GAUGE = 0xB1F2cdeC61db658F091671F5f199635aEF202CAC; address internal constant SBTC_GAUGE = 0x705350c4BcD35c9441419DdD5d2f097d7a55410F; address internal constant HBTC_GAUGE = 0x4c18E409Dc8619bFb6a1cB56D114C3f592E0aE79; address internal constant HUSD_GAUGE = 0x2db0E83599a91b508Ac268a6197b8B14F5e72840; address internal constant USDK_GAUGE = 0xC2b1DF84112619D190193E48148000e3990Bf627; address internal constant USDN_GAUGE = 0xF98450B5602fa59CC66e1379DFfB6FDDc724CfC4; /** * @return Amount of staked LP tokens for a given account. * @dev Implementation of ProtocolAdapter interface function. */ function getBalance(address token, address account) external view override returns (uint256) { if (token == C_CRV) { return ERC20(C_GAUGE).balanceOf(account); } else if (token == Y_CRV) { return ERC20(Y_GAUGE).balanceOf(account); } else if (token == B_CRV) { return ERC20(B_GAUGE).balanceOf(account); } else if (token == S_CRV) { return ERC20(S_GAUGE).balanceOf(account); } else if (token == P_CRV) { return ERC20(P_GAUGE).balanceOf(account); } else if (token == THREE_CRV) { return ERC20(THREE_GAUGE).balanceOf(account); } else if (token == RENBTC_CRV) { return ERC20(RENBTC_GAUGE).balanceOf(account); } else if (token == SBTC_CRV) { return ERC20(SBTC_GAUGE).balanceOf(account); } else if (token == HBTC_CRV) { return ERC20(HBTC_GAUGE).balanceOf(account); } else if (token == HUSD_CRV) { return ERC20(HUSD_GAUGE).balanceOf(account); } else if (token == USDK_CRV) { return ERC20(USDK_GAUGE).balanceOf(account); } else if (token == USDN_CRV) { return ERC20(USDN_GAUGE).balanceOf(account); } else { return 0; } } }
0x608060405234801561001057600080fd5b50600436106100415760003560e01c806330fa738c14610046578063d4fac45d14610064578063f72c079114610084575b600080fd5b61004e61008c565b60405161005b919061080a565b60405180910390f35b61007761007236600461079d565b6100c5565b60405161005b919061087b565b61004e610740565b6040518060400160405280600581526020017f455243323000000000000000000000000000000000000000000000000000000081525081565b600073ffffffffffffffffffffffffffffffffffffffff831673845838df265dcd2c412a1dc9e959c7d08537f8a214156101a0576040517f70a08231000000000000000000000000000000000000000000000000000000008152737ca5b0a2910b33e9759dc7ddb0413949071d7575906370a08231906101499085906004016107e9565b60206040518083038186803b15801561016157600080fd5b505afa158015610175573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061019991906107d1565b905061073a565b73ffffffffffffffffffffffffffffffffffffffff831673df5e0e81dff6faf3a7e52ba697820c5e32d806a81415610222576040517f70a0823100000000000000000000000000000000000000000000000000000000815273fa712ee4788c042e2b7bb55e6cb8ec569c4530c1906370a08231906101499085906004016107e9565b73ffffffffffffffffffffffffffffffffffffffff8316733b3ac5386837dc563660fb6a0937dfaa5924333b14156102a4576040517f70a082310000000000000000000000000000000000000000000000000000000081527369fb7c45726cfe2badee8317005d3f94be838840906370a08231906101499085906004016107e9565b73ffffffffffffffffffffffffffffffffffffffff831673c25a3a3b969415c80451098fa907ec722572917f1415610326576040517f70a0823100000000000000000000000000000000000000000000000000000000815273a90996896660decc6e997655e065b23788857849906370a08231906101499085906004016107e9565b73ffffffffffffffffffffffffffffffffffffffff831673d905e2eaebe188fc92179b6350807d8bd91db0d814156103a8576040517f70a082310000000000000000000000000000000000000000000000000000000081527364e3c23bfc40722d3b649844055f1d51c1ac041d906370a08231906101499085906004016107e9565b73ffffffffffffffffffffffffffffffffffffffff8316736c3f90f043a72fa612cbac8115ee7e52bde6e490141561042a576040517f70a0823100000000000000000000000000000000000000000000000000000000815273bfcf63294ad7105dea65aa58f8ae5be2d9d0952a906370a08231906101499085906004016107e9565b73ffffffffffffffffffffffffffffffffffffffff83167349849c98ae39fff122806c06791fa73784fb367514156104ac576040517f70a0823100000000000000000000000000000000000000000000000000000000815273b1f2cdec61db658f091671f5f199635aef202cac906370a08231906101499085906004016107e9565b73ffffffffffffffffffffffffffffffffffffffff831673075b1bb99792c9e1041ba13afef80c91a1e70fb3141561052e576040517f70a0823100000000000000000000000000000000000000000000000000000000815273705350c4bcd35c9441419ddd5d2f097d7a55410f906370a08231906101499085906004016107e9565b73ffffffffffffffffffffffffffffffffffffffff831673b19059ebb43466c323583928285a49f558e572fd14156105b0576040517f70a08231000000000000000000000000000000000000000000000000000000008152734c18e409dc8619bfb6a1cb56d114c3f592e0ae79906370a08231906101499085906004016107e9565b73ffffffffffffffffffffffffffffffffffffffff8316735b5cfe992adac0c9d48e05854b2d91c73a0038581415610632576040517f70a08231000000000000000000000000000000000000000000000000000000008152732db0e83599a91b508ac268a6197b8b14f5e72840906370a08231906101499085906004016107e9565b73ffffffffffffffffffffffffffffffffffffffff83167397e2768e8e73511ca874545dc5ff8067eb19b78714156106b4576040517f70a0823100000000000000000000000000000000000000000000000000000000815273c2b1df84112619d190193e48148000e3990bf627906370a08231906101499085906004016107e9565b73ffffffffffffffffffffffffffffffffffffffff8316734f3e8f405cf5afc05d68142f3783bdfe138115221415610736576040517f70a0823100000000000000000000000000000000000000000000000000000000815273f98450b5602fa59cc66e1379dffb6fddc724cfc4906370a08231906101499085906004016107e9565b5060005b92915050565b6040518060400160405280600581526020017f417373657400000000000000000000000000000000000000000000000000000081525081565b803573ffffffffffffffffffffffffffffffffffffffff8116811461073a57600080fd5b600080604083850312156107af578182fd5b6107b98484610779565b91506107c88460208501610779565b90509250929050565b6000602082840312156107e2578081fd5b5051919050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b6000602080835283518082850152825b818110156108365785810183015185820160400152820161081a565b818111156108475783604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b9081526020019056fea2646970667358221220278dfe042ab6fa15ad253aa1f6551c20843084e5a1d076fcafbefa467120185064736f6c63430006050033
{"success": true, "error": null, "results": {}}
true
null
{}
47
0x11c7262CB638D51E596363243C82066F49110Ed9
pragma solidity 0.5.16; pragma experimental ABIEncoderV2; 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); } } 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); } contract WanttrollerErrorReporter { enum Error { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, UNAUTHORIZED } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK, SET_IMPLEMENTATION_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_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 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)}); } } 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 WantFaucet is Exponential { using SafeMath for uint256; // Min time between drips uint dripInterval = 200; address admin; address teamWallet; address wantAddress; uint constant teamFactor = 0.01e18; constructor(address _admin, address _teamWallet, address _wantAddress) public { admin = _admin; teamWallet = _teamWallet; wantAddress = _wantAddress; } function setAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } function drip(uint amount) public { EIP20Interface want = EIP20Interface(wantAddress); require(msg.sender == admin, "drip(): Only admin may call this function"); // Compute team amount: 1% (MathError err, Exp memory teamAmount) = mulExp(Exp({ mantissa: amount }), Exp({ mantissa: teamFactor })); require(err == MathError.NO_ERROR); // Check balance requested for withdrawal require(amount.add(teamAmount.mantissa) < want.balanceOf(address(this)), "Insufficent balance for drip"); // Transfer team amount bool success = want.transfer(teamWallet, teamAmount.mantissa); require(success, "collectRewards(): Unable to send team tokens"); // Transfer admin amount success = want.transfer(admin, amount); require(success, "collectRewards(): Unable to send admin tokens"); } } 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 wanttrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingWanttrollerImplementation; } contract WanttrollerV1Storage is UnitrollerAdminStorage, Exponential { struct WantDrop { /// @notice Total accounts requesting piece of drop uint numRegistrants; /// @notice Total amount to be dropped uint totalDrop; } // @notice Total amount dropped uint public totalDropped; // @notice Min time between drops uint public waitblocks = 200; // @notice Tracks beginning of this drop uint public currentDropStartBlock; // @notice Tracks the index of the current drop uint public currentDropIndex; /// @notice Store total registered and total reward for that drop mapping(uint => WantDrop) public wantDropState; /// @notice Any WANT rewards accrued but not yet collected mapping(address => uint) public accruedRewards; /// @notice Track the last drop this account was part of mapping(address => uint) public lastDropRegistered; address wantTokenAddress; address[] public accountsRegisteredForDrop; /// @notice Stores the current amount of drop being awarded uint public currentReward; /// @notice Each time rewards are distributed next rewards reduced by applying this factor uint public discountFactor = 0.9995e18; // Store faucet address address public wantFaucetAddress; } contract Unitroller is UnitrollerAdminStorage, WanttrollerErrorReporter { /** * @notice Emitted when pendingWanttrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingWanttrollerImplementation is accepted, which means wanttroller 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 = pendingWanttrollerImplementation; pendingWanttrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingWanttrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Accepts new implementation of wanttroller. 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 != pendingWanttrollerImplementation || pendingWanttrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = wanttrollerImplementation; address oldPendingImplementation = pendingWanttrollerImplementation; wanttrollerImplementation = pendingWanttrollerImplementation; pendingWanttrollerImplementation = address(0); emit NewImplementation(oldImplementation, wanttrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingWanttrollerImplementation); return uint(Error.NO_ERROR); } function _transferOwnership(address newAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } emit NewAdmin(admin, newAdmin); admin = newAdmin; 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, ) = wanttrollerImplementation.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 Wanttroller is WanttrollerV1Storage, WanttrollerErrorReporter { using SafeMath for uint256; uint constant initialReward = 50e18; event WantDropIndex(address account, uint index); event CollectRewards(address owner, uint rewardsAmount); event AccrueRewards(address owner, uint rewardsAmount); constructor() public { admin = msg.sender; } //-------------------- // Main actions // ------------------- /** * @notice Redeem rewards earned in wallet and register for next drop */ function collectRewards() public { // Register for next drop, accrue last reward if applicable registerForDrop(); if (_needsDrip()){ _dripFaucet(); } // send accrued reward to sender EIP20Interface want = EIP20Interface(wantTokenAddress); bool success = want.transfer(msg.sender, accruedRewards[msg.sender]); require(success, "collectRewards(): Unable to send tokens"); // emit emit CollectRewards(msg.sender, accruedRewards[msg.sender]); // Reset accrued to zero accruedRewards[msg.sender] = 0; } /** * @notice Register to receive reward in next WantDrop, accrues any rewards from the last drop */ function registerForDrop() public { // If previous drop has finished, start a new drop if (isDropOver()) { _startNewDrop(); } // Add rewards to balance _accrueRewards(); // Update want index if (lastDropRegistered[msg.sender] != currentDropIndex) { // Store index for account lastDropRegistered[msg.sender] = currentDropIndex; // Bump total registered count for this drop uint _numRegistrants = wantDropState[currentDropIndex].numRegistrants; wantDropState[currentDropIndex].numRegistrants = _numRegistrants.add(1); // Add to array of those on drop accountsRegisteredForDrop.push(msg.sender); // Emit event emit WantDropIndex(msg.sender, currentDropIndex); } // Track sender registered for current drop lastDropRegistered[msg.sender] = currentDropIndex; } /** * @notice Register to receive reward in next WantDrop, accrues any rewards from the last drop, * sends all rewards to wallet */ function registerAndCollect() public { registerForDrop(); collectRewards(); } //--------------------- // Statuses & getters //--------------------- /** * @notice Gets most current drop index. If current drop has finished, returns next drop index */ function getCurrentDropIndex() public view returns(uint) { if (isDropOver()) return currentDropIndex.add(1); else return currentDropIndex; } /** * @notice True if registered for most current drop */ function registeredForNextDrop() public view returns(bool) { if (isDropOver()) return false; else if (lastDropRegistered[msg.sender] == currentDropIndex) return true; else return false; } /** * @notice Blocks remaining to register for stake drop */ function blocksRemainingToRegister() public view returns(uint) { if (isDropOver() || currentDropIndex == 0){ return waitblocks; } else { return currentDropStartBlock.add(waitblocks).sub(block.number); } } /** * @notice True if waitblocks have passed since drop registration started */ function isDropOver() public view returns(bool) { // If current block is beyond start + waitblocks, drop registration over if (block.number >= currentDropStartBlock.add(waitblocks)) return true; else return false; } function getTotalCurrentDropReward() public view returns(uint) { if (isDropOver()) { return _nextReward(currentReward); } else { return currentReward; } } /** * @notice returns expected drop based on how many registered */ function getExpectedReward() public view returns(uint) { if (isDropOver()) { return _nextReward(currentReward); } // total reward / num registrants (MathError err, Exp memory result) = divScalar(Exp({mantissa: wantDropState[currentDropIndex].totalDrop}), wantDropState[currentDropIndex].numRegistrants ); require(err == MathError.NO_ERROR); return result.mantissa; } /** * @notice Gets the sender's total accrued rewards */ function getRewards() public view returns(uint) { uint pendingRewards = _pendingRewards(); if (pendingRewards > 0) { return accruedRewards[msg.sender].add(pendingRewards); } else { return accruedRewards[msg.sender]; } } /** * @notice Return stakers list for */ function getAccountsRegisteredForDrop() public view returns(address[] memory) { if (isDropOver()){ address[] memory blank; return blank; } else return accountsRegisteredForDrop; } // -------------------------------- // Reward computation and helpers // -------------------------------- /** * @notice Used to compute any pending reward not yet accrued onto a users accruedRewards */ function _pendingRewards() internal view returns(uint) { // Last drop user wanted uint _lastDropRegistered = lastDropRegistered[msg.sender]; // If new account, no rewards if (_lastDropRegistered == 0) return 0; // If drop requested has completed, accrue rewards if (_lastDropRegistered < currentDropIndex) { // Accrued = accrued + reward for last drop return _computeRewardMantissa(_lastDropRegistered); } else if (isDropOver()) { // Accrued = accrued + reward for last drop return _computeRewardMantissa(_lastDropRegistered); } else { return 0; } } /** * @notice Used to add rewards from last drop user was in to their accuedRewards balances */ function _accrueRewards() internal { uint pendingRewards = _pendingRewards(); if (pendingRewards > 0) { accruedRewards[msg.sender] = accruedRewards[msg.sender].add(pendingRewards); emit AccrueRewards(msg.sender, pendingRewards); } } /** * @notice Compute how much reward each participant in the drop received */ function _computeRewardMantissa(uint index) internal view returns(uint) { WantDrop memory wantDrop = wantDropState[index]; // Total Reward / Total participants (MathError err, Exp memory reward) = divScalar(Exp({ mantissa: wantDrop.totalDrop }), wantDrop.numRegistrants); require(err == MathError.NO_ERROR, "ComputeReward() Division error"); return reward.mantissa; } //------------------------------ // Drop management //------------------------------ /** * @notice Sets up state for new drop state and drips from faucet if rewards getting low */ function _startNewDrop() internal { // Bump drop index currentDropIndex = currentDropIndex.add(1); // Update current drop start to now currentDropStartBlock = block.number; // Compute next drop reward uint nextReward = _nextReward(currentReward); // Update global for total dropped totalDropped = totalDropped.add(nextReward); // Init next drop state wantDropState[currentDropIndex] = WantDrop({ totalDrop: nextReward, numRegistrants: 0 }); // Clear registrants delete accountsRegisteredForDrop; // Update currentReward currentReward = nextReward; } /** * @notice Compute next drop reward, based on current reward * @param _currentReward the current block reward for reference */ function _nextReward(uint _currentReward) private view returns(uint) { if (currentDropIndex == 1) { return initialReward; } else { (MathError err, Exp memory newRewardExp) = mulExp(Exp({mantissa: discountFactor }), Exp({mantissa: _currentReward })); require(err == MathError.NO_ERROR); return newRewardExp.mantissa; } } //------------------------------ // Receiving from faucet //------------------------------ /** * @notice checks if balance is too low and needs to visit the WANT faucet */ function _needsDrip() internal view returns(bool) { EIP20Interface want = EIP20Interface(wantTokenAddress); uint curBalance = want.balanceOf(address(this)); if (curBalance < currentReward || curBalance < accruedRewards[msg.sender]) { return true; } return false; } /** * @notice Receive WANT from the want. Attempts to get about 10x more than it needs to reduce need to call so frequently. */ function _dripFaucet() internal { EIP20Interface want = EIP20Interface(wantTokenAddress); uint faucetBlance = want.balanceOf(wantFaucetAddress); // Let's bulk drip for the next ~ 25 drops (MathError err, Exp memory toDrip) = mulScalar(Exp({ mantissa: currentReward }), 25); require(err == MathError.NO_ERROR); WantFaucet faucet = WantFaucet(wantFaucetAddress); if (toDrip.mantissa.add(faucetBlance) < accruedRewards[msg.sender]) { toDrip.mantissa = accruedRewards[msg.sender]; } // If the facuet is ~empty, empty it if (faucetBlance < toDrip.mantissa) { faucet.drip(faucetBlance); } else { faucet.drip(toDrip.mantissa); } } ///------------------------------------ // Admin functions: require governance // ------------------------------------ function _setWantFacuet(address newFacuetAddress) public { require(adminOrInitializing()); wantFaucetAddress = newFacuetAddress; } function _setWantAddress(address newWantAddress) public { require(adminOrInitializing()); wantTokenAddress = newWantAddress; } function _setDiscountFactor(uint256 newDiscountFactor) public { require(adminOrInitializing()); discountFactor = newDiscountFactor; } function _setWaitBlocks(uint256 newWaitBlocks) public { require(adminOrInitializing(), "not an admin"); waitblocks = newWaitBlocks; } function _setCurrentReward(uint256 _currentReward) public { require(adminOrInitializing(), "not an admin"); currentReward = _currentReward; } 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 == wanttrollerImplementation; } // Used for testing function tick() public { } }
0x608060405234801561001057600080fd5b50600436106101fb5760003560e01c80636fe124ba1161011a578063b28b1d27116100ad578063ccf28b841161007c578063ccf28b8414610390578063d144454b146103a3578063d57bef30146103ab578063d81635e9146103b3578063f851a440146103bb576101fb565b8063b28b1d271461034c578063b5c60c8414610354578063c0725b7114610367578063c80232e91461036f576101fb565b806380170088116100e9578063801700881461031457806387654c711461032757806398c722a01461032f578063a506434114610337576101fb565b80636fe124ba146102de57806370bb45b3146102f157806373b8dbca146102f957806375246f381461030c576101fb565b806333673f781161019257806350e643841161016157806350e64384146102b35780635250ac7a146102c657806353d5216b146102ce5780635e4a1e01146102d6576101fb565b806333673f78146102885780633d59e7fd146102905780633eaf5d9f1461029857806347b260fd146102a0576101fb565b8063204b262b116101ce578063204b262b1461024e57806326782247146102565780632aa1e57d1461026b5780632c08beeb14610273576101fb565b80630572b0cc1461020057806307621eca1461021e578063128fced1146102265780631d504dc614610239575b600080fd5b6102086103c3565b6040516102159190611756565b60405180910390f35b61020861041a565b6102086102343660046113b5565b610420565b61024c610247366004611417565b610432565b005b61024c61056f565b61025e61067d565b604051610215919061169d565b61020861068c565b61027b6106b6565b60405161021591906116d7565b6102086106f6565b610208610772565b61024c6107bc565b61024c6102ae3660046113b5565b6107be565b61024c6102c13660046113b5565b6107f1565b610208610824565b61025e610850565b61020861085f565b61024c6102ec366004611435565b610865565b61024c61087b565b6102086103073660046113b5565b6109a9565b6102086109bb565b61024c610322366004611435565b6109c1565b6102086109ea565b61025e6109f0565b61033f6109ff565b60405161021591906116c6565b61025e610a78565b61024c610362366004611435565b610a87565b61027b610ab0565b61038261037d366004611435565b610ad7565b604051610215929190611764565b61025e61039e366004611435565b610af0565b610208610b17565b610208610b1d565b61024c610b23565b61025e610b33565b6000806103ce610b42565b905080156103fe57336000908152600960205260409020546103f6908263ffffffff610b9416565b915050610417565b505033600090815260096020526040902054610417565b505b90565b600d5481565b60096020526000908152604090205481565b806001600160a01b031663f851a4406040518163ffffffff1660e01b815260040160206040518083038186803b15801561046b57600080fd5b505afa15801561047f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506104a391908101906113db565b6001600160a01b0316336001600160a01b0316146104dc5760405162461bcd60e51b81526004016104d390611746565b60405180910390fd5b806001600160a01b031663c1e803346040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561051757600080fd5b505af115801561052b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061054f9190810190611453565b1561056c5760405162461bcd60e51b81526004016104d390611726565b50565b610577610ab0565b1561058457610584610bc2565b61058c610c40565b600754336000908152600a60205260409020541461066857600754336000908152600a602090815260408083208490559282526008905220546105d681600163ffffffff610b9416565b6007805460009081526008602052604080822093909355600c805460018101825591527fdf6966c971051c3d54ec59162606531493a51404a002842f56009d7e5cf4a8c70180546001600160a01b03191633908117909155905491517feb1327dd128a806c3a56e14547c7c336539c79f4d03d1f1b4d29ce5b7968279a9261065e92916116ab565b60405180910390a1505b600754336000908152600a6020526040902055565b6001546001600160a01b031681565b6000610696610ab0565b156106ad576106a6600d54610cc1565b9050610417565b50600d54610417565b60006106c0610ab0565b156106cd57506000610417565b600754336000908152600a602052604090205414156106ee57506001610417565b506000610417565b6000610700610ab0565b15610710576106a6600d54610cc1565b600061071a61130e565b60408051602080820183526007546000818152600880845294812060018101548552919052929052905461074e9190610d3c565b9092509050600082600381111561076157fe5b1461076b57600080fd5b5191505090565b600061077c610ab0565b806107875750600754155b156107955750600554610417565b6106a6436107b0600554600654610b9490919063ffffffff16565b9063ffffffff610da616565b565b6107c6610de8565b6107cf57600080fd5b600f80546001600160a01b0319166001600160a01b0392909216919091179055565b6107f9610de8565b61080257600080fd5b600b80546001600160a01b0319166001600160a01b0392909216919091179055565b600061082e610ab0565b15610847576007546106a690600163ffffffff610b9416565b50600754610417565b6002546001600160a01b031681565b600e5481565b61086d610de8565b61087657600080fd5b600e55565b61088361056f565b61088b610e11565b1561089857610898610ecf565b600b543360008181526009602052604080822054905163a9059cbb60e01b81526001600160a01b03909416939192849263a9059cbb926108db92916004016116ab565b602060405180830381600087803b1580156108f557600080fd5b505af1158015610909573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061092d91908101906113f9565b90508061094c5760405162461bcd60e51b81526004016104d390611716565b33600081815260096020526040908190205490517f2a2d1456672a2b5013c6d74f8677f133bbf5f7d5bb6be09231f7814782b9a7179261098d9290916116ab565b60405180910390a1505033600090815260096020526040812055565b600a6020526000908152604090205481565b60055481565b6109c9610de8565b6109e55760405162461bcd60e51b81526004016104d390611706565b600d55565b60075481565b600f546001600160a01b031681565b6060610a09610ab0565b15610a1657506060610417565b600c805480602002602001604051908101604052809291908181526020018280548015610a6c57602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610a4e575b50505050509050610417565b6003546001600160a01b031681565b610a8f610de8565b610aab5760405162461bcd60e51b81526004016104d390611706565b600555565b6000610ac9600554600654610b9490919063ffffffff16565b43106106ee57506001610417565b6008602052600090815260409020805460019091015482565b600c8181548110610afd57fe5b6000918252602090912001546001600160a01b0316905081565b60045481565b60065481565b610b2b61056f565b6107bc61087b565b6000546001600160a01b031681565b336000908152600a602052604081205480610b61576000915050610417565b600754811015610b74576103f6816110b8565b610b7c610ab0565b15610b8a576103f6816110b8565b6000915050610417565b600082820183811015610bb95760405162461bcd60e51b81526004016104d3906116f6565b90505b92915050565b600754610bd690600163ffffffff610b9416565b60075543600655600d54600090610bec90610cc1565b600454909150610c02908263ffffffff610b9416565b60045560408051808201825260008082526020808301858152600754835260089091529281209151825591516001909101556109e590600c90611321565b6000610c4a610b42565b9050801561056c5733600090815260096020526040902054610c72908263ffffffff610b9416565b33600081815260096020526040908190209290925590517f17d99360aa166d2131bd8a029d02455fa48f24acda7813810fd7ef57e43005d891610cb69184906116ab565b60405180910390a150565b600060075460011415610cde57506802b5e3af16b1880000610d37565b6000610ce861130e565b610d106040518060200160405280600e5481525060405180602001604052808781525061114d565b90925090506000826003811115610d2357fe5b14610d2d57600080fd5b519150610d379050565b919050565b6000610d4661130e565b600080610d57866000015186611236565b90925090506000826003811115610d6a57fe5b14610d8957506040805160208101909152600081529092509050610d9f565b6040805160208101909152908152600093509150505b9250929050565b6000610bb983836040518060400160405280601f81526020017f536166654d6174683a207375627472616374696f6e20756e646572666c6f7700815250611261565b600080546001600160a01b0316331480610e0c57506002546001600160a01b031633145b905090565b600b546040516370a0823160e01b81526000916001600160a01b031690829082906370a0823190610e4690309060040161169d565b60206040518083038186803b158015610e5e57600080fd5b505afa158015610e72573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610e969190810190611453565b9050600d54811080610eb657503360009081526009602052604090205481105b15610ec657600192505050610417565b60009250505090565b600b54600f546040516370a0823160e01b81526001600160a01b039283169260009284926370a0823192610f0792169060040161169d565b60206040518083038186803b158015610f1f57600080fd5b505afa158015610f33573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610f579190810190611453565b90506000610f6361130e565b610f7e6040518060200160405280600d548152506019611292565b90925090506000826003811115610f9157fe5b14610f9b57600080fd5b600f543360009081526009602052604090205482516001600160a01b0390921691610fcc908663ffffffff610b9416565b1015610fe5573360009081526009602052604090205482525b815184101561105157604051632c1935bd60e11b81526001600160a01b038216906358326b7a9061101a908790600401611756565b600060405180830381600087803b15801561103457600080fd5b505af1158015611048573d6000803e3d6000fd5b505050506110b1565b8151604051632c1935bd60e11b81526001600160a01b038316916358326b7a9161107e9190600401611756565b600060405180830381600087803b15801561109857600080fd5b505af11580156110ac573d6000803e3d6000fd5b505050505b5050505050565b60006110c261133f565b5060008281526008602090815260408083208151808301909252805482526001015491810191909152906110f461130e565b611114604051806020016040528085602001518152508460000151610d3c565b9092509050600082600381111561112757fe5b146111445760405162461bcd60e51b81526004016104d390611736565b51949350505050565b600061115761130e565b60008061116c866000015186600001516112a9565b9092509050600082600381111561117f57fe5b1461119e57506040805160208101909152600081529092509050610d9f565b6000806111b36706f05b59d3b20000846112e8565b909250905060008260038111156111c657fe5b146111e857506040805160208101909152600081529094509250610d9f915050565b6000806111fd83670de0b6b3a7640000611236565b9092509050600082600381111561121057fe5b1461121757fe5b604080516020810190915290815260009a909950975050505050505050565b6000808261124a5750600190506000610d9f565b600083858161125557fe5b04915091509250929050565b600081848411156112855760405162461bcd60e51b81526004016104d391906116e5565b50508183035b9392505050565b600061129c61130e565b600080610d578660000151865b600080836112bc57506000905080610d9f565b838302838582816112c957fe5b04146112dd57506002915060009050610d9f565b600092509050610d9f565b60008083830184811061130057600092509050610d9f565b506002915060009050610d9f565b6040518060200160405280600081525090565b508054600082559060005260206000209081019061056c9190611359565b604051806040016040528060008152602001600081525090565b61041791905b80821115610415576000815560010161135f565b8035610bbc816117f1565b8051610bbc816117f1565b8051610bbc81611805565b8035610bbc8161180e565b8035610bbc81611817565b8051610bbc81611817565b6000602082840312156113c757600080fd5b60006113d38484611373565b949350505050565b6000602082840312156113ed57600080fd5b60006113d3848461137e565b60006020828403121561140b57600080fd5b60006113d38484611389565b60006020828403121561142957600080fd5b60006113d38484611394565b60006020828403121561144757600080fd5b60006113d3848461139f565b60006020828403121561146557600080fd5b60006113d384846113aa565b600061147d8383611494565b505060200190565b61148e816117ac565b82525050565b61148e81611785565b60006114a882611778565b6114b2818561177c565b93506114bd83611772565b8060005b838110156114eb5781516114d58882611471565b97506114e083611772565b9250506001016114c1565b509495945050505050565b61148e81611790565b600061150a82611778565b611514818561177c565b93506115248185602086016117b7565b61152d816117e7565b9093019392505050565b6000611544601b8361177c565b7f536166654d6174683a206164646974696f6e206f766572666c6f770000000000815260200192915050565b600061157d600c8361177c565b6b3737ba1030b71030b236b4b760a11b815260200192915050565b60006115a560278361177c565b7f636f6c6c6563745265776172647328293a20556e61626c6520746f2073656e6481526620746f6b656e7360c81b602082015260400192915050565b60006115ee60158361177c565b7418da185b99d9481b9bdd08185d5d1a1bdc9a5e9959605a1b815260200192915050565b600061161f601e8361177c565b7f436f6d707574655265776172642829204469766973696f6e206572726f720000815260200192915050565b600061165860278361177c565b7f6f6e6c7920756e6974726f6c6c65722061646d696e2063616e206368616e676581526620627261696e7360c81b602082015260400192915050565b61148e81610417565b60208101610bbc8284611494565b604081016116b98285611485565b61128b6020830184611694565b60208082528101610bb9818461149d565b60208101610bbc82846114f6565b60208082528101610bb981846114ff565b60208082528101610bbc81611537565b60208082528101610bbc81611570565b60208082528101610bbc81611598565b60208082528101610bbc816115e1565b60208082528101610bbc81611612565b60208082528101610bbc8161164b565b60208101610bbc8284611694565b604081016116b98285611694565b60200190565b5190565b90815260200190565b6000610bbc826117a0565b151590565b6000610bbc82611785565b6001600160a01b031690565b6000610bbc82611795565b60005b838110156117d25781810151838201526020016117ba565b838111156117e1576000848401525b50505050565b601f01601f191690565b6117fa81611785565b811461056c57600080fd5b6117fa81611790565b6117fa81611795565b6117fa8161041756fea365627a7a72315820ba74370b6e34e4fb281e88f1312ca0ce38bfaa4a8dac464a9687dcc097ac45746c6578706572696d656e74616cf564736f6c63430005100040
{"success": true, "error": null, "results": {"detectors": [{"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "uninitialized-state", "impact": "High", "confidence": "High"}, {"check": "controlled-delegatecall", "impact": "High", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'uninitialized-state', 'impact': 'High', 'confidence': 'High'}, {'check': 'controlled-delegatecall', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}]}
48
0x11c937fD367D75465DC211c367684d8d4520E6f9
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 = 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(); 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); } /// @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)"))); } } 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; } 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 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 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 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 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) * (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 = 0xCE4c11c339be0CddAf07eacF18d7e6884800F43E; 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(swapedTokens >= 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)); 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(DAI_JOIN_ADDRESS); 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 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 + _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 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); // 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); 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(); (,,,,,,,,,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); 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 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); } } }
0x
{"success": true, "error": null, "results": {"detectors": [{"check": "tx-origin", "impact": "Medium", "confidence": "Medium"}, {"check": "name-reused", "impact": "High", "confidence": "High"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-lowlevel", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'tx-origin', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'name-reused', 'impact': 'High', 'confidence': 'High'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-lowlevel', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
49
0x1232b1601419b8b9874683f680e793343f8cbda6
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 BFactory is BBronze { event LOG_NEW_POOL( address indexed caller, address indexed pool ); event LOG_BLABS( address indexed caller, address indexed blabs ); event LOG_RESERVES_ADDRESS( address indexed caller, address indexed reservesAddress ); event LOG_ALLOW_NON_ADMIN_POOL( address indexed caller, bool allow ); mapping(address=>bool) private _isBPool; function isBPool(address b) external view returns (bool) { return _isBPool[b]; } function newBPool() external returns (BPool) { if (!_allowNonAdminPool) { require(msg.sender == _blabs); } BPool bpool = new BPool(); _isBPool[address(bpool)] = true; emit LOG_NEW_POOL(msg.sender, address(bpool)); bpool.setController(msg.sender); return bpool; } address private _blabs; address private _reservesAddress; bool private _allowNonAdminPool; constructor() public { _blabs = msg.sender; _reservesAddress = msg.sender; _allowNonAdminPool = false; } function getAllowNonAdminPool() external view returns (bool) { return _allowNonAdminPool; } function setAllowNonAdminPool(bool b) external { require(msg.sender == _blabs, "ERR_NOT_BLABS"); emit LOG_ALLOW_NON_ADMIN_POOL(msg.sender, b); _allowNonAdminPool = b; } function getBLabs() external view returns (address) { return _blabs; } function setBLabs(address b) external { require(msg.sender == _blabs); emit LOG_BLABS(msg.sender, b); _blabs = b; } function getReservesAddress() external view returns (address) { return _reservesAddress; } function setReservesAddress(address a) external { require(msg.sender == _blabs); emit LOG_RESERVES_ADDRESS(msg.sender, a); _reservesAddress = a; } function collect(BPool pool) external { require(msg.sender == _blabs); uint collected = IERC20(pool).balanceOf(address(this)); bool xfer = pool.transfer(_blabs, collected); require(xfer); } function collectTokenReserves(BPool pool) external { require(msg.sender == _blabs); require(_isBPool[address(pool)]); pool.drainTotalReserves(_reservesAddress); } } 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 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); } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c8063c124b18411610071578063c124b18414610142578063c2bb6dc214610168578063c6ce34fb146101a2578063d556c5dc146101c8578063db90def3146101d0578063e5a23849146101ef576100a9565b806306ec16f8146100ae5780632ad415bd146100d657806336ffb167146100fa5780638318f24a146101025780639a86139b14610128575b600080fd5b6100d4600480360360208110156100c457600080fd5b50356001600160a01b03166101f7565b005b6100de61031c565b604080516001600160a01b039092168252519081900360200190f35b6100de61032b565b6100d46004803603602081101561011857600080fd5b50356001600160a01b031661033a565b6101306103a9565b60408051918252519081900360200190f35b6100d46004803603602081101561015857600080fd5b50356001600160a01b03166103b6565b61018e6004803603602081101561017e57600080fd5b50356001600160a01b031661045b565b604080519115158252519081900360200190f35b6100d4600480360360208110156101b857600080fd5b50356001600160a01b0316610479565b6100de6104e8565b6100d4600480360360208110156101e657600080fd5b503515156105f2565b61018e610697565b6001546001600160a01b0316331461020e57600080fd5b604080516370a0823160e01b815230600482015290516000916001600160a01b038416916370a0823191602480820192602092909190829003018186803b15801561025857600080fd5b505afa15801561026c573d6000803e3d6000fd5b505050506040513d602081101561028257600080fd5b50516001546040805163a9059cbb60e01b81526001600160a01b0392831660048201526024810184905290519293506000929185169163a9059cbb9160448082019260209290919082900301818787803b1580156102df57600080fd5b505af11580156102f3573d6000803e3d6000fd5b505050506040513d602081101561030957600080fd5b505190508061031757600080fd5b505050565b6002546001600160a01b031690565b6001546001600160a01b031690565b6001546001600160a01b0316331461035157600080fd5b6040516001600160a01b0382169033907fe33f2276fe6ea8141b3855e68646ebcf09ec2df8768afe2a7bf153c9b10c273b90600090a3600280546001600160a01b0319166001600160a01b0392909216919091179055565b6542524f4e5a4560d01b90565b6001546001600160a01b031633146103cd57600080fd5b6001600160a01b03811660009081526020819052604090205460ff166103f257600080fd5b6002546040805163577756b360e11b81526001600160a01b03928316600482015290519183169163aeeead669160248082019260009290919082900301818387803b15801561044057600080fd5b505af1158015610454573d6000803e3d6000fd5b5050505050565b6001600160a01b031660009081526020819052604090205460ff1690565b6001546001600160a01b0316331461049057600080fd5b6040516001600160a01b0382169033907ff586fa6ee1fc42f5b727f3b214ccbd0b6d7e698c45d49ba32f224fbb8670155d90600090a3600180546001600160a01b0319166001600160a01b0392909216919091179055565b600254600090600160a01b900460ff16610513576001546001600160a01b0316331461051357600080fd5b6000604051610521906106a7565b604051809103906000f08015801561053d573d6000803e3d6000fd5b506001600160a01b038116600081815260208190526040808220805460ff1916600117905551929350909133917f8ccec77b0cb63ac2cafd0f5de8cdfadab91ce656d262240ba8a6343bccc5f94591a3604080516392eefe9b60e01b815233600482015290516001600160a01b038316916392eefe9b91602480830192600092919082900301818387803b1580156105d457600080fd5b505af11580156105e8573d6000803e3d6000fd5b5092935050505090565b6001546001600160a01b03163314610641576040805162461bcd60e51b815260206004820152600d60248201526c4552525f4e4f545f424c41425360981b604482015290519081900360640190fd5b604080518215158152905133917f3f7cb0f9d9d6328953db4b2e4654f86a01cb45ec1e39aa6665763281ddca54a7919081900360200190a260028054911515600160a01b0260ff60a01b19909216919091179055565b600254600160a01b900460ff1690565b61428a806106b58339019056fe60c0604052601060808190527f437265616d20506f6f6c20546f6b656e0000000000000000000000000000000060a0908152620000409160039190620000fe565b506040805180820190915260048082527f43525054000000000000000000000000000000000000000000000000000000006020909201918252620000859181620000fe565b506005805460ff19166012179055348015620000a057600080fd5b50600680546005805462010000600160b01b031916336201000081029190911790915564e8d4a510006007556702c68af0bb1400006008556001600160a01b03199091161760ff60a01b191690556009805460ff19169055620001a3565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200014157805160ff191683800117855562000171565b8280016001018555821562000171579182015b828111156200017157825182559160200191906001019062000154565b506200017f92915062000183565b5090565b620001a091905b808211156200017f57600081556001016200018a565b90565b6140d780620001b36000396000f3fe608060405234801561001057600080fd5b50600436106103925760003560e01c806392eefe9b116101e0578063bc063e1a11610110578063d73dd623116100a8578063d73dd62314610c1a578063dd62ed3e14610c46578063e4a28a52146104f2578063e4e1e53814610c74578063ec09302114610ca6578063f1b8a9b714610cae578063f8b2cb4f14610cd4578063f8d6aed414610cfa578063fde924f714610d3557610392565b8063bc063e1a14610b6c578063bc694ea214610b74578063be3bbd2e14610b7c578063c36596a614610566578063c6580d1214610bd4578063cc77828d14610bdc578063cd2ed8fb14610be4578063cf5e7bd314610bec578063d4cadf6814610c1257610392565b8063a221ee4911610183578063a221ee4914610a00578063a9059cbb14610a35578063aeeead6614610a61578063b02f0b7314610a87578063b0e0d13614610afc578063b4a8e10114610b04578063b7b800a414610b21578063ba019dab14610b29578063ba9530a614610b3157610392565b806392eefe9b14610984578063936c3477146109aa5780639381cd2b146109b257806393c88d14146109ba578063948d8ce6146109c257806395d89b41146109e8578063992e2a92146109f05780639a86139b146109f857610392565b806346ab38f1116102c65780636d0800bc1161025e5780636d0800bc1461083f57806370a082311461086557806376c7a3c71461088b5780637c5e9ea4146108935780638201aa3f146108d3578063867378c514610913578063892980121461091b5780638c28cbe8146109565780638d4e40831461097c57610392565b806346ab38f11461069e57806349b59552146106d05780634bb278f3146106ef5780634d2fd81d146106f75780634f69c0d4146106ff5780635c1bbaf7146107745780635db34277146107af57806366188463146107e15780636d06dfa01461080d57610392565b8063189d00ca11610339578063189d00ca1461055e578063218b53821461056657806321abba011461056e57806323b872dd146105af5780632f37b624146105e55780633018205f1461060b578063313ce5671461062f57806334e199071461064d5780633fdddaa21461066c57610392565b8063024eb2e31461039757806302c96748146103f157806306fdde0314610435578063095ea7b3146104b257806309a3bbe4146104f25780631446a7ff146104fa57806315e84af91461052857806318160ddd14610556575b600080fd5b6103d8600480360360e08110156103ad57600080fd5b5080359060208101359060408101359060608101359060808101359060a08101359060c00135610d3d565b6040805192835260208301919091528051918290030190f35b6104236004803603606081101561040757600080fd5b506001600160a01b038135169060208101359060400135610e0c565b60408051918252519081900360200190f35b61043d61105c565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561047757818101518382015260200161045f565b50505050905090810190601f1680156104a45780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6104de600480360360408110156104c857600080fd5b506001600160a01b0381351690602001356110f2565b604080519115158252519081900360200190f35b610423611147565b6104236004803603604081101561051057600080fd5b506001600160a01b0381358116916020013516611154565b6104236004803603604081101561053e57600080fd5b506001600160a01b0381358116916020013516611203565b6104236112a9565b6104236112af565b6104236112c3565b6103d8600480360360e081101561058457600080fd5b5080359060208101359060408101359060608101359060808101359060a08101359060c001356112cf565b6104de600480360360608110156105c557600080fd5b506001600160a01b0381358116916020810135909116906040013561137c565b6104de600480360360208110156105fb57600080fd5b50356001600160a01b0316611496565b6106136114b4565b604080516001600160a01b039092168252519081900360200190f35b6106376114dc565b6040805160ff9092168252519081900360200190f35b61066a6004803603602081101561066357600080fd5b50356114e5565b005b61066a6004803603606081101561068257600080fd5b506001600160a01b0381351690602081013590604001356115c8565b610423600480360360608110156106b457600080fd5b506001600160a01b038135169060208101359060400135611804565b61066a600480360360208110156106e657600080fd5b50351515611a58565b61066a611b2d565b610423611c3d565b61066a6004803603604081101561071557600080fd5b81359190810190604081016020820135600160201b81111561073657600080fd5b82018360208201111561074857600080fd5b803590602001918460208302840111600160201b8311171561076957600080fd5b509092509050611c5c565b610423600480360360c081101561078a57600080fd5b5080359060208101359060408101359060608101359060808101359060a00135611e26565b610423600480360360608110156107c557600080fd5b506001600160a01b038135169060208101359060400135611ed9565b6104de600480360360408110156107f757600080fd5b506001600160a01b0381351690602001356120e0565b6104236004803603606081101561082357600080fd5b506001600160a01b0381351690602081013590604001356121b8565b6104236004803603602081101561085557600080fd5b50356001600160a01b03166123d0565b6104236004803603602081101561087b57600080fd5b50356001600160a01b03166123e2565b6104236123fd565b6103d8600480360360a08110156108a957600080fd5b506001600160a01b038135811691602081013591604082013516906060810135906080013561240f565b6103d8600480360360a08110156108e957600080fd5b506001600160a01b0381358116916020810135916040820135169060608101359060800135612704565b6104236129de565b610423600480360360c081101561093157600080fd5b5080359060208101359060408101359060608101359060808101359060a001356129f2565b61066a6004803603602081101561096c57600080fd5b50356001600160a01b0316612aa2565b6104de612be8565b61066a6004803603602081101561099a57600080fd5b50356001600160a01b0316612bf1565b610423612cbc565b610423612cdb565b610423612ce8565b610423600480360360208110156109d857600080fd5b50356001600160a01b0316612cf8565b61043d612d54565b610423612db5565b610423612dc1565b610423600480360360a0811015610a1657600080fd5b5080359060208101359060408101359060608101359060800135612dce565b6104de60048036036040811015610a4b57600080fd5b506001600160a01b038135169060200135612e33565b61066a60048036036020811015610a7757600080fd5b50356001600160a01b0316612e49565b61066a60048036036040811015610a9d57600080fd5b81359190810190604081016020820135600160201b811115610abe57600080fd5b820183602082011115610ad057600080fd5b803590602001918460208302840111600160201b83111715610af157600080fd5b509092509050612f8f565b6104236131a6565b61066a60048036036020811015610b1a57600080fd5b50356131ab565b61042361327c565b610423613281565b610423600480360360c0811015610b4757600080fd5b5080359060208101359060408101359060608101359060808101359060a00135613286565b610423613307565b610423613317565b610b84613323565b60408051602080825283518183015283519192839290830191858101910280838360005b83811015610bc0578181015183820152602001610ba8565b505050509050019250505060405180910390f35b6104236133a9565b610b846133ae565b6104236133c6565b61066a60048036036020811015610c0257600080fd5b50356001600160a01b03166133cc565b610423613668565b6104de60048036036040811015610c3057600080fd5b506001600160a01b038135169060200135613687565b61042360048036036040811015610c5c57600080fd5b506001600160a01b0381358116916020013516613708565b61066a60048036036060811015610c8a57600080fd5b506001600160a01b038135169060208101359060400135613733565b6104236138a2565b61042360048036036020811015610cc457600080fd5b50356001600160a01b03166138b2565b61042360048036036020811015610cea57600080fd5b50356001600160a01b0316613920565b610423600480360360c0811015610d1057600080fd5b5080359060208101359060408101359060608101359060808101359060a0013561397c565b6104de6139ff565b6000806000610d4c8988613a0f565b90506000610d6b610d65670de0b6b3a764000084613a75565b87613a9b565b90506000610d8a88610d85670de0b6b3a764000085613a75565b613a0f565b9050610d97818988613ae7565b93506000610da58d83613a75565b90506000610db3828f613a0f565b90506000610dc18287613b32565b90506000610dcf828f613a9b565b90506000610ddd8f83613a75565b9050610df681610d85670de0b6b3a76400006000613a75565b9950505050505050505097509795505050505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615610e8457600080fd5b6005805461ff00191661010017905560095460ff16610ea257600080fd5b6001600160a01b0384166000908152600b602052604090205460ff16610ec757600080fd5b6001600160a01b0384166000908152600b60205260409020600390810154610efc91670de0b6b3a76400005b04600101613a9b565b831115610f0857600080fd5b6000600b6000866001600160a01b03166001600160a01b0316815260200190815260200160002090506000610f5282600301548360020154600254600d5489600754600854610d3d565b909350905082610f6157600080fd5b83831115610f6e57600080fd5b610f85610f7f836003015487613a75565b82613a75565b60038301556000610f968482613a9b565b6040805188815290519192506001600160a01b038916913391600080516020614063833981519152919081900360200190a36001600160a01b0387166000908152600c6020526040902054610feb9083613bbf565b6001600160a01b0388166000908152600c602052604090205561100e3385613bd1565b61102061101b8583613a75565b613bdf565b60055461103c906201000090046001600160a01b031682613beb565b611047873388613bf5565b5050506005805461ff00191690559392505050565b60038054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156110e85780601f106110bd576101008083540402835291602001916110e8565b820191906000526020600020905b8154815290600101906020018083116110cb57829003601f168201915b5050505050905090565b3360008181526001602090815260408083206001600160a01b03871680855290835281842086905581518681529151939490939092600080516020614083833981519152928290030190a35060015b92915050565b6802b5e3af16b188000081565b600554600090610100900460ff161561116c57600080fd5b6001600160a01b0383166000908152600b602052604090205460ff1661119157600080fd5b6001600160a01b0382166000908152600b602052604090205460ff166111b657600080fd5b6001600160a01b038084166000908152600b602052604080822092851682528120600380840154600280860154928401549084015493946111fa9492939290612dce565b95945050505050565b600554600090610100900460ff161561121b57600080fd5b6001600160a01b0383166000908152600b602052604090205460ff1661124057600080fd5b6001600160a01b0382166000908152600b602052604090205460ff1661126557600080fd5b6001600160a01b038084166000908152600b60205260408082209285168252902060038083015460028085015492840154908401546007546111fa94929190612dce565b60025490565b6402540be400670de0b6b3a76400005b0481565b670de0b6b3a764000081565b60008060006112de8988613a0f565b905060006112f7610d65670de0b6b3a764000084613a75565b9050600061131688611311670de0b6b3a764000085613a75565b613a9b565b9050611323888288613ae7565b935060006113318d83613bbf565b9050600061133f828f613a0f565b9050600061134d8287613b32565b9050600061135b828f613a9b565b9050611367818f613a75565b98505050505050505097509795505050505050565b6000336001600160a01b03851614806113b857506001600160a01b03841660009081526001602090815260408083203384529091529020548211155b6113c157600080fd5b6113cc848484613c86565b336001600160a01b0385161480159061140a57506001600160a01b038416600090815260016020908152604080832033845290915290205460001914155b1561148c576001600160a01b038416600090815260016020908152604080832033845290915290205461143d9083613a75565b6001600160a01b03858116600090815260016020908152604080832033808552908352928190208590558051948552519287169391926000805160206140838339815191529281900390910190a35b5060019392505050565b6001600160a01b03166000908152600b602052604090205460ff1690565b600554600090610100900460ff16156114cc57600080fd5b506006546001600160a01b031690565b60055460ff1690565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561155b57600080fd5b6005805461ff00191661010017905560095460ff161561157a57600080fd5b6006546001600160a01b0316331461159157600080fd5b64e8d4a510008110156115a357600080fd5b67016345785d8a00008111156115b857600080fd5b6007556005805461ff0019169055565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561163e57600080fd5b6005805461ff001916610100179055600654336001600160a01b039091161461166657600080fd5b6001600160a01b0383166000908152600b602052604090205460ff1661168b57600080fd5b60095460ff161561169b57600080fd5b670de0b6b3a76400008110156116b057600080fd5b6802b5e3af16b18800008111156116c657600080fd5b620f42408210156116d657600080fd5b6001600160a01b0383166000908152600b60205260409020600201548082111561172e5761170f600d5461170a8484613a75565b613bbf565b600d8190556802b5e3af16b1880000101561172957600080fd5b61174f565b8082101561174f5761174b600d546117468385613a75565b613a75565b600d555b6001600160a01b0384166000908152600b60205260409020600281018390556003018054908490558084111561179857611793853361178e8785613a75565b613d45565b6117f2565b808410156117f25760006117ac8286613a75565b905060006117bb826000613a9b565b90506117d187336117cc8585613a75565b613bf5565b6005546117ef9088906201000090046001600160a01b031683613bf5565b50505b50506005805461ff0019169055505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561187c57600080fd5b6005805461ff00191661010017905560095460ff1661189a57600080fd5b6001600160a01b0384166000908152600b602052604090205460ff166118bf57600080fd5b6001600160a01b0384166000908152600b6020526040902060038101546002808301549054600d546007546118f9949392919089906129f2565b91508282101561190857600080fd5b6001600160a01b0385166000908152600b6020526040902060039081015461193891670de0b6b3a7640000610ef3565b82111561194457600080fd5b600061196182600301548360020154600254600d548960006129f2565b905060006119728285600854613ae7565b9050611985610f7f846003015486613a75565b600384015560006119968782613a9b565b6040805187815290519192506001600160a01b038a16913391600080516020614063833981519152919081900360200190a36001600160a01b0388166000908152600c60205260409020546119eb9083613bbf565b6001600160a01b0389166000908152600c6020526040902055611a0e3388613bd1565b611a1b61101b8883613a75565b600554611a37906201000090046001600160a01b031682613beb565b611a42883387613bf5565b505050506005805461ff00191690559392505050565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615611ace57600080fd5b6005805461ff00191661010017905560095460ff1615611aed57600080fd5b6006546001600160a01b03163314611b0457600080fd5b60068054911515600160a01b0260ff60a01b199092169190911790556005805461ff0019169055565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615611ba357600080fd5b6005805461ff001916610100179055600654336001600160a01b0390911614611bcb57600080fd5b60095460ff1615611bdb57600080fd5b600a5460021115611beb57600080fd5b6009805460ff191660011790556006805460ff60a01b1916600160a01b179055611c1d68056bc75e2d63100000613d9e565b611c303368056bc75e2d63100000613beb565b6005805461ff0019169055565b600554600090610100900460ff1615611c5557600080fd5b5060085490565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615611cd257600080fd5b6005805461ff00191661010017905560095460ff16611cf057600080fd5b6000611cfa6112a9565b90506000611d088583613a0f565b905080611d1457600080fd5b60005b600a54811015611e12576000600a8281548110611d3057fe5b60009182526020808320909101546001600160a01b0316808352600b909152604082206003015490925090611d658583613a9b565b905080611d7157600080fd5b878785818110611d7d57fe5b90506020020135811115611d9057600080fd5b6001600160a01b0383166000908152600b6020526040902060030154611db69082613bbf565b6001600160a01b0384166000818152600b60209081526040918290206003019390935580518481529051919233926000805160206140238339815191529281900390910190a3611e07833383613d45565b505050600101611d17565b50611e1c85613d9e565b6117f23386613beb565b600080611e338786613a0f565b90506000611e418786613bbf565b90506000611e4f8289613a0f565b90506000611e65670de0b6b3a764000085613a0f565b90506000611e738383613b32565b90506000611e81828e613a9b565b90506000611e8f828f613a75565b90506000611eae611ea8670de0b6b3a76400008a613a75565b8b613a9b565b9050611ec682610d85670de0b6b3a764000084613a75565b9f9e505050505050505050505050505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615611f5157600080fd5b6005805461ff00191661010017905560095460ff16611f6f57600080fd5b6001600160a01b0384166000908152600b602052604090205460ff16611f9457600080fd5b6001600160a01b0384166000908152600b6020526040902060030154611fc6906002670de0b6b3a76400005b04613a9b565b831115611fd257600080fd5b6000600b6000866001600160a01b03166001600160a01b031681526020019081526020016000209050600061201c82600301548360020154600254600d54896007546008546112cf565b90935090508383101561202e57600080fd5b61203f610f7f836003015487613bbf565b60038301556040805186815290516001600160a01b0388169133916000805160206140238339815191529181900360200190a36001600160a01b0386166000908152600c60205260409020546120959082613bbf565b6001600160a01b0387166000908152600c60205260409020556120b783613d9e565b6120c13384613beb565b6120cc863387613d45565b50506005805461ff00191690559392505050565b3360009081526001602090815260408083206001600160a01b038616845290915281205480831115612135573360009081526001602090815260408083206001600160a01b0388168452909152812055612164565b61213f8184613a75565b3360009081526001602090815260408083206001600160a01b03891684529091529020555b3360008181526001602090815260408083206001600160a01b038916808552908352928190205481519081529051929392600080516020614083833981519152929181900390910190a35060019392505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561223057600080fd5b6005805461ff00191661010017905560095460ff1661224e57600080fd5b6001600160a01b0384166000908152600b602052604090205460ff1661227357600080fd5b6001600160a01b0384166000908152600b6020526040902060038101546002808301549054600d546007546122ad94939291908990611e26565b9150816122b957600080fd5b828211156122c657600080fd5b6001600160a01b0385166000908152600b60205260409020600301546122f6906002670de0b6b3a7640000611fc0565b82111561230257600080fd5b600061231f82600301548360020154600254600d54896000611e26565b905060006123308483600854613ae7565b9050612343610f7f846003015486613bbf565b60038401556040805185815290516001600160a01b0389169133916000805160206140238339815191529181900360200190a36001600160a01b0387166000908152600c60205260409020546123999082613bbf565b6001600160a01b0388166000908152600c60205260409020556123bb86613d9e565b6123c53387613beb565b611047873386613d45565b600c6020526000908152604090205481565b6001600160a01b031660009081526020819052604090205490565b620f4240670de0b6b3a76400006112bf565b60408051602080825236908201819052600092839233926001600160e01b03198535169285929081908101848480828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561247657600080fd5b6005805461ff0019166101001790556001600160a01b0387166000908152600b602052604090205460ff166124aa57600080fd5b6001600160a01b0385166000908152600b602052604090205460ff166124cf57600080fd5b600654600160a01b900460ff166124e557600080fd5b6001600160a01b038088166000908152600b60205260408082209288168252902060038082015461251e91670de0b6b3a7640000610ef3565b86111561252a57600080fd5b600061254b8360030154846002015484600301548560020154600754612dce565b90508581111561255a57600080fd5b61257a83600301548460020154846003015485600201548b60075461397c565b94508885111561258957600080fd5b60006125aa84600301548560020154856003015486600201548c600061397c565b905060006125bb8783600854613ae7565b90506125ce610f7f866003015489613bbf565b85600301819055506125e484600301548a613a75565b600380860182905586015460028088015490870154600754612607949190612dce565b95508286101561261657600080fd5b8786111561262357600080fd5b61262d878a613a0f565b83111561263957600080fd5b896001600160a01b03168c6001600160a01b0316336001600160a01b03167f908fb5ee8f16c6bc9bc3690973819f32a4d4b10188134543c88706e0e1d433788a8d604051808381526020018281526020019250505060405180910390a46001600160a01b038c166000908152600c60205260409020546126b99082613bbf565b6001600160a01b038d166000908152600c60205260409020556126dd8c3389613d45565b6126e88a338b613bf5565b50505050506005805461ff001916905590969095509350505050565b60408051602080825236908201819052600092839233926001600160e01b03198535169285929081908101848480828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561276b57600080fd5b6005805461ff0019166101001790556001600160a01b0387166000908152600b602052604090205460ff1661279f57600080fd5b6001600160a01b0385166000908152600b602052604090205460ff166127c457600080fd5b600654600160a01b900460ff166127da57600080fd5b6001600160a01b038088166000908152600b6020526040808220928816825290206003820154612814906002670de0b6b3a7640000611fc0565b88111561282057600080fd5b60006128418360030154846002015484600301548560020154600754612dce565b90508581111561285057600080fd5b61287083600301548460020154846003015485600201548d600754613286565b94508685101561287f57600080fd5b60006128a084600301548560020154856003015486600201548e6000613286565b905060006128b18288600854613ae7565b90506128c185600301548c613bbf565b85600301819055506128da610f7f856003015489613a75565b6003808601829055860154600280880154908701546007546128fd949190612dce565b95508286101561290c57600080fd5b8786111561291957600080fd5b6129238b88613a0f565b83111561292f57600080fd5b896001600160a01b03168c6001600160a01b0316336001600160a01b03167f908fb5ee8f16c6bc9bc3690973819f32a4d4b10188134543c88706e0e1d433788e8b604051808381526020018281526020019250505060405180910390a46001600160a01b038a166000908152600c60205260409020546129af9082613bbf565b6001600160a01b038b166000908152600c60205260409020556129d38c338d613d45565b6126e88a3389613bf5565b64e8d4a51000670de0b6b3a76400006112bf565b6000806129ff8786613a0f565b90506000612a1a85611311670de0b6b3a76400006000613a75565b90506000612a288883613a75565b90506000612a36828a613a0f565b90506000612a5582612a50670de0b6b3a764000088613a0f565b613b32565b90506000612a63828e613a9b565b90506000612a718e83613a75565b90506000612a8a611ea8670de0b6b3a76400008a613a75565b9050611ec682611311670de0b6b3a764000084613a75565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615612b1857600080fd5b6005805461ff0019166101001790556001600160a01b0381166000908152600b602052604090205460ff16612b4c57600080fd5b604080516370a0823160e01b815230600482015290516001600160a01b038316916370a08231916024808301926020929190829003018186803b158015612b9257600080fd5b505afa158015612ba6573d6000803e3d6000fd5b505050506040513d6020811015612bbc57600080fd5b50516001600160a01b039091166000908152600b60205260409020600301556005805461ff0019169055565b60095460ff1690565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615612c6757600080fd5b6005805461ff001916610100179055600654336001600160a01b0390911614612c8f57600080fd5b600680546001600160a01b0319166001600160a01b03929092169190911790556005805461ff0019169055565b600554600090610100900460ff1615612cd457600080fd5b50600d5490565b68056bc75e2d6310000081565b6005670de0b6b3a76400006112bf565b600554600090610100900460ff1615612d1057600080fd5b6001600160a01b0382166000908152600b602052604090205460ff16612d3557600080fd5b506001600160a01b03166000908152600b602052604090206002015490565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156110e85780601f106110bd576101008083540402835291602001916110e8565b6704a03ce68d21555681565b6542524f4e5a4560d01b90565b600080612ddb8787613a0f565b90506000612de98686613a0f565b90506000612df78383613a0f565b90506000612e19670de0b6b3a7640000610d85670de0b6b3a764000089613a75565b9050612e258282613a9b565b9a9950505050505050505050565b6000612e40338484613c86565b50600192915050565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615612ebf57600080fd5b6005805461010061ff001990911617908190556201000090046001600160a01b03163314612eec57600080fd5b60005b600a54811015612f80576000600a8281548110612f0857fe5b60009182526020808320909101546001600160a01b03908116808452600c835260408085208054959055805185815290519195508593928816927f261074971f6b45f02124a88c43d5c95e174626f867c87684fb60dbbe35ec2cd292918290030190a3612f76828583613bf5565b5050600101612eef565b50506005805461ff0019169055565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561300557600080fd5b6005805461ff00191661010017905560095460ff1661302357600080fd5b600061302d6112a9565b9050600061303c856000613a9b565b9050600061304a8683613a75565b905060006130588285613a0f565b90508061306457600080fd5b61306e3388613bd1565b60055461308a906201000090046001600160a01b031684613beb565b61309382613bdf565b60005b600a54811015613191576000600a82815481106130af57fe5b60009182526020808320909101546001600160a01b0316808352600b9091526040822060030154909250906130e48583613a9b565b9050806130f057600080fd5b8989858181106130fc57fe5b9050602002013581101561310f57600080fd5b6001600160a01b0383166000908152600b60205260409020600301546131359082613a75565b6001600160a01b0384166000818152600b60209081526040918290206003019390935580518481529051919233926000805160206140638339815191529281900390910190a3613186833383613bf5565b505050600101613096565b50506005805461ff0019169055505050505050565b600881565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561322157600080fd5b6005805461ff00191661010017905560095460ff161561324057600080fd5b6006546001600160a01b0316331461325757600080fd5b670de0b6b3a764000081111561326c57600080fd5b6008556005805461ff0019169055565b600281565b600181565b6000806132938786613a0f565b905060006132a9670de0b6b3a764000085613a75565b90506132b58582613a9b565b905060006132c78a610d858c85613bbf565b905060006132d58285613b32565b905060006132eb670de0b6b3a764000083613a75565b90506132f78a82613a9b565b9c9b505050505050505050505050565b600a670de0b6b3a76400006112bf565b671bc16d674ec7ffff81565b600554606090610100900460ff161561333b57600080fd5b60095460ff1661334a57600080fd5b600a8054806020026020016040519081016040528092919081815260200182805480156110e857602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311613382575050505050905090565b600081565b600554606090610100900460ff161561334a57600080fd5b600a5490565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561344257600080fd5b6005805461ff001916610100179055600654336001600160a01b039091161461346a57600080fd5b6001600160a01b0381166000908152600b602052604090205460ff1661348f57600080fd5b60095460ff161561349f57600080fd5b6001600160a01b0381166000908152600b6020526040812060030154906134c68282613a9b565b600d546001600160a01b0385166000908152600b60205260409020600201549192506134f191613a75565b600d556001600160a01b0383166000908152600b6020526040902060010154600a8054600019810191908290811061352557fe5b600091825260209091200154600a80546001600160a01b03909216918490811061354b57fe5b9060005260206000200160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555081600b6000600a858154811061358b57fe5b60009182526020808320909101546001600160a01b03168352820192909252604001902060010155600a8054806135be57fe5b60008281526020808220600019908401810180546001600160a01b031916905590920190925560408051608081018252838152808301848152818301858152606083018681526001600160a01b038c168752600b909552929094209051815460ff1916901515178155925160018401555160028301555160039091015561364a85336117cc8787613a75565b6005546117f29086906201000090046001600160a01b031685613bf5565b600554600090610100900460ff161561368057600080fd5b5060075490565b3360009081526001602090815260408083206001600160a01b03861684529091528120546136b59083613bbf565b3360008181526001602090815260408083206001600160a01b038916808552908352928190208590558051948552519193600080516020614083833981519152929081900390910190a350600192915050565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a26006546001600160a01b031633146137ab57600080fd5b6001600160a01b0383166000908152600b602052604090205460ff16156137d157600080fd5b60095460ff16156137e157600080fd5b600a546008116137f057600080fd5b604080516080810182526001808252600a805460208085019182526000858701818152606087018281526001600160a01b038c16808452600b9094529782209651875460ff1916901515178755925186860155915160028601559451600390940193909355805491820181559091527fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a80180546001600160a01b031916909117905561389d8383836115c8565b505050565b6002670de0b6b3a76400006112bf565b600554600090610100900460ff16156138ca57600080fd5b6001600160a01b0382166000908152600b602052604090205460ff166138ef57600080fd5b6001600160a01b0382166000908152600b6020526040902060020154600d54613919908290613a0f565b9392505050565b600554600090610100900460ff161561393857600080fd5b6001600160a01b0382166000908152600b602052604090205460ff1661395d57600080fd5b506001600160a01b03166000908152600b602052604090206003015490565b6000806139898588613a0f565b905060006139978786613a75565b905060006139a58883613a0f565b905060006139b38285613b32565b90506139c781670de0b6b3a7640000613a75565b90506139db670de0b6b3a764000087613a75565b94506139f06139ea8c83613a9b565b86613a0f565b9b9a5050505050505050505050565b600654600160a01b900460ff1690565b600081613a1b57600080fd5b670de0b6b3a76400008302831580613a435750670de0b6b3a7640000848281613a4057fe5b04145b613a4c57600080fd5b60028304810181811015613a5f57600080fd5b6000848281613a6a57fe5b049695505050505050565b6000806000613a848585613da7565b915091508015613a9357600080fd5b509392505050565b6000828202831580613ab5575082848281613ab257fe5b04145b613abe57600080fd5b6706f05b59d3b20000810181811015613ad657600080fd5b6000670de0b6b3a764000082613a6a565b600082841015613af657600080fd5b670de0b6b3a7640000821115613b0b57600080fd5b6000613b178585613a75565b9050613b238184613a9b565b915081811015613a9357600080fd5b60006001831015613b4257600080fd5b671bc16d674ec7ffff831115613b5757600080fd5b6000613b6283613dcc565b90506000613b708483613a75565b90506000613b8686613b8185613de7565b613df5565b905081613b97579250611141915050565b6000613ba887846305f5e100613e4c565b9050613bb48282613a9b565b979650505050505050565b60008282018381101561391957600080fd5b613bdb8282613f2a565b5050565b613be881613f35565b50565b613bdb8282613fb4565b6040805163a9059cbb60e01b81526001600160a01b03848116600483015260248201849052915160009286169163a9059cbb91604480830192602092919082900301818787803b158015613c4857600080fd5b505af1158015613c5c573d6000803e3d6000fd5b505050506040513d6020811015613c7257600080fd5b5051905080613c8057600080fd5b50505050565b6001600160a01b038316600090815260208190526040902054811115613cab57600080fd5b6001600160a01b038316600090815260208190526040902054613cce9082613a75565b6001600160a01b038085166000908152602081905260408082209390935590841681522054613cfd9082613bbf565b6001600160a01b0380841660008181526020818152604091829020949094558051858152905191939287169260008051602061404383398151915292918290030190a3505050565b604080516323b872dd60e01b81526001600160a01b0384811660048301523060248301526044820184905291516000928616916323b872dd91606480830192602092919082900301818787803b158015613c4857600080fd5b613be881613fbf565b600080828410613dbd5750508082036000613dc5565b505081810360015b9250929050565b6000670de0b6b3a7640000613de083613de7565b0292915050565b670de0b6b3a7640000900490565b60008060028306613e0e57670de0b6b3a7640000613e10565b835b90506002830492505b821561391957613e298485613a9b565b93506002830615613e4157613e3e8185613a9b565b90505b600283049250613e19565b6000828180613e6387670de0b6b3a7640000613da7565b9092509050670de0b6b3a764000080600060015b888410613f1b576000670de0b6b3a764000082029050600080613eab8a613ea685670de0b6b3a7640000613a75565b613da7565b91509150613ebd87611311848c613a9b565b9650613ec98784613a0f565b965086613ed857505050613f1b565b8715613ee2579315935b8015613eec579315935b8415613f0357613efc8688613a75565b9550613f10565b613f0d8688613bbf565b95505b505050600101613e77565b50909998505050505050505050565b613bdb823083613c86565b30600090815260208190526040902054811115613f5157600080fd5b30600090815260208190526040902054613f6b9082613a75565b30600090815260208190526040902055600254613f889082613a75565b60025560408051828152905160009130916000805160206140438339815191529181900360200190a350565b613bdb308383613c86565b30600090815260208190526040902054613fd99082613bbf565b30600090815260208190526040902055600254613ff69082613bbf565b60025560408051828152905130916000916000805160206140438339815191529181900360200190a35056fe63982df10efd8dfaaaa0fcc7f50b2d93b7cba26ccc48adee2873220d485dc39addf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efe74c91552b64c2e2e7bd255639e004e693bd3e1d01cc33e65610b86afcc1ffed8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925a265627a7a72315820f9b2a615ae8e6d1abb19a5a5d9e1bf9edf711481354eccf109c3e0548ed8024b64736f6c634300050c0032a265627a7a72315820b5a09a05b3a281312f0ff93c65888f582453998e52641770b320e62c55d04f5564736f6c634300050c0032
{"success": true, "error": null, "results": {}}
true
null
{}
50
0x1248460fd7e9c7148f2c11e94e0524c3dcfa7219
pragma solidity 0.5.16; interface IParams { function isLiquidation(uint256 price) external view returns (bool); } interface IEsm { function shutdown() external; function isClosed() external view returns (bool); } contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require( msg.sender == nominatedOwner, "You must be nominated before you can accept ownership" ); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require( msg.sender == owner, "Only the contract owner may perform this action" ); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } 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 WhiteList is Owned { /// @notice Users with permissions mapping(address => uint256) public whiter; /// @notice Append address into whiteList successevent event AppendWhiter(address adder); /// @notice Remove address into whiteList successevent event RemoveWhiter(address remover); /** * @notice Construct a new WhiteList, default owner in whiteList */ constructor() internal { appendWhiter(owner); } modifier onlyWhiter() { require(isWhiter(), "WhiteList: msg.sender not in whilteList."); _; } /** * @notice Only onwer can append address into whitelist * @param account The address not added, can added to the whitelist */ function appendWhiter(address account) public onlyOwner { require(account != address(0), "WhiteList: address not zero"); require( !isWhiter(account), "WhiteListe: the account exsit whilteList yet" ); whiter[account] = 1; emit AppendWhiter(account); } /** * @notice Only onwer can remove address into whitelist * @param account The address in whitelist yet */ function removeWhiter(address account) public onlyOwner { require( isWhiter(account), "WhiteListe: the account not exist whilteList" ); delete whiter[account]; emit RemoveWhiter(account); } /** * @notice Check whether acccount in whitelist * @param account Any address */ function isWhiter(address account) public view returns (bool) { return whiter[account] == 1; } /** * @notice Check whether msg.sender in whitelist overrides. */ function isWhiter() public view returns (bool) { return isWhiter(msg.sender); } } contract Oracle is Owned, WhiteList { using SafeMath for uint256; /// @notice Token-usdt price uint256 public val; /// @notice Price update date(s) uint256 public time; /// @notice Oracle Name bytes32 name; /// @notice Oracle update success event event OracleUpdate(uint256 val, uint256 time); /// @notice Dparam address IParams params; /// @notice Esm address IEsm esm; /** * @notice Construct a new Oracle * @param _params Dynamic parameter contract address * @param _esm Esm parameter contract address */ constructor(address _params, address _esm) public Owned(msg.sender) { params = IParams(_params); esm = IEsm(_esm); name = "OIN-USDT"; } /** * @notice Chain-off push price to chain-on * @param price Token-usdt price decimals is same as token */ function poke(uint256 price) public onlyWhiter { require(!esm.isClosed(), "System closed yet."); val = price; time = block.timestamp; if (params.isLiquidation(price)) { esm.shutdown(); } else { emit OracleUpdate(val, time); } } /** * @notice Anybody can read the oracle price */ function peek() public view returns (uint256) { return val; } }
0x608060405234801561001057600080fd5b50600436106100cf5760003560e01c806353a47bb71161008c57806379ba50971161006657806379ba5097146102c05780638da5cb5b146102ca578063c97ec6bd14610314578063f95f450014610358576100cf565b806353a47bb71461020057806359e02dd71461024a57806367f3c2a514610268576100cf565b80631627540c146100d457806316ada547146101185780631dcba5311461013657806332145f901461015857806332a2b2db146101865780633c6bb436146101e2575b600080fd5b610116600480360360208110156100ea57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061039c565b005b6101206104e8565b6040518082815260200191505060405180910390f35b61013e6104ee565b604051808215151515815260200191505060405180910390f35b6101846004803603602081101561016e57600080fd5b81019080803590602001909291905050506104fe565b005b6101c86004803603602081101561019c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610800565b604051808215151515815260200191505060405180910390f35b6101ea61084c565b6040518082815260200191505060405180910390f35b610208610852565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b610252610878565b6040518082815260200191505060405180910390f35b6102aa6004803603602081101561027e57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610882565b6040518082815260200191505060405180910390f35b6102c861089a565b005b6102d2610ac0565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6103566004803603602081101561032a57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610ae5565b005b61039a6004803603602081101561036e57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610c91565b005b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610441576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f815260200180610f19602f913960400191505060405180910390fd5b80600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055507f906a1c6bd7e3091ea86693dd029a831c19049ce77f1dce2ce0bab1cacbabce2281604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a150565b60045481565b60006104f933610800565b905090565b6105066104ee565b61055b576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526028815260200180610fa06028913960400191505060405180910390fd5b600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663c2b6b58c6040518163ffffffff1660e01b815260040160206040518083038186803b1580156105c357600080fd5b505afa1580156105d7573d6000803e3d6000fd5b505050506040513d60208110156105ed57600080fd5b810190808051906020019092919050505015610671576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260128152602001807f53797374656d20636c6f736564207965742e000000000000000000000000000081525060200191505060405180910390fd5b8060038190555042600481905550600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663ab68bdb7826040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b1580156106f257600080fd5b505afa158015610706573d6000803e3d6000fd5b505050506040513d602081101561071c57600080fd5b8101908080519060200190929190505050156107b957600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663fc0e74d16040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561079c57600080fd5b505af11580156107b0573d6000803e3d6000fd5b505050506107fd565b7fd43c12578a968ffd94dee5ea7925911b346fff65b3be20ee01eef9fdb4af8655600354600454604051808381526020018281526020019250505060405180910390a15b50565b60006001600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054149050919050565b60035481565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000600354905090565b60026020528060005260406000206000915090505481565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610940576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526035815260200180610ee46035913960400191505060405180910390fd5b7fb532073b38c83145e3e5135377a08bf9aab55bc0fd7c1179cd4fb995d2a5159c6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060405180910390a1600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610b8a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f815260200180610f19602f913960400191505060405180910390fd5b610b9381610800565b610be8576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c815260200180610f48602c913960400191505060405180910390fd5b600260008273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600090557fa7498c8942adb10d7b806c9a26cff6dd93b6f0259681ffcb98d8dafd8b174f8e81604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a150565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610d36576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f815260200180610f19602f913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161415610dd9576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f57686974654c6973743a2061646472657373206e6f74207a65726f000000000081525060200191505060405180910390fd5b610de281610800565b15610e38576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c815260200180610f74602c913960400191505060405180910390fd5b6001600260008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055507ff6f23488d2332695a038c333e5b9b5ad5a5a6aa7001c5c8f2c851051907402c681604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a15056fe596f75206d757374206265206e6f6d696e61746564206265666f726520796f752063616e20616363657074206f776e6572736869704f6e6c792074686520636f6e7472616374206f776e6572206d617920706572666f726d207468697320616374696f6e57686974654c697374653a20746865206163636f756e74206e6f74206578697374207768696c74654c69737457686974654c697374653a20746865206163636f756e74206578736974207768696c74654c6973742079657457686974654c6973743a206d73672e73656e646572206e6f7420696e207768696c74654c6973742ea265627a7a723158204f3652f01144da7dadbde785601d135d4a0360fa764b6011b0e01b316276ec6d64736f6c63430005100032
{"success": true, "error": null, "results": {}}
true
null
{}
51
0x132ab3156a97b321b547c7747c996b6b680762e8
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'); } }
0x608060405234801561001057600080fd5b50600436106103db5760003560e01c806382c630661161020a578063d2797b5911610125578063e7c47e84116100b8578063f76c595511610087578063f76c595514610ab7578063f77c479114610add578063f8453e7c14610ae5578063fd96044b14610bb0578063fec8ee0c14610bd6576103db565b8063e7c47e8414610a45578063ef78d4fd14610a73578063efbe1c1c14610a92578063f301af4214610a9a576103db565b8063de263bfa116100f4578063de263bfa146109e1578063dfe0503114610a07578063e152253614610a0f578063e6f1daf214610a3d576103db565b8063d2797b591461095c578063d31f3f6d14610982578063d7981fe81461098a578063ddf2be3f146109b8576103db565b8063b21544f31161019d578063bf88a6ff1161016c578063bf88a6ff146108d0578063c0c53b8b146108d8578063c4d66de814610910578063cdf10baf14610936576103db565b8063b21544f314610853578063b6aa515b14610885578063b6b55f25146108ab578063be5d1be9146108c8576103db565b806396c55175116101d957806396c55175146107d95780639bd324f2146107ff5780639df4ed5614610825578063aaa626b61461084b576103db565b806382c630661461076357806384e9bd7e1461076b57806387564d84146107915780638ec872e3146107b6576103db565b80632e1a7d4d116102fa57806352665f471161028d57806370a082311161025c57806370a08231146107105780637598108c1461073657806376d8b1171461075357806381c0c2631461075b576103db565b806352665f471461069357806365fe9451146106bf5780636dd5b69d146106c75780636e553f65146106e4576103db565b80633ccfd60b116102c95780633ccfd60b1461061b5780633f26d0f91461062357806343d7f86f146106515780634b82009314610659576103db565b80632e1a7d4d1461058557806333134583146105a257806333fd6f74146105c857806338d07436146105f6576103db565b806317e28089116103725780631d2747d4116103415780631d2747d41461052157806323a582921461054f5780632585581f14610557578063275f63e91461055f576103db565b806317e28089146104e3578063180692d0146104eb57806318160ddd146104f35780631b9f546f146104fb576103db565b806313ecb1ca116103ae57806313ecb1ca1461046a57806313fa13681461049057806315fe96dc146104b657806316fa50b1146104db576103db565b806307546172146103e057806309400707146104045780630b54e7651461043c5780630c340a2414610462575b600080fd5b6103e8610bf3565b604080516001600160a01b039092168252519081900360200190f35b61042a6004803603602081101561041a57600080fd5b50356001600160a01b0316610c02565b60408051918252519081900360200190f35b61042a6004803603602081101561045257600080fd5b50356001600160a01b0316610c20565b6103e8610cb7565b61042a6004803603602081101561048057600080fd5b50356001600160a01b0316610cc6565b61042a600480360360208110156104a657600080fd5b50356001600160a01b0316610cd8565b6104d9600480360360408110156104cc57600080fd5b5080359060200135610cf6565b005b6103e8610d1b565b61042a610d36565b61042a610d3c565b61042a610d4e565b61042a6004803603602081101561051157600080fd5b50356001600160a01b0316610d54565b6104d96004803603604081101561053757600080fd5b506001600160a01b0381351690602001351515610d72565b61042a610da8565b61042a610dba565b61042a6004803603602081101561057557600080fd5b50356001600160a01b0316610dcc565b6104d96004803603602081101561059b57600080fd5b5035610e5d565b61042a600480360360208110156105b857600080fd5b50356001600160a01b0316610e6b565b61042a600480360360408110156105de57600080fd5b506001600160a01b0381358116916020013516610eb2565b6104d96004803603604081101561060c57600080fd5b50803590602001351515610f13565b6104d9610f9e565b61042a6004803603604081101561063957600080fd5b506001600160a01b0381358116916020013516610fbb565b61042a610fee565b61067f6004803603602081101561066f57600080fd5b50356001600160a01b0316611000565b604080519115158252519081900360200190f35b61042a600480360360408110156106a957600080fd5b50803590602001356001600160a01b0316611015565b61042a611031565b61042a600480360360208110156106dd57600080fd5b5035611043565b6104d9600480360360408110156106fa57600080fd5b50803590602001356001600160a01b0316611055565b61042a6004803603602081101561072657600080fd5b50356001600160a01b0316611158565b61042a6004803603602081101561074c57600080fd5b503561116a565b6103e861118a565b6104d9611199565b6103e86111fa565b6104d96004803603602081101561078157600080fd5b50356001600160a01b0316611209565b6104d9600480360360408110156107a757600080fd5b5080359060200135151561189f565b61042a600480360360408110156107cc57600080fd5b508035906020013561190a565b6104d9600480360360208110156107ef57600080fd5b50356001600160a01b031661191d565b61042a6004803603602081101561081557600080fd5b50356001600160a01b0316611928565b61042a6004803603602081101561083b57600080fd5b50356001600160a01b0316611946565b61042a61196c565b6104d96004803603606081101561086957600080fd5b508035906001600160a01b03602082013516906040013561197e565b6104d96004803603602081101561089b57600080fd5b50356001600160a01b03166119aa565b6104d9600480360360208110156108c157600080fd5b50356119ca565b61042a6119d4565b6103e86119da565b6104d9600480360360608110156108ee57600080fd5b506001600160a01b0381358116916020810135821691604090910135166119f5565b6104d96004803603602081101561092657600080fd5b50356001600160a01b0316611bb7565b61042a6004803603602081101561094c57600080fd5b50356001600160a01b0316611ca8565b61042a6004803603602081101561097257600080fd5b50356001600160a01b0316611e14565b61042a611fea565b61042a600480360360408110156109a057600080fd5b506001600160a01b0381358116916020013516611ffd565b6104d9600480360360608110156109ce57600080fd5b508035906020810135906040013561203f565b61042a600480360360208110156109f757600080fd5b50356001600160a01b0316612062565b6103e8612080565b61067f60048036036040811015610a2557600080fd5b506001600160a01b038135811691602001351661208f565b6104d96120af565b61042a60048036036040811015610a5b57600080fd5b506001600160a01b03813581169160200135166120b8565b610a7b6120e1565b60408051600f9290920b8252519081900360200190f35b61042a6120ea565b6103e860048036036020811015610ab057600080fd5b50356120fc565b61042a60048036036020811015610acd57600080fd5b50356001600160a01b031661212f565b6103e861214d565b6104d9600480360360a0811015610afb57600080fd5b6001600160a01b03823581169260208101358216926040820135831692606083013516919081019060a081016080820135640100000000811115610b3e57600080fd5b820183602082011115610b5057600080fd5b80359060200191846020830284011164010000000083111715610b7257600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092955061215c945050505050565b61042a60048036036020811015610bc657600080fd5b50356001600160a01b031661250f565b61042a60048036036020811015610bec57600080fd5b5035612535565b6035546001600160a01b031681565b6c02863c1f5cdae42f95400000436020526000908152604090205481565b6000610cb1826c02863c1f5cdae42f954000004560009054906101000a90046001600160a01b03166001600160a01b03166316fa50b16040518163ffffffff1660e01b815260040160206040518083038186803b158015610c8057600080fd5b505afa158015610c94573d6000803e3d6000fd5b505050506040513d6020811015610caa57600080fd5b5051610fbb565b92915050565b6033546001600160a01b031681565b603e6020526000908152604090205481565b6c02863c1f5cdae42f95400000486020526000908152604090205481565b6033546001600160a01b03163314610d0d57600080fd5b610d17828261255a565b5050565b6c02863c1f5cdae42f9540000046546001600160a01b031681565b603f5481565b6c02863c1f5cdae42f95400000445481565b603b5481565b6c02863c1f5cdae42f954000004d6020526000908152604090205481565b6001600160a01b03919091166000908152603d602090815260408083203384529091529020805460ff1916911515919091179055565b6c02863c1f5cdae42f95400000505481565b6c02863c1f5cdae42f954000004b5481565b6000610cb1826c02863c1f5cdae42f954000004560009054906101000a90046001600160a01b03166001600160a01b03166316fa50b16040518163ffffffff1660e01b815260040160206040518083038186803b158015610e2c57600080fd5b505afa158015610e40573d6000803e3d6000fd5b505050506040513d6020811015610e5657600080fd5b5051611ffd565b610e68816001610f13565b50565b6000610cb182610e79612581565b6c02863c1f5cdae42f954000004e546001600160a01b03861660009081526c02863c1f5cdae42f954000004d6020526040902054612706565b6001600160a01b0380821660008181526c02863c1f5cdae42f9540000053602090815260408083205494871683526c02863c1f5cdae42f95400000528252808320938352929052908120549091610f0c9185918491612706565b9392505050565b610f1d33826127a7565b603b54610f2a9083612943565b603b55336000908152603a6020526040902054610f479083612943565b336000818152603a6020526040902091909155610f649083612985565b60408051838152905133917f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a9424364919081900360200190a25050565b336000908152603a6020526040902054610fb9906001610f13565b565b6001600160a01b03811660009081526c02863c1f5cdae42f95400000536020526040812054610f0c908490839081612706565b6c02863c1f5cdae42f954000004f5481565b600061100d8260016127a7565b506001919050565b6001600160a01b03161860009081526034602052604090205490565b6c02863c1f5cdae42f954000004e5481565b60009081526034602052604090205490565b6001600160a01b03811633148061108f5750336000908152603d602090815260408083206001600160a01b038516845290915290205460ff165b6110cf576040805162461bcd60e51b815260206004820152600c60248201526b139bdd08185c1c1c9bdd995960a21b604482015290519081900360640190fd5b6110da8160016127a7565b6110e48183612a00565b336000908152603a60205260409020546110fe9083612aa0565b336000908152603a6020526040902055603b5461111b9083612aa0565b603b5560408051838152905133917fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c919081900360200190a25050565b603a6020526000908152604090205481565b6041816c01431e0fae6d7217caa0000000811061118357fe5b0154905081565b6036546001600160a01b031681565b6033546001600160a01b031633146111b057600080fd5b6033546040516000916001600160a01b0316907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908390a3603380546001600160a01b0319169055565b6037546001600160a01b031681565b6c02863c1f5cdae42f954000004b5415806112245750603b54155b1561122e57610e68565b6c02863c1f5cdae42f95400000515460609067ffffffffffffffff8111801561125657600080fd5b50604051908082528060200260200182016040528015611280578160200160208202803683370190505b50905060005b8151811015611344576c02863c1f5cdae42f954000005181815481106112a857fe5b60009182526020918290200154604080516370a0823160e01b815230600482015290516001600160a01b03909216926370a0823192602480840193829003018186803b1580156112f757600080fd5b505afa15801561130b573d6000803e3d6000fd5b505050506040513d602081101561132157600080fd5b5051825183908390811061133157fe5b6020908102919091010152600101611286565b506c02863c1f5cdae42f954000004560009054906101000a90046001600160a01b03166001600160a01b031663075461726040518163ffffffff1660e01b815260040160206040518083038186803b15801561139f57600080fd5b505afa1580156113b3573d6000803e3d6000fd5b505050506040513d60208110156113c957600080fd5b50516c02863c1f5cdae42f954000004554604080516335313c2160e11b81526001600160a01b03928316600482015290519190921691636a62784291602480830192600092919082900301818387803b15801561142557600080fd5b505af1158015611439573d6000803e3d6000fd5b505050506c02863c1f5cdae42f954000004560009054906101000a90046001600160a01b03166001600160a01b031663e6f1daf26040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561149957600080fd5b505af11580156114ad573d6000803e3d6000fd5b5050505060005b815181101561189a5760006115708383815181106114ce57fe5b60200260200101516c02863c1f5cdae42f954000005184815481106114ef57fe5b60009182526020918290200154604080516370a0823160e01b815230600482015290516001600160a01b03909216926370a0823192602480840193829003018186803b15801561153e57600080fd5b505afa158015611552573d6000803e3d6000fd5b505050506040513d602081101561156857600080fd5b505190612943565b9050600061162833836c02863c1f5cdae42f954000005360006c02863c1f5cdae42f954000005188815481106115a257fe5b60009182526020808320909101546001600160a01b031683528281019390935260409182018120543382526c02863c1f5cdae42f95400000529093529081206c02863c1f5cdae42f954000005180549192918a9081106115fe57fe5b60009182526020808320909101546001600160a01b03168352820192909252604001902054612706565b905081156116f657603b546116a7906116539061164d85670de0b6b3a7640000612afa565b90612b53565b6c02863c1f5cdae42f954000005360006c02863c1f5cdae42f9540000051878154811061167c57fe5b60009182526020808320909101546001600160a01b0316835282019290925260400190205490612aa0565b6c02863c1f5cdae42f954000005360006c02863c1f5cdae42f954000005186815481106116d057fe5b60009182526020808320909101546001600160a01b031683528201929092526040019020555b6c02863c1f5cdae42f954000005360006c02863c1f5cdae42f9540000051858154811061171f57fe5b60009182526020808320909101546001600160a01b031683528281019390935260409182018120543382526c02863c1f5cdae42f95400000529093529081206c02863c1f5cdae42f954000005180549192918790811061177b57fe5b60009182526020808320909101546001600160a01b0316835282019290925260400190205414611850576c02863c1f5cdae42f954000005360006c02863c1f5cdae42f954000005185815481106117ce57fe5b60009182526020808320909101546001600160a01b031683528281019390935260409182018120543382526c02863c1f5cdae42f95400000529093529081206c02863c1f5cdae42f954000005180549192918790811061182a57fe5b60009182526020808320909101546001600160a01b031683528201929092526040019020555b80156118905761189085826c02863c1f5cdae42f9540000051868154811061187457fe5b6000918252602090912001546001600160a01b03169190612b95565b50506001016114b4565b505050565b6033546001600160a01b031633146118b657600080fd5b6c02863c1f5cdae42f954000004b82905580156118e4574282016c02863c1f5cdae42f954000004c556118f6565b60006c02863c1f5cdae42f954000004c555b5050426c02863c1f5cdae42f954000005055565b1860009081526034602052604090205490565b610e688160016127a7565b6c02863c1f5cdae42f95400000426020526000908152604090205481565b6c02863c1f5cdae42f954000004654600090610cb19083906001600160a01b0316610fbb565b6c02863c1f5cdae42f95400000475481565b6033546001600160a01b0316331461199557600080fd5b61189a6001600160a01b03831684188261255a565b6033546001600160a01b031633146119c157600080fd5b610e6881612cff565b610e688133611055565b603c5481565b6c02863c1f5cdae42f9540000045546001600160a01b031681565b600054610100900460ff1680611a0e5750611a0e612d6e565b80611a1c575060005460ff16155b611a575760405162461bcd60e51b815260040180806020018281038252602e8152602001806133f0602e913960400191505060405180910390fd5b600054610100900460ff16158015611a82576000805460ff1961ff0019909116610100171660011790555b611a8b84611bb7565b603580546001600160a01b0319166001600160a01b03851690811790915560408051637e062a3560e11b8152905163fc0c546a91600480820192602092909190829003018186803b158015611adf57600080fd5b505afa158015611af3573d6000803e3d6000fd5b505050506040513d6020811015611b0957600080fd5b5051603680546001600160a01b03199081166001600160a01b0393841617909155603780549091168483161790819055604080516318160ddd60e01b8152905191909216916318160ddd916004808301926020929190829003018186803b158015611b7357600080fd5b505afa158015611b87573d6000803e3d6000fd5b505050506040513d6020811015611b9d57600080fd5b50508015611bb1576000805461ff00191690555b50505050565b600054610100900460ff1680611bd05750611bd0612d6e565b80611bde575060005460ff16155b611c195760405162461bcd60e51b815260040180806020018281038252602e8152602001806133f0602e913960400191505060405180910390fd5b600054610100900460ff16158015611c44576000805460ff1961ff0019909116610100171660011790555b603380546001600160a01b0319166001600160a01b0384811691909117918290556040519116906000907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908290a38015610d17576000805461ff00191690555050565b6c02863c1f5cdae42f9540000045546040805163d2797b5960e01b8152306004820152905160009283926001600160a01b039091169163d2797b5991602480820192602092909190829003018186803b158015611d0457600080fd5b505afa158015611d18573d6000803e3d6000fd5b505050506040513d6020811015611d2e57600080fd5b50516c02863c1f5cdae42f954000004554604080516316fa50b160e01b815290519293506000926001600160a01b03909216916316fa50b191600480820192602092909190829003018186803b158015611d8757600080fd5b505afa158015611d9b573d6000803e3d6000fd5b505050506040513d6020811015611db157600080fd5b50516001600160a01b0380821660008181526c02863c1f5cdae42f95400000536020908152604080832054948a1683526c02863c1f5cdae42f954000005282528083209383529290522054919250611e0c9186918591612706565b949350505050565b600080611f826c02863c1f5cdae42f954000004560009054906101000a90046001600160a01b03166001600160a01b031663075461726040518163ffffffff1660e01b815260040160206040518083038186803b158015611e7457600080fd5b505afa158015611e88573d6000803e3d6000fd5b505050506040513d6020811015611e9e57600080fd5b50516c02863c1f5cdae42f954000004554604080516308b752bb60e41b81523060048201526001600160a01b03928316602482015290519190921691638b752bb0916044808301926020929190829003018186803b158015611eff57600080fd5b505afa158015611f13573d6000803e3d6000fd5b505050506040513d6020811015611f2957600080fd5b50516c02863c1f5cdae42f95400000455460408051630940070760e01b815230600482015290516001600160a01b0390921691630940070791602480820192602092909190829003018186803b15801561153e57600080fd5b6c02863c1f5cdae42f9540000046546001600160a01b0390811660008181526c02863c1f5cdae42f9540000053602090815260408083205494891683526c02863c1f5cdae42f954000005282528083209383529290522054919250610f0c9185918491612706565b6c02863c1f5cdae42f9540000050545b90565b6001600160a01b0380831660009081526c02863c1f5cdae42f954000005260209081526040808320938516835292905290812054610f0c908490839081612706565b6033546001600160a01b0316331461205657600080fd5b61189a8383188261255a565b6c02863c1f5cdae42f95400000416020526000908152604090205481565b6039546001600160a01b031681565b603d60209081526000928352604080842090915290825290205460ff1681565b610fb933611209565b6c02863c1f5cdae42f954000005260209081526000928352604080842090915290825290205481565b604054600f0b81565b6c02863c1f5cdae42f954000004c5481565b6c02863c1f5cdae42f9540000051818154811061211557fe5b6000918252602090912001546001600160a01b0316905081565b6c02863c1f5cdae42f95400000536020526000908152604090205481565b6038546001600160a01b031681565b600054610100900460ff16806121755750612175612d6e565b80612183575060005460ff16155b6121be5760405162461bcd60e51b815260040180806020018281038252602e8152602001806133f0602e913960400191505060405180910390fd5b600054610100900460ff161580156121e9576000805460ff1961ff0019909116610100171660011790555b6121f48686866119f5565b6c02863c1f5cdae42f954000004580546001600160a01b0319166001600160a01b038516908117909155604080516376d8b11760e01b815290516376d8b11791600480820192602092909190829003018186803b15801561225457600080fd5b505afa158015612268573d6000803e3d6000fd5b505050506040513d602081101561227e57600080fd5b50516c02863c1f5cdae42f954000004680546001600160a01b0319166001600160a01b0390921691909117905581516122ca906c02863c1f5cdae42f954000005190602085019061334a565b506c02863c1f5cdae42f9540000046546c02863c1f5cdae42f9540000051805460018101825560009182527fc3a663b2abf67098c4ee9266947fc39af695e9ac338685a7b0e64b0d4464a7040180546001600160a01b0319166001600160a01b03938416179055604080516316fa50b160e01b8152905191928616916316fa50b191600480820192602092909190829003018186803b15801561236c57600080fd5b505afa158015612380573d6000803e3d6000fd5b505050506040513d602081101561239657600080fd5b505190506001600160a01b03811615612401576c02863c1f5cdae42f954000005180546001810182556000919091527fc3a663b2abf67098c4ee9266947fc39af695e9ac338685a7b0e64b0d4464a7040180546001600160a01b0319166001600160a01b0383161790555b836001600160a01b031663d31f3f6d6040518163ffffffff1660e01b815260040160206040518083038186803b15801561243a57600080fd5b505afa15801561244e573d6000803e3d6000fd5b505050506040513d602081101561246457600080fd5b50600090505b83518110156124f35783818151811061247f57fe5b60200260200101516001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156124bf57600080fd5b505afa1580156124d3573d6000803e3d6000fd5b505050506040513d60208110156124e957600080fd5b505060010161246a565b50508015612507576000805461ff00191690555b505050505050565b6c02863c1f5cdae42f954000004654600090610cb19083906001600160a01b0316611ffd565b6c01431e0fae6d7217caa0000041816c01431e0fae6d7217caa0000000811061118357fe5b6000828152603460205260409020548114610d175760009182526034602052604090912055565b6c02863c1f5cdae42f954000004f546035546040805163c33342e960e01b815230600482015290516000936125e49390926001600160a01b039091169163c33342e991602480820192602092909190829003018186803b15801561153e57600080fd5b90506c02863c1f5cdae42f954000004c5460001415612671576c02863c1f5cdae42f954000004b546c02863c1f5cdae42f954000005054612626904290612943565b101561266c576126696c02863c1f5cdae42f954000004b5461164d6126626c02863c1f5cdae42f9540000050544261294390919063ffffffff16565b8490612afa565b90505b611ffa565b6c02863c1f5cdae42f954000004c544210156126dd576126696126b96c02863c1f5cdae42f9540000050546c02863c1f5cdae42f954000004c5461294390919063ffffffff16565b61164d6126626c02863c1f5cdae42f9540000050544261294390919063ffffffff16565b6c02863c1f5cdae42f954000004c546c02863c1f5cdae42f95400000505410611ffa5750600090565b60006c02863c1f5cdae42f954000004b54600014806127255750603b54155b1561273257506000611e0c565b61273c8383612943565b9050612769612762603b5461164d670de0b6b3a764000088612afa90919063ffffffff16565b8290612aa0565b6001600160a01b0386166000908152603a602052604090205490915061279e90670de0b6b3a76400009061164d908490612afa565b95945050505050565b6c02863c1f5cdae42f954000004b5415806127c25750603b54155b156127cc57610d17565b60006127d6612581565b9050600061282584836c02863c1f5cdae42f954000004e546c02863c1f5cdae42f954000004d6000896001600160a01b03166001600160a01b0316815260200190815260200160002054612706565b90508082146128695761285981612853846c02863c1f5cdae42f954000004f54612aa090919063ffffffff16565b90612943565b6c02863c1f5cdae42f954000004f555b81156128b157603b546128a19061288c9061164d85670de0b6b3a7640000612afa565b6c02863c1f5cdae42f954000004e5490612aa0565b6c02863c1f5cdae42f954000004e555b6c02863c1f5cdae42f954000004e546001600160a01b03851660009081526c02863c1f5cdae42f954000004d60205260409020541461291f576c02863c1f5cdae42f954000004e546001600160a01b03851660009081526c02863c1f5cdae42f954000004d60205260409020555b426c02863c1f5cdae42f9540000050556129398482612d74565b611bb18484610d17565b6000610f0c83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250612f67565b6c02863c1f5cdae42f95400000455460408051632e1a7d4d60e01b81526004810184905290516001600160a01b0390921691632e1a7d4d9160248082019260009290919082900301818387803b1580156129de57600080fd5b505af11580156129f2573d6000803e3d6000fd5b50505050610d178282612ffe565b612a0a8282613015565b6c02863c1f5cdae42f954000004554603754612a33916001600160a01b0391821691168361302d565b6c02863c1f5cdae42f9540000045546040805163b6b55f2560e01b81526004810184905290516001600160a01b039092169163b6b55f259160248082019260009290919082900301818387803b158015612a8c57600080fd5b505af1158015612507573d6000803e3d6000fd5b600082820183811015610f0c576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b600082612b0957506000610cb1565b82820282848281612b1657fe5b0414610f0c5760405162461bcd60e51b81526004018080602001828103825260218152602001806133cf6021913960400191505060405180910390fd5b6000610f0c83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250613190565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b178152925182516000946060949389169392918291908083835b60208310612c125780518252601f199092019160209182019101612bf3565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114612c74576040519150601f19603f3d011682016040523d82523d6000602084013e612c79565b606091505b5091509150818015612ca7575080511580612ca75750808060200190516020811015612ca457600080fd5b50515b612cf8576040805162461bcd60e51b815260206004820152601f60248201527f5472616e7366657248656c7065723a205452414e534645525f4641494c454400604482015290519081900360640190fd5b5050505050565b6001600160a01b038116612d1257600080fd5b6033546040516001600160a01b038084169216907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a90600090a3603380546001600160a01b0319166001600160a01b0392909216919091179055565b303b1590565b8015610d17576001600160a01b03821660009081526c02863c1f5cdae42f95400000436020526040902054612da99082612aa0565b6001600160a01b0392831660009081526c02863c1f5cdae42f95400000436020908152604082209290925560349091527fe9b68ca2b566af5bdfbb3361c12fcbb5dbf956c250bbd74cc175cc06ec62c7915467646576526174696f60c01b9091527fb8fbd2e70438ec482a0e7fc9b87580647182c1694aea1065027a1d634e92d6b9549092831615801590612e3d57508015155b15612eac57612e86612e5b670de0b6b3a764000061164d8585612afa565b6001600160a01b03851660009081526c02863c1f5cdae42f9540000043602052604090205490612aa0565b6001600160a01b03841660009081526c02863c1f5cdae42f954000004360205260409020555b5060346020527f82e0b58992d24d827851dcbd63485b5933f9d3ae4c2ca50477d1437e73f6d342546765636f526174696f60c01b6000527ffc6561c6b7742261fbeab673eba1bedd2f5b1d7221f757ea8c9a87d664cfbed2549092506001600160a01b03831615801590612f1f57508015155b1561189a57612f3d612e5b670de0b6b3a764000061164d8585612afa565b6001600160a01b03841660009081526c02863c1f5cdae42f95400000436020526040902055505050565b60008184841115612ff65760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015612fbb578181015183820152602001612fa3565b50505050905090810190601f168015612fe85780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b603754610d17906001600160a01b03168383612b95565b603754610d17906001600160a01b03168330846131f5565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663095ea7b360e01b178152925182516000946060949389169392918291908083835b602083106130aa5780518252601f19909201916020918201910161308b565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d806000811461310c576040519150601f19603f3d011682016040523d82523d6000602084013e613111565b606091505b509150915081801561313f57508051158061313f575080806020019051602081101561313c57600080fd5b50515b612cf8576040805162461bcd60e51b815260206004820152601e60248201527f5472616e7366657248656c7065723a20415050524f56455f4641494c45440000604482015290519081900360640190fd5b600081836131df5760405162461bcd60e51b8152602060048201818152835160248401528351909283926044909101919085019080838360008315612fbb578181015183820152602001612fa3565b5060008385816131eb57fe5b0495945050505050565b604080516001600160a01b0385811660248301528481166044830152606480830185905283518084039091018152608490920183526020820180516001600160e01b03166323b872dd60e01b17815292518251600094606094938a169392918291908083835b6020831061327a5780518252601f19909201916020918201910161325b565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d80600081146132dc576040519150601f19603f3d011682016040523d82523d6000602084013e6132e1565b606091505b509150915081801561330f57508051158061330f575080806020019051602081101561330c57600080fd5b50515b6125075760405162461bcd60e51b815260040180806020018281038252602481526020018061341e6024913960400191505060405180910390fd5b82805482825590600052602060002090810192821561339f579160200282015b8281111561339f57825182546001600160a01b0319166001600160a01b0390911617825560209092019160019091019061336a565b506133ab9291506133af565b5090565b5b808211156133ab5780546001600160a01b03191681556001016133b056fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a65645472616e7366657248656c7065723a205452414e534645525f46524f4d5f4641494c4544a2646970667358221220e6b17a0285247d254acbd0a61e34ac7fc1ac8bd1bb2ce083df4eefde4a2366a964736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}]}
52
0x1363729a0cd6ed9e983d9bd385c9ed3591053703
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) { // 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; } } 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; } } contract NoRugToken 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; /** * @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 = "No Rug Token"; _symbol = "NRT"; _decimals = 18; _totalSupply = _totalSupply.add(35 * 1e4 * 10**_decimals); _balances[msg.sender] = _balances[msg.sender].add(35 * 1e4 * 10**_decimals); emit Transfer(address(0), msg.sender, 35 * 1e4 * 10**_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)); 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 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 { } }
0x608060405234801561001057600080fd5b50600436106100f55760003560e01c8063715018a611610097578063a457c2d711610066578063a457c2d7146102ca578063a9059cbb146102f6578063dd62ed3e14610322578063f2fde38b14610350576100f5565b8063715018a6146102775780638da5cb5b1461028157806395d89b41146102a55780639b1f9e74146102ad576100f5565b806323b872dd116100d357806323b872dd146101d1578063313ce56714610207578063395093511461022557806370a0823114610251576100f5565b806306fdde03146100fa578063095ea7b31461017757806318160ddd146101b7575b600080fd5b610102610376565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561013c578181015183820152602001610124565b50505050905090810190601f1680156101695780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101a36004803603604081101561018d57600080fd5b506001600160a01b03813516906020013561040c565b604080519115158252519081900360200190f35b6101bf610429565b60408051918252519081900360200190f35b6101a3600480360360608110156101e757600080fd5b506001600160a01b0381358116916020810135909116906040013561042f565b61020f61049e565b6040805160ff9092168252519081900360200190f35b6101a36004803603604081101561023b57600080fd5b506001600160a01b0381351690602001356104a7565b6101bf6004803603602081101561026757600080fd5b50356001600160a01b03166104f5565b61027f610510565b005b6102896105c4565b604080516001600160a01b039092168252519081900360200190f35b6101026105d3565b61027f600480360360208110156102c357600080fd5b5035610634565b6101a3600480360360408110156102e057600080fd5b506001600160a01b0381351690602001356106f1565b6101a36004803603604081101561030c57600080fd5b506001600160a01b03813516906020013561073f565b6101bf6004803603604081101561033857600080fd5b506001600160a01b0381358116916020013516610753565b61027f6004803603602081101561036657600080fd5b50356001600160a01b031661077e565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104025780601f106103d757610100808354040283529160200191610402565b820191906000526020600020905b8154815290600101906020018083116103e557829003601f168201915b5050505050905090565b60006104206104196108a1565b84846108a5565b50600192915050565b60035490565b600061043c848484610991565b610494846104486108a1565b6001600160a01b038716600090815260026020526040812061048f9187919061046f6108a1565b6001600160a01b0316815260208101919091526040016000205490610ad4565b6108a5565b5060019392505050565b60065460ff1690565b60006104206104b46108a1565b8461048f85600260006104c56108a1565b6001600160a01b03908116825260208083019390935260409182016000908120918c168152925290205490610888565b6001600160a01b031660009081526001602052604090205490565b6105186108a1565b6000546001600160a01b0390811691161461057a576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6000546001600160a01b031690565b60058054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104025780601f106103d757610100808354040283529160200191610402565b336106705760405162461bcd60e51b8152600401808060200182810382526021815260200180610b5a6021913960400191505060405180910390fd5b61067c33600083610ae9565b336000908152600160205260409020546106969082610ad4565b336000908152600160205260409020556003546106b39082610ad4565b60035560408051828152905160009133917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a350565b60006104206106fe6108a1565b8461048f856002600061070f6108a1565b6001600160a01b03908116825260208083019390935260409182016000908120918c168152925290205490610ad4565b600061042061074c6108a1565b8484610991565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b6107866108a1565b6000546001600160a01b039081169116146107e8576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b6001600160a01b03811661082d5760405162461bcd60e51b8152600401808060200182810382526026815260200180610b126026913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b60008282018381101561089a57600080fd5b9392505050565b3390565b6001600160a01b0383166108ea5760405162461bcd60e51b8152600401808060200182810382526024815260200180610ba06024913960400191505060405180910390fd5b6001600160a01b03821661092f5760405162461bcd60e51b8152600401808060200182810382526022815260200180610b386022913960400191505060405180910390fd5b6001600160a01b03808416600081815260026020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b0383166109d65760405162461bcd60e51b8152600401808060200182810382526025815260200180610b7b6025913960400191505060405180910390fd5b6001600160a01b038216610a1b5760405162461bcd60e51b8152600401808060200182810382526023815260200180610aef6023913960400191505060405180910390fd5b610a26838383610ae9565b6001600160a01b038316600090815260016020526040902054610a499082610ad4565b6001600160a01b038085166000908152600160205260408082209390935590841681522054610a789082610888565b6001600160a01b0380841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600082821115610ae357600080fd5b50900390565b50505056fe45524332303a207472616e7366657220746f20746865207a65726f20616464726573734f776e61626c653a206e6577206f776e657220697320746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f2061646472657373a26469706673582212205905fff2e76d829788a93164ae1eaf7a64b5dc4839da03ef68a01232f8e6d46764736f6c63430007000033
{"success": true, "error": null, "results": {}}
true
null
{}
53
0x136d6f80bb3a853d151686bfed2c9309aea6ddec
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 BFactory is BBronze { event LOG_NEW_POOL( address indexed caller, address indexed pool ); event LOG_BLABS( address indexed caller, address indexed blabs ); event LOG_RESERVES_ADDRESS( address indexed caller, address indexed reservesAddress ); event LOG_ALLOW_NON_ADMIN_POOL( address indexed caller, bool allow ); mapping(address=>bool) private _isBPool; function isBPool(address b) external view returns (bool) { return _isBPool[b]; } function newBPool() external returns (BPool) { if (!_allowNonAdminPool) { require(msg.sender == _blabs); } BPool bpool = new BPool(); _isBPool[address(bpool)] = true; emit LOG_NEW_POOL(msg.sender, address(bpool)); bpool.setController(msg.sender); return bpool; } address private _blabs; address private _reservesAddress; bool private _allowNonAdminPool; constructor() public { _blabs = msg.sender; _reservesAddress = msg.sender; _allowNonAdminPool = false; } function getAllowNonAdminPool() external view returns (bool) { return _allowNonAdminPool; } function setAllowNonAdminPool(bool b) external { require(msg.sender == _blabs, "ERR_NOT_BLABS"); emit LOG_ALLOW_NON_ADMIN_POOL(msg.sender, b); _allowNonAdminPool = b; } function getBLabs() external view returns (address) { return _blabs; } function setBLabs(address b) external { require(msg.sender == _blabs); emit LOG_BLABS(msg.sender, b); _blabs = b; } function getReservesAddress() external view returns (address) { return _reservesAddress; } function setReservesAddress(address a) external { require(msg.sender == _blabs); emit LOG_RESERVES_ADDRESS(msg.sender, a); _reservesAddress = a; } function collect(BPool pool) external { require(msg.sender == _blabs); require(_isBPool[address(pool)]); uint collected = IERC20(pool).balanceOf(address(this)); bool xfer = pool.transfer(_blabs, collected); require(xfer); } function collectTokenReserves(BPool pool) external { require(msg.sender == _blabs); require(_isBPool[address(pool)]); pool.drainTotalReserves(_reservesAddress); } } 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, "ERR_ADD_OVERFLOW"); return c; } function bsub(uint a, uint b) internal pure returns (uint) { (uint c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); 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, "ERR_MUL_OVERFLOW"); uint c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint c2 = c1 / BONE; return c2; } function bdiv(uint a, uint b) internal pure returns (uint) { require(b != 0, "ERR_DIV_ZERO"); uint c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // 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, "ERR_BPOW_BASE_TOO_LOW"); require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH"); 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 tokenInFee) { 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); tokenInFee = bsub(tokenAmountIn, adjustedIn); return (tokenAmountOut, tokenInFee); } /********************************************************************************************** // 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 tokenInFee) { uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BONE); foo = bmul(tokenBalanceIn, foo); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(foo, tokenAmountIn); tokenInFee = bdiv(foo, BONE); tokenInFee = bsub(tokenAmountIn, tokenInFee); return (tokenAmountIn, tokenInFee); } /********************************************************************************************** // 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, "ERR_MATH_APPROX"); require(reservesRatio <= BONE, "ERR_INVALID_RESERVE"); uint swapFeeAndReserves = bsub(amountWithFee, amountWithoutFee); reserves = bmul(swapFeeAndReserves, reservesRatio); require(swapFeeAndReserves >= reserves, "ERR_MATH_APPROX"); } function calcReservesFromFee(uint fee, uint reservesRatio) internal pure returns (uint reserves) { require(reservesRatio <= BONE, "ERR_INVALID_RESERVE"); reserves = bmul(fee, reservesRatio); } } 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, uint256 reservesAmount ); event LOG_JOIN( address indexed caller, address indexed tokenIn, uint256 tokenAmountIn, uint256 reservesAmount ); event LOG_EXIT( address indexed caller, address indexed tokenOut, uint256 tokenAmountOut, uint256 reservesAmount ); event LOG_DRAIN_RESERVES( address indexed caller, address indexed tokenOut, uint256 tokenAmountOut ); event LOG_ADD_RESERVES( address indexed token, uint256 reservesAmount ); 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); uint erc20Balance = IERC20(token).balanceOf(address(this)); uint reserves = totalReserves[token]; // `_records[token].balance` should be equaled to `bsub(erc20Balance, reserves)` unless there are extra // tokens transferred to this pool without calling `joinxxx`. require(_records[token].balance <= bsub(erc20Balance, reserves)); _records[token].balance = bsub(erc20Balance, reserves); } 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, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_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, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_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, "ERR_NOT_FINALIZED"); uint poolTotal = totalSupply(); uint ratio = bdiv(poolAmountOut, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); 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, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN"); _records[t].balance = badd(_records[t].balance, tokenAmountIn); emit LOG_JOIN(msg.sender, t, tokenAmountIn, 0); _pullUnderlying(t, msg.sender, tokenAmountIn); } _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); } function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external _logs_ _lock_ { require(_finalized, "ERR_NOT_FINALIZED"); uint poolTotal = totalSupply(); uint exitFee = bmul(poolAmountIn, EXIT_FEE); uint pAiAfterExitFee = bsub(poolAmountIn, exitFee); uint ratio = bdiv(pAiAfterExitFee, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); _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, "ERR_MATH_APPROX"); require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT"); _records[t].balance = bsub(_records[t].balance, tokenAmountOut); emit LOG_EXIT(msg.sender, t, tokenAmountOut, 0); _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, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); require(_publicSwap, "ERR_SWAP_NOT_PUBLIC"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO"); uint spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE"); uint tokenInFee; (tokenAmountOut, tokenInFee) = calcOutGivenIn( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); uint reserves = calcReservesFromFee(tokenInFee, _reservesRatio); // Subtract `reserves`. 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, "ERR_MATH_APPROX"); require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE"); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut, reserves); totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves); emit LOG_ADD_RESERVES(address(tokenIn), 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, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); require(_publicSwap, "ERR_SWAP_NOT_PUBLIC"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO"); uint spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE"); uint tokenInFee; (tokenAmountIn, tokenInFee) = calcInGivenOut( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountOut, _swapFee ); require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN"); uint reserves = calcReservesFromFee( tokenInFee, _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, "ERR_MATH_APPROX"); require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE"); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut, reserves); totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves); emit LOG_ADD_RESERVES(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, "ERR_NOT_FINALIZED"); require(_records[tokenIn].bound, "ERR_NOT_BOUND"); require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "ERR_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, "ERR_LIMIT_OUT"); inRecord.balance = bsub(badd(inRecord.balance, tokenAmountIn), reserves); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn, reserves); totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves); emit LOG_ADD_RESERVES(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, "ERR_NOT_FINALIZED"); require(_records[tokenIn].bound, "ERR_NOT_BOUND"); Record storage inRecord = _records[tokenIn]; tokenAmountIn = calcSingleInGivenPoolOut( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, poolAmountOut, _swapFee ); require(tokenAmountIn != 0, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN"); require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "ERR_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, reserves); totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves); emit LOG_ADD_RESERVES(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, "ERR_NOT_FINALIZED"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); Record storage outRecord = _records[tokenOut]; tokenAmountOut = calcSingleOutGivenPoolIn( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, poolAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "ERR_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, reserves); totalReserves[address(tokenOut)] = badd(totalReserves[address(tokenOut)], reserves); emit LOG_ADD_RESERVES(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, "ERR_NOT_FINALIZED"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "ERR_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, "ERR_MATH_APPROX"); require(poolAmountIn <= maxPoolAmountIn, "ERR_LIMIT_IN"); outRecord.balance = bsub(bsub(outRecord.balance, tokenAmountOut), reserves); uint exitFee = bmul(poolAmountIn, EXIT_FEE); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut, reserves); totalReserves[address(tokenOut)] = badd(totalReserves[address(tokenOut)], reserves); emit LOG_ADD_RESERVES(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, "ERR_ERC20_FALSE"); } function _pushUnderlying(address erc20, address to, uint amount) internal { bool xfer = IERC20(erc20).transfer(to, amount); require(xfer, "ERR_ERC20_FALSE"); } 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); } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c8063c124b18411610071578063c124b18414610142578063c2bb6dc214610168578063c6ce34fb146101a2578063d556c5dc146101c8578063db90def3146101d0578063e5a23849146101ef576100a9565b806306ec16f8146100ae5780632ad415bd146100d657806336ffb167146100fa5780638318f24a146101025780639a86139b14610128575b600080fd5b6100d4600480360360208110156100c457600080fd5b50356001600160a01b03166101f7565b005b6100de610341565b604080516001600160a01b039092168252519081900360200190f35b6100de610350565b6100d46004803603602081101561011857600080fd5b50356001600160a01b031661035f565b6101306103ce565b60408051918252519081900360200190f35b6100d46004803603602081101561015857600080fd5b50356001600160a01b03166103db565b61018e6004803603602081101561017e57600080fd5b50356001600160a01b0316610480565b604080519115158252519081900360200190f35b6100d4600480360360208110156101b857600080fd5b50356001600160a01b031661049e565b6100de61050d565b6100d4600480360360208110156101e657600080fd5b50351515610617565b61018e6106bc565b6001546001600160a01b0316331461020e57600080fd5b6001600160a01b03811660009081526020819052604090205460ff1661023357600080fd5b604080516370a0823160e01b815230600482015290516000916001600160a01b038416916370a0823191602480820192602092909190829003018186803b15801561027d57600080fd5b505afa158015610291573d6000803e3d6000fd5b505050506040513d60208110156102a757600080fd5b50516001546040805163a9059cbb60e01b81526001600160a01b0392831660048201526024810184905290519293506000929185169163a9059cbb9160448082019260209290919082900301818787803b15801561030457600080fd5b505af1158015610318573d6000803e3d6000fd5b505050506040513d602081101561032e57600080fd5b505190508061033c57600080fd5b505050565b6002546001600160a01b031690565b6001546001600160a01b031690565b6001546001600160a01b0316331461037657600080fd5b6040516001600160a01b0382169033907fe33f2276fe6ea8141b3855e68646ebcf09ec2df8768afe2a7bf153c9b10c273b90600090a3600280546001600160a01b0319166001600160a01b0392909216919091179055565b6542524f4e5a4560d01b90565b6001546001600160a01b031633146103f257600080fd5b6001600160a01b03811660009081526020819052604090205460ff1661041757600080fd5b6002546040805163577756b360e11b81526001600160a01b03928316600482015290519183169163aeeead669160248082019260009290919082900301818387803b15801561046557600080fd5b505af1158015610479573d6000803e3d6000fd5b5050505050565b6001600160a01b031660009081526020819052604090205460ff1690565b6001546001600160a01b031633146104b557600080fd5b6040516001600160a01b0382169033907ff586fa6ee1fc42f5b727f3b214ccbd0b6d7e698c45d49ba32f224fbb8670155d90600090a3600180546001600160a01b0319166001600160a01b0392909216919091179055565b600254600090600160a01b900460ff16610538576001546001600160a01b0316331461053857600080fd5b6000604051610546906106cc565b604051809103906000f080158015610562573d6000803e3d6000fd5b506001600160a01b038116600081815260208190526040808220805460ff1916600117905551929350909133917f8ccec77b0cb63ac2cafd0f5de8cdfadab91ce656d262240ba8a6343bccc5f94591a3604080516392eefe9b60e01b815233600482015290516001600160a01b038316916392eefe9b91602480830192600092919082900301818387803b1580156105f957600080fd5b505af115801561060d573d6000803e3d6000fd5b5092935050505090565b6001546001600160a01b03163314610666576040805162461bcd60e51b815260206004820152600d60248201526c4552525f4e4f545f424c41425360981b604482015290519081900360640190fd5b604080518215158152905133917f3f7cb0f9d9d6328953db4b2e4654f86a01cb45ec1e39aa6665763281ddca54a7919081900360200190a260028054911515600160a01b0260ff60a01b19909216919091179055565b600254600160a01b900460ff1690565b6153d7806106da8339019056fe60c0604052601060808190527f437265616d20506f6f6c20546f6b656e0000000000000000000000000000000060a0908152620000409160039190620000fe565b506040805180820190915260048082527f43525054000000000000000000000000000000000000000000000000000000006020909201918252620000859181620000fe565b506005805460ff19166012179055348015620000a057600080fd5b50600680546005805462010000600160b01b031916336201000081029190911790915564e8d4a510006007556702c68af0bb1400006008556001600160a01b03199091161760ff60a01b191690556009805460ff19169055620001a3565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200014157805160ff191683800117855562000171565b8280016001018555821562000171579182015b828111156200017157825182559160200191906001019062000154565b506200017f92915062000183565b5090565b620001a091905b808211156200017f57600081556001016200018a565b90565b61522480620001b36000396000f3fe608060405234801561001057600080fd5b506004361061039d5760003560e01c806392eefe9b116101eb578063bc694ea211610110578063dd62ed3e116100a8578063dd62ed3e14610c51578063e4a28a52146104fd578063e4e1e53814610c7f578063eb9253c014610cb1578063ec09302114610cdd578063f1b8a9b714610ce5578063f8b2cb4f14610d0b578063f8d6aed414610d31578063fde924f714610d6c5761039d565b8063bc694ea214610b7f578063be3bbd2e14610b87578063c36596a614610571578063c6580d1214610bdf578063cc77828d14610be7578063cd2ed8fb14610bef578063cf5e7bd314610bf7578063d4cadf6814610c1d578063d73dd62314610c255761039d565b8063a9059cbb11610183578063a9059cbb14610a40578063aeeead6614610a6c578063b02f0b7314610a92578063b0e0d13614610b07578063b4a8e10114610b0f578063b7b800a414610b2c578063ba019dab14610b34578063ba9530a614610b3c578063bc063e1a14610b775761039d565b806392eefe9b1461098f578063936c3477146109b55780639381cd2b146109bd57806393c88d14146109c5578063948d8ce6146109cd57806395d89b41146109f3578063992e2a92146109fb5780639a86139b14610a03578063a221ee4914610a0b5761039d565b806346ab38f1116102d15780636d0800bc116102695780636d0800bc1461084a57806370a082311461087057806376c7a3c7146108965780637c5e9ea41461089e5780638201aa3f146108de578063867378c51461091e57806389298012146109265780638c28cbe8146109615780638d4e4083146109875761039d565b806346ab38f1146106a957806349b59552146106db5780634bb278f3146106fa5780634d2fd81d146107025780634f69c0d41461070a5780635c1bbaf71461077f5780635db34277146107ba57806366188463146107ec5780636d06dfa0146108185761039d565b8063189d00ca11610344578063189d00ca14610569578063218b53821461057157806321abba011461057957806323b872dd146105ba5780632f37b624146105f05780633018205f14610616578063313ce5671461063a57806334e19907146106585780633fdddaa2146106775761039d565b8063024eb2e3146103a257806302c96748146103fc57806306fdde0314610440578063095ea7b3146104bd57806309a3bbe4146104fd5780631446a7ff1461050557806315e84af91461053357806318160ddd14610561575b600080fd5b6103e3600480360360e08110156103b857600080fd5b5080359060208101359060408101359060608101359060808101359060a08101359060c00135610d74565b6040805192835260208301919091528051918290030190f35b61042e6004803603606081101561041257600080fd5b506001600160a01b038135169060208101359060400135610e43565b60408051918252519081900360200190f35b6104486111df565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561048257818101518382015260200161046a565b50505050905090810190601f1680156104af5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6104e9600480360360408110156104d357600080fd5b506001600160a01b038135169060200135611275565b604080519115158252519081900360200190f35b61042e6112ca565b61042e6004803603604081101561051b57600080fd5b506001600160a01b03813581169160200135166112d7565b61042e6004803603604081101561054957600080fd5b506001600160a01b03813581169160200135166113f6565b61042e61150c565b61042e611512565b61042e611526565b6103e3600480360360e081101561058f57600080fd5b5080359060208101359060408101359060608101359060808101359060a08101359060c00135611532565b6104e9600480360360608110156105d057600080fd5b506001600160a01b038135811691602081013590911690604001356115df565b6104e96004803603602081101561060657600080fd5b50356001600160a01b03166116f9565b61061e611717565b604080516001600160a01b039092168252519081900360200190f35b61064261173f565b6040805160ff9092168252519081900360200190f35b6106756004803603602081101561066e57600080fd5b5035611748565b005b6106756004803603606081101561068d57600080fd5b506001600160a01b03813516906020810135906040013561182b565b61042e600480360360608110156106bf57600080fd5b506001600160a01b038135169060208101359060400135611a67565b610675600480360360208110156106f157600080fd5b50351515611dce565b610675611ea3565b61042e611fb3565b6106756004803603604081101561072057600080fd5b81359190810190604081016020820135600160201b81111561074157600080fd5b82018360208201111561075357600080fd5b803590602001918460208302840111600160201b8311171561077457600080fd5b509092509050611fd2565b61042e600480360360c081101561079557600080fd5b5080359060208101359060408101359060608101359060808101359060a00135612289565b61042e600480360360608110156107d057600080fd5b506001600160a01b03813516906020810135906040013561233c565b6104e96004803603604081101561080257600080fd5b506001600160a01b038135169060200135612659565b61042e6004803603606081101561082e57600080fd5b506001600160a01b038135169060208101359060400135612731565b61042e6004803603602081101561086057600080fd5b50356001600160a01b0316612a98565b61042e6004803603602081101561088657600080fd5b50356001600160a01b0316612aaa565b61042e612ac5565b6103e3600480360360a08110156108b457600080fd5b506001600160a01b0381358116916020810135916040820135169060608101359060800135612ad7565b6103e3600480360360a08110156108f457600080fd5b506001600160a01b0381358116916020810135916040820135169060608101359060800135612fd7565b61042e6134bc565b61042e600480360360c081101561093c57600080fd5b5080359060208101359060408101359060608101359060808101359060a001356134d0565b6106756004803603602081101561097757600080fd5b50356001600160a01b0316613580565b6104e9613726565b610675600480360360208110156109a557600080fd5b50356001600160a01b031661372f565b61042e6137fa565b61042e613819565b61042e613826565b61042e600480360360208110156109e357600080fd5b50356001600160a01b0316613836565b610448613892565b61042e6138f3565b61042e6138ff565b61042e600480360360a0811015610a2157600080fd5b508035906020810135906040810135906060810135906080013561390c565b6104e960048036036040811015610a5657600080fd5b506001600160a01b038135169060200135613971565b61067560048036036020811015610a8257600080fd5b50356001600160a01b0316613987565b61067560048036036040811015610aa857600080fd5b81359190810190604081016020820135600160201b811115610ac957600080fd5b820183602082011115610adb57600080fd5b803590602001918460208302840111600160201b83111715610afc57600080fd5b509092509050613acd565b61042e613dd2565b61067560048036036020811015610b2557600080fd5b5035613dd7565b61042e613ea8565b61042e613ead565b6103e3600480360360c0811015610b5257600080fd5b5080359060208101359060408101359060608101359060808101359060a00135613eb2565b61042e613f43565b61042e613f53565b610b8f613f5f565b60408051602080825283518183015283519192839290830191858101910280838360005b83811015610bcb578181015183820152602001610bb3565b505050509050019250505060405180910390f35b61042e613fe5565b610b8f613fea565b61042e614002565b61067560048036036020811015610c0d57600080fd5b50356001600160a01b0316614008565b61042e6142a4565b6104e960048036036040811015610c3b57600080fd5b506001600160a01b0381351690602001356142c3565b61042e60048036036040811015610c6757600080fd5b506001600160a01b0381358116916020013516614344565b61067560048036036060811015610c9557600080fd5b506001600160a01b03813516906020810135906040013561436f565b61067560048036036040811015610cc757600080fd5b506001600160a01b0381351690602001356144de565b61042e614642565b61042e60048036036020811015610cfb57600080fd5b50356001600160a01b0316614652565b61042e60048036036020811015610d2157600080fd5b50356001600160a01b03166146c0565b6103e3600480360360c0811015610d4757600080fd5b5080359060208101359060408101359060608101359060808101359060a0013561471c565b6104e96147c6565b6000806000610d8389886147d6565b90506000610da2610d9c670de0b6b3a7640000846148e9565b8761494b565b90506000610dc188610dbc670de0b6b3a7640000856148e9565b6147d6565b9050610dce818988614a0d565b93506000610ddc8d836148e9565b90506000610dea828f6147d6565b90506000610df88287614b0a565b90506000610e06828f61494b565b90506000610e148f836148e9565b9050610e2d81610dbc670de0b6b3a764000060006148e9565b9950505050505050505097509795505050505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615610ebb57600080fd5b6005805461ff00191661010017905560095460ff16610f15576040805162461bcd60e51b815260206004820152601160248201527011549497d393d517d19253905312569151607a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b602052604090205460ff16610f72576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b60205260409020600390810154610fa791670de0b6b3a76400005b0460010161494b565b831115610fef576040805162461bcd60e51b81526020600482015260116024820152704552525f4d41585f4f55545f524154494f60781b604482015290519081900360640190fd5b6000600b6000866001600160a01b03166001600160a01b031681526020019081526020016000209050600061103982600301548360020154600254600d5489600754600854610d74565b909350905082611082576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b838311156110c6576040805162461bcd60e51b815260206004820152600c60248201526b22a9292fa624a6a4aa2fa4a760a11b604482015290519081900360640190fd5b6110dd6110d78360030154876148e9565b826148e9565b600383015560006110ee848261494b565b604080518881526020810185905281519293506001600160a01b038a16923392600080516020615150833981519152928290030190a36001600160a01b0387166000908152600c60205260409020546111479083614c18565b6001600160a01b0388166000818152600c60209081526040918290209390935580518581529051919260008051602061517083398151915292918290030190a26111913385614c65565b6111a361119e85836148e9565b614c73565b6005546111bf906201000090046001600160a01b031682614c7f565b6111ca873388614c89565b5050506005805461ff00191690559392505050565b60038054604080516020601f600260001961010060018816150201909516949094049384018190048102820181019092528281526060939092909183018282801561126b5780601f106112405761010080835404028352916020019161126b565b820191906000526020600020905b81548152906001019060200180831161124e57829003601f168201915b5050505050905090565b3360008181526001602090815260408083206001600160a01b038716808552908352818420869055815186815291519394909390926000805160206151d0833981519152928290030190a35060015b92915050565b6802b5e3af16b188000081565b600554600090610100900460ff16156112ef57600080fd5b6001600160a01b0383166000908152600b602052604090205460ff1661134c576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0382166000908152600b602052604090205460ff166113a9576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b038084166000908152600b602052604080822092851682528120600380840154600280860154928401549084015493946113ed949293929061390c565b95945050505050565b600554600090610100900460ff161561140e57600080fd5b6001600160a01b0383166000908152600b602052604090205460ff1661146b576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0382166000908152600b602052604090205460ff166114c8576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b038084166000908152600b60205260408082209285168252902060038083015460028085015492840154908401546007546113ed9492919061390c565b60025490565b6402540be400670de0b6b3a76400005b0481565b670de0b6b3a764000081565b600080600061154189886147d6565b9050600061155a610d9c670de0b6b3a7640000846148e9565b9050600061157988611574670de0b6b3a7640000856148e9565b61494b565b9050611586888288614a0d565b935060006115948d83614c18565b905060006115a2828f6147d6565b905060006115b08287614b0a565b905060006115be828f61494b565b90506115ca818f6148e9565b98505050505050505097509795505050505050565b6000336001600160a01b038516148061161b57506001600160a01b03841660009081526001602090815260408083203384529091529020548211155b61162457600080fd5b61162f848484614d54565b336001600160a01b0385161480159061166d57506001600160a01b038416600090815260016020908152604080832033845290915290205460001914155b156116ef576001600160a01b03841660009081526001602090815260408083203384529091529020546116a090836148e9565b6001600160a01b03858116600090815260016020908152604080832033808552908352928190208590558051948552519287169391926000805160206151d08339815191529281900390910190a35b5060019392505050565b6001600160a01b03166000908152600b602052604090205460ff1690565b600554600090610100900460ff161561172f57600080fd5b506006546001600160a01b031690565b60055460ff1690565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156117be57600080fd5b6005805461ff00191661010017905560095460ff16156117dd57600080fd5b6006546001600160a01b031633146117f457600080fd5b64e8d4a5100081101561180657600080fd5b67016345785d8a000081111561181b57600080fd5b6007556005805461ff0019169055565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156118a157600080fd5b6005805461ff001916610100179055600654336001600160a01b03909116146118c957600080fd5b6001600160a01b0383166000908152600b602052604090205460ff166118ee57600080fd5b60095460ff16156118fe57600080fd5b670de0b6b3a764000081101561191357600080fd5b6802b5e3af16b188000081111561192957600080fd5b620f424082101561193957600080fd5b6001600160a01b0383166000908152600b60205260409020600201548082111561199157611972600d5461196d84846148e9565b614c18565b600d8190556802b5e3af16b1880000101561198c57600080fd5b6119b2565b808210156119b2576119ae600d546119a983856148e9565b6148e9565b600d555b6001600160a01b0384166000908152600b6020526040902060028101839055600301805490849055808411156119fb576119f685336119f187856148e9565b614e13565b611a55565b80841015611a55576000611a0f82866148e9565b90506000611a1e82600061494b565b9050611a348733611a2f85856148e9565b614c89565b600554611a529088906201000090046001600160a01b031683614c89565b50505b50506005805461ff0019169055505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615611adf57600080fd5b6005805461ff00191661010017905560095460ff16611b39576040805162461bcd60e51b815260206004820152601160248201527011549497d393d517d19253905312569151607a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b602052604090205460ff16611b96576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b6020526040902060038101546002808301549054600d54600754611bd0949392919089906134d0565b915082821015611c17576040805162461bcd60e51b815260206004820152600d60248201526c11549497d31253525517d3d555609a1b604482015290519081900360640190fd5b6001600160a01b0385166000908152600b60205260409020600390810154611c4791670de0b6b3a7640000610f9e565b821115611c8f576040805162461bcd60e51b81526020600482015260116024820152704552525f4d41585f4f55545f524154494f60781b604482015290519081900360640190fd5b6000611cac82600301548360020154600254600d548960006134d0565b90506000611cbd8285600854614a0d565b9050611cd06110d78460030154866148e9565b60038401556000611ce1878261494b565b604080518781526020810185905281519293506001600160a01b038b16923392600080516020615150833981519152928290030190a36001600160a01b0388166000908152600c6020526040902054611d3a9083614c18565b6001600160a01b0389166000818152600c60209081526040918290209390935580518581529051919260008051602061517083398151915292918290030190a2611d843388614c65565b611d9161119e88836148e9565b600554611dad906201000090046001600160a01b031682614c7f565b611db8883387614c89565b505050506005805461ff00191690559392505050565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615611e4457600080fd5b6005805461ff00191661010017905560095460ff1615611e6357600080fd5b6006546001600160a01b03163314611e7a57600080fd5b60068054911515600160a01b0260ff60a01b199092169190911790556005805461ff0019169055565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615611f1957600080fd5b6005805461ff001916610100179055600654336001600160a01b0390911614611f4157600080fd5b60095460ff1615611f5157600080fd5b600a5460021115611f6157600080fd5b6009805460ff191660011790556006805460ff60a01b1916600160a01b179055611f9368056bc75e2d63100000614e6c565b611fa63368056bc75e2d63100000614c7f565b6005805461ff0019169055565b600554600090610100900460ff1615611fcb57600080fd5b5060085490565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561204857600080fd5b6005805461ff00191661010017905560095460ff166120a2576040805162461bcd60e51b815260206004820152601160248201527011549497d393d517d19253905312569151607a1b604482015290519081900360640190fd5b60006120ac61150c565b905060006120ba85836147d6565b905080612100576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b60005b600a54811015612275576000600a828154811061211c57fe5b60009182526020808320909101546001600160a01b0316808352600b909152604082206003015490925090612151858361494b565b905080612197576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b8787858181106121a357fe5b905060200201358111156121ed576040805162461bcd60e51b815260206004820152600c60248201526b22a9292fa624a6a4aa2fa4a760a11b604482015290519081900360640190fd5b6001600160a01b0383166000908152600b60205260409020600301546122139082614c18565b6001600160a01b0384166000818152600b60209081526040808320600301949094558351858152908101919091528251919233926000805160206151908339815191529281900390910190a361226a833383614e13565b505050600101612103565b5061227f85614e6c565b611a553386614c7f565b60008061229687866147d6565b905060006122a48786614c18565b905060006122b282896147d6565b905060006122c8670de0b6b3a7640000856147d6565b905060006122d68383614b0a565b905060006122e4828e61494b565b905060006122f2828f6148e9565b9050600061231161230b670de0b6b3a76400008a6148e9565b8b61494b565b905061232982610dbc670de0b6b3a7640000846148e9565b9f9e505050505050505050505050505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156123b457600080fd5b6005805461ff00191661010017905560095460ff1661240e576040805162461bcd60e51b815260206004820152601160248201527011549497d393d517d19253905312569151607a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b602052604090205460ff1661246b576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b602052604090206003015461249d906002670de0b6b3a76400005b0461494b565b8311156124e4576040805162461bcd60e51b815260206004820152601060248201526f4552525f4d41585f494e5f524154494f60801b604482015290519081900360640190fd5b6000600b6000866001600160a01b03166001600160a01b031681526020019081526020016000209050600061252e82600301548360020154600254600d5489600754600854611532565b909350905083831015612578576040805162461bcd60e51b815260206004820152600d60248201526c11549497d31253525517d3d555609a1b604482015290519081900360640190fd5b6125896110d7836003015487614c18565b6003830155604080518681526020810183905281516001600160a01b038916923392600080516020615190833981519152929081900390910190a36001600160a01b0386166000908152600c60205260409020546125e79082614c18565b6001600160a01b0387166000818152600c60209081526040918290209390935580518481529051919260008051602061517083398151915292918290030190a261263083614e6c565b61263a3384614c7f565b612645863387614e13565b50506005805461ff00191690559392505050565b3360009081526001602090815260408083206001600160a01b0386168452909152812054808311156126ae573360009081526001602090815260408083206001600160a01b03881684529091528120556126dd565b6126b881846148e9565b3360009081526001602090815260408083206001600160a01b03891684529091529020555b3360008181526001602090815260408083206001600160a01b0389168085529083529281902054815190815290519293926000805160206151d0833981519152929181900390910190a35060019392505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156127a957600080fd5b6005805461ff00191661010017905560095460ff16612803576040805162461bcd60e51b815260206004820152601160248201527011549497d393d517d19253905312569151607a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b602052604090205460ff16612860576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0384166000908152600b6020526040902060038101546002808301549054600d5460075461289a94939291908990612289565b9150816128e0576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b82821115612924576040805162461bcd60e51b815260206004820152600c60248201526b22a9292fa624a6a4aa2fa4a760a11b604482015290519081900360640190fd5b6001600160a01b0385166000908152600b6020526040902060030154612954906002670de0b6b3a7640000612497565b82111561299b576040805162461bcd60e51b815260206004820152601060248201526f4552525f4d41585f494e5f524154494f60801b604482015290519081900360640190fd5b60006129b882600301548360020154600254600d54896000612289565b905060006129c98483600854614a0d565b90506129dc6110d7846003015486614c18565b6003840155604080518581526020810183905281516001600160a01b038a16923392600080516020615190833981519152929081900390910190a36001600160a01b0387166000908152600c6020526040902054612a3a9082614c18565b6001600160a01b0388166000818152600c60209081526040918290209390935580518481529051919260008051602061517083398151915292918290030190a2612a8386614e6c565b612a8d3387614c7f565b6111ca873386614e13565b600c6020526000908152604090205481565b6001600160a01b031660009081526020819052604090205490565b620f4240670de0b6b3a7640000611522565b60408051602080825236908201819052600092839233926001600160e01b03198535169285929081908101848480828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615612b3e57600080fd5b6005805461ff0019166101001790556001600160a01b0387166000908152600b602052604090205460ff16612baa576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0385166000908152600b602052604090205460ff16612c07576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b600654600160a01b900460ff16612c5b576040805162461bcd60e51b81526020600482015260136024820152724552525f535741505f4e4f545f5055424c494360681b604482015290519081900360640190fd5b6001600160a01b038088166000908152600b602052604080822092881682529020600380820154612c9491670de0b6b3a7640000610f9e565b861115612cdc576040805162461bcd60e51b81526020600482015260116024820152704552525f4d41585f4f55545f524154494f60781b604482015290519081900360640190fd5b6000612cfd836003015484600201548460030154856002015460075461390c565b905085811115612d4a576040805162461bcd60e51b81526020600482015260136024820152724552525f4241445f4c494d49545f505249434560681b604482015290519081900360640190fd5b6000612d6c84600301548560020154856003015486600201548c60075461471c565b909650905089861115612db5576040805162461bcd60e51b815260206004820152600c60248201526b22a9292fa624a6a4aa2fa4a760a11b604482015290519081900360640190fd5b6000612dc382600854614e75565b9050612dd66110d7866003015489614c18565b8560030181905550612dec84600301548a6148e9565b600380860182905586015460028088015490870154600754612e0f94919061390c565b955082861015612e58576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b87861115612e9f576040805162461bcd60e51b815260206004820152600f60248201526e4552525f4c494d49545f505249434560881b604482015290519081900360640190fd5b612ea9878a6147d6565b831115612eef576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b60408051888152602081018b905280820183905290516001600160a01b03808d1692908f169133917f50ef2fc267012b5c84b56835f16ffd5331ac5a151a3760d74908721ba78b0efe919081900360600190a46001600160a01b038c166000908152600c6020526040902054612f659082614c18565b6001600160a01b038d166000818152600c60209081526040918290209390935580518481529051919260008051602061517083398151915292918290030190a2612fb08c3389614e13565b612fbb8a338b614c89565b50505050506005805461ff001916905590969095509350505050565b60408051602080825236908201819052600092839233926001600160e01b03198535169285929081908101848480828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561303e57600080fd5b6005805461ff0019166101001790556001600160a01b0387166000908152600b602052604090205460ff166130aa576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b6001600160a01b0385166000908152600b602052604090205460ff16613107576040805162461bcd60e51b815260206004820152600d60248201526c11549497d393d517d093d55391609a1b604482015290519081900360640190fd5b600654600160a01b900460ff1661315b576040805162461bcd60e51b81526020600482015260136024820152724552525f535741505f4e4f545f5055424c494360681b604482015290519081900360640190fd5b6001600160a01b038088166000908152600b6020526040808220928816825290206003820154613195906002670de0b6b3a7640000612497565b8811156131dc576040805162461bcd60e51b815260206004820152601060248201526f4552525f4d41585f494e5f524154494f60801b604482015290519081900360640190fd5b60006131fd836003015484600201548460030154856002015460075461390c565b90508581111561324a576040805162461bcd60e51b81526020600482015260136024820152724552525f4241445f4c494d49545f505249434560681b604482015290519081900360640190fd5b600061326c84600301548560020154856003015486600201548e600754613eb2565b9096509050878610156132b6576040805162461bcd60e51b815260206004820152600d60248201526c11549497d31253525517d3d555609a1b604482015290519081900360640190fd5b60006132c482600854614e75565b90506132d76110d786600301548d614c18565b85600301819055506132ed8460030154886148e9565b60038086018290558601546002808801549087015460075461331094919061390c565b955082861015613359576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b878611156133a0576040805162461bcd60e51b815260206004820152600f60248201526e4552525f4c494d49545f505249434560881b604482015290519081900360640190fd5b6133aa8b886147d6565b8311156133f0576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b604080518c81526020810189905280820183905290516001600160a01b03808d1692908f169133917f50ef2fc267012b5c84b56835f16ffd5331ac5a151a3760d74908721ba78b0efe919081900360600190a46001600160a01b038c166000908152600c60205260409020546134669082614c18565b6001600160a01b038d166000818152600c60209081526040918290209390935580518481529051919260008051602061517083398151915292918290030190a26134b18c338d614e13565b612fbb8a3389614c89565b64e8d4a51000670de0b6b3a7640000611522565b6000806134dd87866147d6565b905060006134f885611574670de0b6b3a764000060006148e9565b9050600061350688836148e9565b90506000613514828a6147d6565b905060006135338261352e670de0b6b3a7640000886147d6565b614b0a565b90506000613541828e61494b565b9050600061354f8e836148e9565b9050600061356861230b670de0b6b3a76400008a6148e9565b905061232982611574670de0b6b3a7640000846148e9565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156135f657600080fd5b6005805461ff0019166101001790556001600160a01b0381166000908152600b602052604090205460ff1661362a57600080fd5b604080516370a0823160e01b815230600482015290516000916001600160a01b038416916370a0823191602480820192602092909190829003018186803b15801561367457600080fd5b505afa158015613688573d6000803e3d6000fd5b505050506040513d602081101561369e57600080fd5b50516001600160a01b0383166000908152600c60205260409020549091506136c682826148e9565b6001600160a01b0384166000908152600b602052604090206003015411156136ed57600080fd5b6136f782826148e9565b6001600160a01b039093166000908152600b602052604090206003019290925550506005805461ff0019169055565b60095460ff1690565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156137a557600080fd5b6005805461ff001916610100179055600654336001600160a01b03909116146137cd57600080fd5b600680546001600160a01b0319166001600160a01b03929092169190911790556005805461ff0019169055565b600554600090610100900460ff161561381257600080fd5b50600d5490565b68056bc75e2d6310000081565b6005670de0b6b3a7640000611522565b600554600090610100900460ff161561384e57600080fd5b6001600160a01b0382166000908152600b602052604090205460ff1661387357600080fd5b506001600160a01b03166000908152600b602052604090206002015490565b60048054604080516020601f600260001961010060018816150201909516949094049384018190048102820181019092528281526060939092909183018282801561126b5780601f106112405761010080835404028352916020019161126b565b6704a03ce68d21555681565b6542524f4e5a4560d01b90565b60008061391987876147d6565b9050600061392786866147d6565b9050600061393583836147d6565b90506000613957670de0b6b3a7640000610dbc670de0b6b3a7640000896148e9565b9050613963828261494b565b9a9950505050505050505050565b600061397e338484614d54565b50600192915050565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156139fd57600080fd5b6005805461010061ff001990911617908190556201000090046001600160a01b03163314613a2a57600080fd5b60005b600a54811015613abe576000600a8281548110613a4657fe5b60009182526020808320909101546001600160a01b03908116808452600c835260408085208054959055805185815290519195508593928816927f261074971f6b45f02124a88c43d5c95e174626f867c87684fb60dbbe35ec2cd292918290030190a3613ab4828583614c89565b5050600101613a2d565b50506005805461ff0019169055565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615613b4357600080fd5b6005805461ff00191661010017905560095460ff16613b9d576040805162461bcd60e51b815260206004820152601160248201527011549497d393d517d19253905312569151607a1b604482015290519081900360640190fd5b6000613ba761150c565b90506000613bb685600061494b565b90506000613bc486836148e9565b90506000613bd282856147d6565b905080613c18576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b613c223388614c65565b600554613c3e906201000090046001600160a01b031684614c7f565b613c4782614c73565b60005b600a54811015613dbd576000600a8281548110613c6357fe5b60009182526020808320909101546001600160a01b0316808352600b909152604082206003015490925090613c98858361494b565b905080613cde576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b898985818110613cea57fe5b90506020020135811015613d35576040805162461bcd60e51b815260206004820152600d60248201526c11549497d31253525517d3d555609a1b604482015290519081900360640190fd5b6001600160a01b0383166000908152600b6020526040902060030154613d5b90826148e9565b6001600160a01b0384166000818152600b60209081526040808320600301949094558351858152908101919091528251919233926000805160206151508339815191529281900390910190a3613db2833383614c89565b505050600101613c4a565b50506005805461ff0019169055505050505050565b600881565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615613e4d57600080fd5b6005805461ff00191661010017905560095460ff1615613e6c57600080fd5b6006546001600160a01b03163314613e8357600080fd5b670de0b6b3a7640000811115613e9857600080fd5b6008556005805461ff0019169055565b600281565b600181565b6000806000613ec188876147d6565b90506000613ed7670de0b6b3a7640000866148e9565b9050613ee3868261494b565b90506000613ef58b610dbc8d85614c18565b90506000613f038285614b0a565b90506000613f19670de0b6b3a7640000836148e9565b9050613f258b8261494b565b9650613f3189856148e9565b95505050505050965096945050505050565b600a670de0b6b3a7640000611522565b671bc16d674ec7ffff81565b600554606090610100900460ff1615613f7757600080fd5b60095460ff16613f8657600080fd5b600a80548060200260200160405190810160405280929190818152602001828054801561126b57602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311613fbe575050505050905090565b600081565b600554606090610100900460ff1615613f8657600080fd5b600a5490565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561407e57600080fd5b6005805461ff001916610100179055600654336001600160a01b03909116146140a657600080fd5b6001600160a01b0381166000908152600b602052604090205460ff166140cb57600080fd5b60095460ff16156140db57600080fd5b6001600160a01b0381166000908152600b602052604081206003015490614102828261494b565b600d546001600160a01b0385166000908152600b602052604090206002015491925061412d916148e9565b600d556001600160a01b0383166000908152600b6020526040902060010154600a8054600019810191908290811061416157fe5b600091825260209091200154600a80546001600160a01b03909216918490811061418757fe5b9060005260206000200160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555081600b6000600a85815481106141c757fe5b60009182526020808320909101546001600160a01b03168352820192909252604001902060010155600a8054806141fa57fe5b60008281526020808220600019908401810180546001600160a01b031916905590920190925560408051608081018252838152808301848152818301858152606083018681526001600160a01b038c168752600b909552929094209051815460ff191690151517815592516001840155516002830155516003909101556142868533611a2f87876148e9565b600554611a559086906201000090046001600160a01b031685614c89565b600554600090610100900460ff16156142bc57600080fd5b5060075490565b3360009081526001602090815260408083206001600160a01b03861684529091528120546142f19083614c18565b3360008181526001602090815260408083206001600160a01b0389168085529083529281902085905580519485525191936000805160206151d0833981519152929081900390910190a350600192915050565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a26006546001600160a01b031633146143e757600080fd5b6001600160a01b0383166000908152600b602052604090205460ff161561440d57600080fd5b60095460ff161561441d57600080fd5b600a5460081161442c57600080fd5b604080516080810182526001808252600a805460208085019182526000858701818152606087018281526001600160a01b038c16808452600b9094529782209651875460ff1916901515178755925186860155915160028601559451600390940193909355805491820181559091527fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a80180546001600160a01b03191690911790556144d983838361182b565b505050565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561455457600080fd5b6005805461ff001916610100179055600654336001600160a01b039091161461457c57600080fd5b6001600160a01b0382166000908152600b602052604090205460ff16156145a257600080fd5b604080516370a0823160e01b815230600482015290516000916001600160a01b038516916370a0823191602480820192602092909190829003018186803b1580156145ec57600080fd5b505afa158015614600573d6000803e3d6000fd5b505050506040513d602081101561461657600080fd5b505190508082111561462757600080fd5b614632833384614c89565b50506005805461ff001916905550565b6002670de0b6b3a7640000611522565b600554600090610100900460ff161561466a57600080fd5b6001600160a01b0382166000908152600b602052604090205460ff1661468f57600080fd5b6001600160a01b0382166000908152600b6020526040902060020154600d546146b99082906147d6565b9392505050565b600554600090610100900460ff16156146d857600080fd5b6001600160a01b0382166000908152600b602052604090205460ff166146fd57600080fd5b506001600160a01b03166000908152600b602052604090206003015490565b600080600061472b86896147d6565b9050600061473988876148e9565b9050600061474789836147d6565b905060006147558285614b0a565b905061476981670de0b6b3a76400006148e9565b90506147758c8261494b565b9050614789670de0b6b3a7640000886148e9565b955061479581876147d6565b95506147a981670de0b6b3a76400006147d6565b94506147b586866148e9565b945050505050965096945050505050565b600654600160a01b900460ff1690565b600081614819576040805162461bcd60e51b815260206004820152600c60248201526b4552525f4449565f5a45524f60a01b604482015290519081900360640190fd5b670de0b6b3a764000083028315806148415750670de0b6b3a764000084828161483e57fe5b04145b614885576040805162461bcd60e51b815260206004820152601060248201526f11549497d1125597d25395115493905360821b604482015290519081900360640190fd5b600283048101818110156148d3576040805162461bcd60e51b815260206004820152601060248201526f11549497d1125597d25395115493905360821b604482015290519081900360640190fd5b60008482816148de57fe5b049695505050505050565b60008060006148f88585614ed4565b915091508015614943576040805162461bcd60e51b81526020600482015260116024820152704552525f5355425f554e444552464c4f5760781b604482015290519081900360640190fd5b509392505050565b600082820283158061496557508284828161496257fe5b04145b6149a9576040805162461bcd60e51b815260206004820152601060248201526f4552525f4d554c5f4f564552464c4f5760801b604482015290519081900360640190fd5b6706f05b59d3b200008101818110156149fc576040805162461bcd60e51b815260206004820152601060248201526f4552525f4d554c5f4f564552464c4f5760801b604482015290519081900360640190fd5b6000670de0b6b3a7640000826148de565b600082841015614a56576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b670de0b6b3a7640000821115614aa9576040805162461bcd60e51b81526020600482015260136024820152724552525f494e56414c49445f5245534552564560681b604482015290519081900360640190fd5b6000614ab585856148e9565b9050614ac1818461494b565b915081811015614943576040805162461bcd60e51b815260206004820152600f60248201526e08aa4a4be9a82a890be82a0a0a49eb608b1b604482015290519081900360640190fd5b60006001831015614b5a576040805162461bcd60e51b81526020600482015260156024820152744552525f42504f575f424153455f544f4f5f4c4f5760581b604482015290519081900360640190fd5b671bc16d674ec7ffff831115614bb0576040805162461bcd60e51b815260206004820152601660248201527508aa4a4be84a09eaebe8482a68abea89e9ebe90928e960531b604482015290519081900360640190fd5b6000614bbb83614ef9565b90506000614bc984836148e9565b90506000614bdf86614bda85614f14565b614f22565b905081614bf05792506112c4915050565b6000614c0187846305f5e100614f79565b9050614c0d828261494b565b979650505050505050565b6000828201838110156146b9576040805162461bcd60e51b815260206004820152601060248201526f4552525f4144445f4f564552464c4f5760801b604482015290519081900360640190fd5b614c6f8282615057565b5050565b614c7c81615062565b50565b614c6f82826150e1565b6040805163a9059cbb60e01b81526001600160a01b03848116600483015260248201849052915160009286169163a9059cbb91604480830192602092919082900301818787803b158015614cdc57600080fd5b505af1158015614cf0573d6000803e3d6000fd5b505050506040513d6020811015614d0657600080fd5b5051905080614d4e576040805162461bcd60e51b815260206004820152600f60248201526e4552525f45524332305f46414c534560881b604482015290519081900360640190fd5b50505050565b6001600160a01b038316600090815260208190526040902054811115614d7957600080fd5b6001600160a01b038316600090815260208190526040902054614d9c90826148e9565b6001600160a01b038085166000908152602081905260408082209390935590841681522054614dcb9082614c18565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716926000805160206151b083398151915292918290030190a3505050565b604080516323b872dd60e01b81526001600160a01b0384811660048301523060248301526044820184905291516000928616916323b872dd91606480830192602092919082900301818787803b158015614cdc57600080fd5b614c7c816150ec565b6000670de0b6b3a7640000821115614eca576040805162461bcd60e51b81526020600482015260136024820152724552525f494e56414c49445f5245534552564560681b604482015290519081900360640190fd5b6146b9838361494b565b600080828410614eea5750508082036000614ef2565b505081810360015b9250929050565b6000670de0b6b3a7640000614f0d83614f14565b0292915050565b670de0b6b3a7640000900490565b60008060028306614f3b57670de0b6b3a7640000614f3d565b835b90506002830492505b82156146b957614f56848561494b565b93506002830615614f6e57614f6b818561494b565b90505b600283049250614f46565b6000828180614f9087670de0b6b3a7640000614ed4565b9092509050670de0b6b3a764000080600060015b888410615048576000670de0b6b3a764000082029050600080614fd88a614fd385670de0b6b3a76400006148e9565b614ed4565b91509150614fea87611574848c61494b565b9650614ff687846147d6565b96508661500557505050615048565b871561500f579315935b8015615019579315935b84156150305761502986886148e9565b955061503d565b61503a8688614c18565b95505b505050600101614fa4565b50909998505050505050505050565b614c6f823083614d54565b3060009081526020819052604090205481111561507e57600080fd5b3060009081526020819052604090205461509890826148e9565b306000908152602081905260409020556002546150b590826148e9565b60025560408051828152905160009130916000805160206151b08339815191529181900360200190a350565b614c6f308383614d54565b306000908152602081905260409020546151069082614c18565b306000908152602081905260409020556002546151239082614c18565b60025560408051828152905130916000916000805160206151b08339815191529181900360200190a35056fe9d9058fd2f25ccc389fec7720abef0ca83472f5abfafd5f10d37f51e6a0493f39448856d254ce9f0a13e70882297125673303bfaa163fc49ad146aa8bb55660715a8ca63e37b2cff1677df2b6b82d36fcf8a524228bd7a4b4d02d107c28c1e8addf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925a265627a7a723158207dad9bb8ad3db854a4a389f6262e2e5a43e63dd7f6f0ab3f7030243786f9ba5664736f6c634300050c0032a265627a7a72315820cc86a63508fbc4cc20b56ca9e2d3a44cde86d6ad19dc2d0e157ddd997d3b9c1864736f6c634300050c0032
{"success": true, "error": null, "results": {"detectors": [{"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}]}
54
0x13a1c4cead8552ea27c7adbd4d4af8b6ec1fd54f
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 SetTokenV2 { function getTotalComponentRealUnits(address) external view returns (int256); function getComponents() external view returns(address[] memory); } contract TokenSetsV2TokenAdapter 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: 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) { address[] memory components = SetTokenV2(token).getComponents(); Component[] memory underlyingTokens = new Component[](components.length); for (uint256 i = 0; i < underlyingTokens.length; i++) { underlyingTokens[i] = Component({ token: components[i], tokenType: "ERC20", rate: uint256(SetTokenV2(token).getTotalComponentRealUnits(components[i])) }); } return underlyingTokens; } }
0x608060405234801561001057600080fd5b50600436106100365760003560e01c80632a50c1461461003b57806379b1833414610064575b600080fd5b61004e610049366004610552565b610084565b60405161005b9190610820565b60405180910390f35b610077610072366004610552565b610286565b60405161005b919061076e565b61008c6104c9565b60405180608001604052808373ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff166306fdde036040518163ffffffff1660e01b815260040160006040518083038186803b1580156100f957600080fd5b505afa15801561010d573d6000803e3d6000fd5b505050506040513d6000823e601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682016040526101539190810190610638565b81526020018373ffffffffffffffffffffffffffffffffffffffff166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b15801561019e57600080fd5b505afa1580156101b2573d6000803e3d6000fd5b505050506040513d6000823e601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682016040526101f89190810190610638565b81526020018373ffffffffffffffffffffffffffffffffffffffff1663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b15801561024357600080fd5b505afa158015610257573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061027b91906106e2565b60ff16905292915050565b6060808273ffffffffffffffffffffffffffffffffffffffff166399d50d5d6040518163ffffffff1660e01b815260040160006040518083038186803b1580156102cf57600080fd5b505afa1580156102e3573d6000803e3d6000fd5b505050506040513d6000823e601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682016040526103299190810190610575565b90506060815167ffffffffffffffff8111801561034557600080fd5b5060405190808252806020026020018201604052801561037f57816020015b61036c61050a565b8152602001906001900390816103645790505b50905060005b81518110156104c15760405180606001604052808483815181106103a557fe5b602002602001015173ffffffffffffffffffffffffffffffffffffffff1681526020016040518060400160405280600581526020017f455243323000000000000000000000000000000000000000000000000000000081525081526020018673ffffffffffffffffffffffffffffffffffffffff1663eaf993e186858151811061042b57fe5b60200260200101516040518263ffffffff1660e01b815260040161044f919061074d565b60206040518083038186803b15801561046757600080fd5b505afa15801561047b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061049f9190610620565b8152508282815181106104ae57fe5b6020908102919091010152600101610385565b509392505050565b6040518060800160405280600073ffffffffffffffffffffffffffffffffffffffff1681526020016060815260200160608152602001600060ff1681525090565b6040518060600160405280600073ffffffffffffffffffffffffffffffffffffffff16815260200160608152602001600081525090565b805161054c81610907565b92915050565b600060208284031215610563578081fd5b813561056e81610907565b9392505050565b60006020808385031215610587578182fd5b825167ffffffffffffffff8082111561059e578384fd5b81850186601f8201126105af578485fd5b80519250818311156105bf578485fd5b83830291506105cf8483016108b0565b8381528481019082860184840187018a10156105e9578788fd5b8794505b85851015610613576105ff8a82610541565b8352600194909401939186019186016105ed565b5098975050505050505050565b600060208284031215610631578081fd5b5051919050565b600060208284031215610649578081fd5b815167ffffffffffffffff80821115610660578283fd5b81840185601f820112610671578384fd5b8051925081831115610681578384fd5b6106b260207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f860116016108b0565b91508282528560208483010111156106c8578384fd5b6106d98360208401602084016108d7565b50949350505050565b6000602082840312156106f3578081fd5b815160ff8116811461056e578182fd5b6000815180845261071b8160208601602086016108d7565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b60208082528251828201819052600091906040908185019080840286018301878501865b83811015610812577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc08984030185528151606073ffffffffffffffffffffffffffffffffffffffff825116855288820151818a8701526107f482870182610703565b92890151958901959095525094870194925090860190600101610792565b509098975050505050505050565b60006020825273ffffffffffffffffffffffffffffffffffffffff835116602083015260208301516080604084015261085c60a0840182610703565b604085015191507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08482030160608501526108978183610703565b60ff606087015116608086015280935050505092915050565b60405181810167ffffffffffffffff811182821017156108cf57600080fd5b604052919050565b60005b838110156108f25781810151838201526020016108da565b83811115610901576000848401525b50505050565b73ffffffffffffffffffffffffffffffffffffffff8116811461092957600080fd5b5056fea2646970667358221220a652505937d26022beaa082bfe3187b34f32384806d4882b070250bf3a4670fc64736f6c63430006050033
{"success": true, "error": null, "results": {}}
true
null
{}
55
0x13B70f58f8e7Fce3811401fF65D2dF33AD5DC61D
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)) ); } }
0x6080604052600436106100295760003560e01c80638b4187131461002e578063c848aed214610050575b600080fd5b34801561003a57600080fd5b5061004e610049366004611c95565b610063565b005b61004e61005e366004611c28565b6102bc565b61006b611b49565b8180602001905181019061007f9190611da8565b905060006100b3732f0b23f53734252bda2277357e97e1517d6b042a644554482d4160d81b846040015185602001516108fe565b6060830151602084015160405163095ea7b360e01b8152929350736b175474e89094c44da98b954eedeac495271d0f9263095ea7b3926100f7929091600401611fdb565b602060405180830381600087803b15801561011157600080fd5b505af1158015610125573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101499190611d70565b61016e5760405162461bcd60e51b81526004016101659061213e565b60405180910390fd5b60608201516020830151604051635320bf6b60e11b81526001600160a01b039092169163a6417ed6916101ab9160009160019183906004016120b3565b600060405180830381600087803b1580156101c557600080fd5b505af11580156101d9573d6000803e3d6000fd5b50506040516370a0823160e01b81526000925073a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4891506370a0823190610217903090600401611f89565b60206040518083038186803b15801561022f57600080fd5b505afa158015610243573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102679190611d90565b905061029173a191e578a6736167326d05c119ce0c90849e84b784600001518386602001516109a2565b6102b4732f0b23f53734252bda2277357e97e1517d6b042a838560400151610d9f565b505050505050565b346002146102dc5760405162461bcd60e51b815260040161016590612120565b6040516370a0823160e01b8152819073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2906370a0823190610315908a90600401611f89565b60206040518083038186803b15801561032d57600080fd5b505afa158015610341573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103659190611d90565b10156103835760405162461bcd60e51b8152600401610165906121ad565b6040516323b872dd60e01b815273a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48906323b872dd906103be90339030908890600401611f9d565b602060405180830381600087803b1580156103d857600080fd5b505af11580156103ec573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104109190611d70565b61042c5760405162461bcd60e51b81526004016101659061216b565b85600061044d8273c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2611124565b905073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004016000604051808303818588803b15801561049e57600080fd5b505af11580156104b2573d6000803e3d6000fd5b5073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2935063095ea7b392508b91506104e090508634611275565b6040518363ffffffff1660e01b81526004016104fd929190611fdb565b602060405180830381600087803b15801561051757600080fd5b505af115801561052b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061054f9190611d70565b5060408051600380825260808201909252606091816020015b610570611b7a565b81526020019060019003908161056857905050905061058f82856112a1565b8160008151811061059c57fe5b60200260200101819052506105f860405180608001604052808981526020018781526020018681526020018a6001600160a01b03168152506040516020016105e4919061227e565b60405160208183030381529060405261132b565b8160018151811061060557fe5b60209081029190910101526106238261061e8634611275565b6113a7565b8160028151811061063057fe5b6020908102919091010152604080516001808252818301909252606091816020015b61065a611bcc565b8152602001906001900390816106525790505090506106776113e2565b8160008151811061068457fe5b602090810291909101015260405163a67a6a4560e01b81526001600160a01b0385169063a67a6a45906106bd9084908690600401611ff4565b600060405180830381600087803b1580156106d757600080fd5b505af11580156106eb573d6000803e3d6000fd5b50506040516370a0823160e01b8152736b175474e89094c44da98b954eedeac495271d0f925063a9059cbb91508d9083906370a0823190610730903090600401611f89565b60206040518083038186803b15801561074857600080fd5b505afa15801561075c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107809190611d90565b6040518363ffffffff1660e01b815260040161079d929190611fdb565b602060405180830381600087803b1580156107b757600080fd5b505af11580156107cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107ef9190611d70565b506040516370a0823160e01b815273a0b86991c6218b36c1d19d4a2e9eb0ce3606eb489063a9059cbb908d9083906370a0823190610831903090600401611f89565b60206040518083038186803b15801561084957600080fd5b505afa15801561085d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108819190611d90565b6040518363ffffffff1660e01b815260040161089e929190611fdb565b602060405180830381600087803b1580156108b857600080fd5b505af11580156108cc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108f09190611d70565b505050505050505050505050565b604051636090dec560e01b8152600090735ef30b9986345249bc32d8928b7ee64de9435e3990636090dec59061093a908790309060040161209c565b602060405180830381600087803b15801561095457600080fd5b505af1158015610968573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061098c9190611d90565b905061099a858285856109a2565b949350505050565b604051632726b07360e01b8152735ef30b9986345249bc32d8928b7ee64de9435e39906000908290632726b073906109de908890600401612093565b60206040518083038186803b1580156109f657600080fd5b505afa158015610a0a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a2e9190611c0c565b90506000826001600160a01b03166336569e776040518163ffffffff1660e01b815260040160206040518083038186803b158015610a6b57600080fd5b505afa158015610a7f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610aa39190611c0c565b90506000836001600160a01b0316632c2cb9fd886040518263ffffffff1660e01b8152600401610ad39190612093565b60206040518083038186803b158015610aeb57600080fd5b505afa158015610aff573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b239190611d90565b9050610b328884886001611402565b836001600160a01b03166345e6bdcd88610b54610b4f8c8b611541565b6115c6565b610b75867319c0976f590d67707e62397c87829d896dc0f1f189888d6115e8565b6040518463ffffffff1660e01b8152600401610b93939291906122d1565b600060405180830381600087803b158015610bad57600080fd5b505af1158015610bc1573d6000803e3d6000fd5b50505050836001600160a01b031663f9f30db68830610bdf89611779565b6040518463ffffffff1660e01b8152600401610bfd939291906122b2565b600060405180830381600087803b158015610c1757600080fd5b505af1158015610c2b573d6000803e3d6000fd5b5050604051634538c4eb60e01b81526001600160a01b0385169250634538c4eb9150610c71903090739759a6ac90977b93b58547b4a71c78317f391a2890600401611fc1565b60206040518083038186803b158015610c8957600080fd5b505afa158015610c9d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cc19190611d90565b610d38576040516328ec8bf160e21b81526001600160a01b0383169063a3b22fc490610d0590739759a6ac90977b93b58547b4a71c78317f391a2890600401611f89565b600060405180830381600087803b158015610d1f57600080fd5b505af1158015610d33573d6000803e3d6000fd5b505050505b60405163ef693bed60e01b8152739759a6ac90977b93b58547b4a71c78317f391a289063ef693bed90610d719030908990600401611fdb565b600060405180830381600087803b158015610d8b57600080fd5b505af11580156108f0573d6000803e3d6000fd5b6000735ef30b9986345249bc32d8928b7ee64de9435e3990506000816001600160a01b03166336569e776040518163ffffffff1660e01b815260040160206040518083038186803b158015610df357600080fd5b505afa158015610e07573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e2b9190611c0c565b90506000826001600160a01b0316632726b073866040518263ffffffff1660e01b8152600401610e5b9190612093565b60206040518083038186803b158015610e7357600080fd5b505afa158015610e87573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610eab9190611c0c565b90506000836001600160a01b0316632c2cb9fd876040518263ffffffff1660e01b8152600401610edb9190612093565b60206040518083038186803b158015610ef357600080fd5b505afa158015610f07573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f2b9190611d90565b90506000836001600160a01b0316632424be5c83856040518363ffffffff1660e01b8152600401610f5d92919061209c565b604080518083038186803b158015610f7457600080fd5b505afa158015610f88573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fac9190611df5565b915050610fd9739759a6ac90977b93b58547b4a71c78317f391a2884610fd487878888611791565b61196f565b6000610fe58988611541565b9050856001600160a01b03166345e6bdcd89611000846115c6565b600003856000036040518463ffffffff1660e01b8152600401611025939291906122d1565b600060405180830381600087803b15801561103f57600080fd5b505af1158015611053573d6000803e3d6000fd5b50506040516313771f0760e31b81526001600160a01b0389169250639bb8f8389150611087908b90309086906004016122b2565b600060405180830381600087803b1580156110a157600080fd5b505af11580156110b5573d6000803e3d6000fd5b505060405163ef693bed60e01b81526001600160a01b038c16925063ef693bed91506110e79030908b90600401611fdb565b600060405180830381600087803b15801561110157600080fd5b505af1158015611115573d6000803e3d6000fd5b50505050505050505050505050565b6000808390506000816001600160a01b031663295c39a56040518163ffffffff1660e01b815260040160206040518083038186803b15801561116557600080fd5b505afa158015611179573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061119d9190611d90565b90506000805b828110156112565760405163062bd3e960e01b81526001600160a01b0385169063062bd3e9906111d7908490600401612093565b60206040518083038186803b1580156111ef57600080fd5b505afa158015611203573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112279190611c0c565b9150856001600160a01b0316826001600160a01b0316141561124e57935061126f92505050565b6001016111a3565b5060405162461bcd60e51b815260040161016590612214565b92915050565b60008282018381101561129a5760405162461bcd60e51b8152600401610165906120e9565b9392505050565b6112a9611b7a565b604080516101008101825260018152600060208083018290528351608081018552828152929384019291908201905b81526020016000815260200185815250815260200184815260200160008152602001306001600160a01b031681526020016000815260200160405180602001604052806000815250815250905092915050565b611333611b7a565b60408051610100810182526008815260006020808301829052835160808101855282815292938401929190820190815260200160008152602001600081525081526020016000815260200160008152602001306001600160a01b03168152602001600081526020018381525090505b919050565b6113af611b7a565b604080516101008101825260008082526020808301829052835160808101855260018152929384019291908201906112d8565b6113ea611bcc565b50604080518082019091523081526001602082015290565b80156114db57836001600160a01b0316637bd2bea76040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561144357600080fd5b505af1158015611457573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061147b9190611c0c565b6001600160a01b031663095ea7b385846040518363ffffffff1660e01b81526004016114a8929190611fdb565b600060405180830381600087803b1580156114c257600080fd5b505af11580156114d6573d6000803e3d6000fd5b505050505b604051633b4da69f60e01b81526001600160a01b03851690633b4da69f906115099086908690600401611fdb565b600060405180830381600087803b15801561152357600080fd5b505af1158015611537573d6000803e3d6000fd5b5050505050505050565b600061129a836001600160a01b031663b3bcfa826040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561158157600080fd5b505af1158015611595573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115b99190611d90565b8390601203600a0a611aa6565b8060008112156113a25760405162461bcd60e51b815260040161016590612258565b600080856001600160a01b03166344e2a5a8856040518263ffffffff1660e01b81526004016116179190612093565b602060405180830381600087803b15801561163157600080fd5b505af1158015611645573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116699190611d90565b90506000876001600160a01b0316636c25b346876040518263ffffffff1660e01b81526004016116999190611f89565b60206040518083038186803b1580156116b157600080fd5b505afa1580156116c5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116e99190611d90565b9050611701846b033b2e3c9fd0803ce8000000611aa6565b81101561176e576117398261172c83611726886b033b2e3c9fd0803ce8000000611aa6565b90611ae0565b8161173357fe5b046115c6565b9250611751846b033b2e3c9fd0803ce8000000611aa6565b61175b8484611aa6565b10611766578261176b565b826001015b92505b505095945050505050565b600061126f826b033b2e3c9fd0803ce8000000611aa6565b600080856001600160a01b031663d9638d36846040518263ffffffff1660e01b81526004016117c09190612093565b60a06040518083038186803b1580156117d857600080fd5b505afa1580156117ec573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118109190611e18565b5050509150506000866001600160a01b0316632424be5c85876040518363ffffffff1660e01b815260040161184692919061209c565b604080518083038186803b15801561185d57600080fd5b505afa158015611871573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118959190611df5565b9150506000876001600160a01b0316636c25b346886040518263ffffffff1660e01b81526004016118c69190611f89565b60206040518083038186803b1580156118de57600080fd5b505afa1580156118f2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119169190611d90565b90506000611928826117268587611aa6565b90506b033b2e3c9fd0803ce80000008104945080611952866b033b2e3c9fd0803ce8000000611aa6565b1061195d5784611962565b846001015b9998505050505050505050565b826001600160a01b031663f4b9fa756040518163ffffffff1660e01b8152600401602060405180830381600087803b1580156119aa57600080fd5b505af11580156119be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119e29190611c0c565b6001600160a01b031663095ea7b384836040518363ffffffff1660e01b8152600401611a0f929190611fdb565b600060405180830381600087803b158015611a2957600080fd5b505af1158015611a3d573d6000803e3d6000fd5b5050604051633b4da69f60e01b81526001600160a01b0386169250633b4da69f9150611a6f9085908590600401611fdb565b600060405180830381600087803b158015611a8957600080fd5b505af1158015611a9d573d6000803e3d6000fd5b50505050505050565b600082611ab55750600061126f565b82820282848281611ac257fe5b041461129a5760405162461bcd60e51b8152600401610165906121d3565b600061129a83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f77000081525060008184841115611b415760405162461bcd60e51b815260040161016591906120d6565b505050900390565b604051806080016040528060008152602001600081526020016000815260200160006001600160a01b031681525090565b604080516101008101825260008082526020820152908101611b9a611be3565b8152602001600081526020016000815260200160006001600160a01b0316815260200160008152602001606081525090565b604080518082019091526000808252602082015290565b604080516080810190915260008082526020820190815260200160008152602001600081525090565b600060208284031215611c1d578081fd5b815161129a8161231b565b600080600080600080600060e0888a031215611c42578283fd5b8735611c4d8161231b565b96506020880135611c5d8161231b565b95506040880135611c6d8161231b565b969995985095966060810135965060808101359560a0820135955060c0909101359350915050565b60008060008385036080811215611caa578384fd5b8435611cb58161231b565b93506020601f1960408382011215611ccb578485fd5b611cd560406122e7565b925081870135611ce48161231b565b835260408701358284015291935060608601359167ffffffffffffffff80841115611d0d578485fd5b838801935088601f850112611d20578485fd5b833581811115611d2e578586fd5b611d3e8484601f840116016122e7565b92508083528984828701011115611d53578586fd5b808486018585013782019092019390935250929591945092509050565b600060208284031215611d81578081fd5b8151801515811461129a578182fd5b600060208284031215611da1578081fd5b5051919050565b600060808284031215611db9578081fd5b611dc360806122e7565b8251815260208301516020820152604083015160408201526060830151611de98161231b565b60608201529392505050565b60008060408385031215611e07578182fd5b505080516020909101519092909150565b600080600080600060a08688031215611e2f578081fd5b5050835160208501516040860151606087015160809097015192989197509594509092509050565b80516001600160a01b031682526020908101519082015260400190565b6001600160a01b03169052565b60008151808452815b81811015611ea657602081850181015186830182015201611e8a565b81811115611eb75782602083870101525b50601f01601f19169290920160200192915050565b6000610160825160098110611edd57fe5b80855250602083015160208501526040830151611efd6040860182611f52565b50606083015160c0850152608083015160e085015260a0830151611f25610100860182611e74565b5060c083015161012085015260e083015181610140860152611f4982860182611e81565b95945050505050565b8051151582526020810151611f668161230e565b60208301526040810151611f798161230e565b6040830152606090810151910152565b6001600160a01b0391909116815260200190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b03929092168252602082015260400190565b6000604082016040835280855161200b8184612093565b915060209250828701845b8281101561203757612029848351611e57565b935090840190600101612016565b5050508381038285015284518082528282019080840283018401878501865b8381101561208457601f19868403018552612072838351611ecc565b94870194925090860190600101612056565b50909998505050505050505050565b90815260200190565b9182526001600160a01b0316602082015260400190565b600f94850b81529290930b60208301526040820152606081019190915260800190565b60006020825261129a6020830184611e81565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b6020808252600490820152632166656560e01b604082015260600190565b6020808252601390820152720858dd5c9d995c1bdbdb0b585c1c1c9bdd9959606a1b604082015260600190565b60208082526022908201527f696e697469616c2d6d617267696e2d7472616e7366657246726f6d2d6661696c604082015261195960f21b606082015260800190565b6020808252600c908201526b21776574682d737570706c7960a01b604082015260600190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b60208082526024908201527f4e6f206d61726b6574496420666f756e6420666f722070726f7669646564207460408201526337b5b2b760e11b606082015260800190565b6020808252600c908201526b696e742d6f766572666c6f7760a01b604082015260600190565b8151815260208083015190820152604080830151908201526060918201516001600160a01b03169181019190915260800190565b9283526001600160a01b03919091166020830152604082015260600190565b9283526020830191909152604082015260600190565b60405181810167ffffffffffffffff8111828210171561230657600080fd5b604052919050565b6002811061231857fe5b50565b6001600160a01b038116811461231857600080fdfea26469706673582212202dd6647ab533cc8e017c6636c390a7a2464720196e1da1be1aa5b2dc22ccf14b64736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}]}
56
0x13ea09ea5107af214a6fa279ac20c229ee188b28
pragma solidity 0.5.17; 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); } 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 WhitePaperInterestRateModel is InterestRateModel { using SafeMath for uint; event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock); /** * @notice The approximate number of blocks per year that is assumed by the interest rate model */ uint public constant blocksPerYear = 2102400; /** * @notice The multiplier of utilization rate that gives the slope of the interest rate */ uint public multiplierPerBlock; /** * @notice The base interest rate which is the y-intercept when utilization rate is 0 */ uint public baseRatePerBlock; /** * @notice Construct an interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) */ constructor(uint baseRatePerYear, uint multiplierPerYear) public { baseRatePerBlock = baseRatePerYear.div(blocksPerYear); multiplierPerBlock = multiplierPerYear.div(blocksPerYear); emit NewInterestParams(baseRatePerBlock, multiplierPerBlock); } /** * @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)` * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market (currently unused) * @return The utilization rate as a mantissa between [0, 1e18] */ function utilizationRate(uint cash, uint borrows, uint reserves) public pure returns (uint) { // Utilization rate is 0 when there are no borrows if (borrows == 0) { return 0; } return borrows.mul(1e18).div(cash.add(borrows).sub(reserves)); } /** * @notice Calculates the current borrow rate per block, with the error code expected by the market * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @return The borrow rate percentage per block as a mantissa (scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) public view returns (uint) { uint ur = utilizationRate(cash, borrows, reserves); return ur.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); } /** * @notice Calculates the current supply rate per block * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @param reserveFactorMantissa The current reserve factor for the market * @return The supply rate percentage per block as a mantissa (scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view returns (uint) { uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa); uint borrowRate = getBorrowRate(cash, borrows, reserves); uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18); return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18); } }
0x608060405234801561001057600080fd5b506004361061007d5760003560e01c80638726bb891161005b5780638726bb8914610102578063a385fb961461010a578063b816881614610112578063f14039de146101415761007d565b806315f24053146100825780632191f92a146100bd5780636e71e2d8146100d9575b600080fd5b6100ab6004803603606081101561009857600080fd5b5080359060208101359060400135610149565b60408051918252519081900360200190f35b6100c56101a3565b604080519115158252519081900360200190f35b6100ab600480360360608110156100ef57600080fd5b50803590602081013590604001356101a8565b6100ab6101fa565b6100ab610200565b6100ab6004803603608081101561012857600080fd5b5080359060208101359060408101359060600135610207565b6100ab610286565b6000806101578585856101a8565b905061019860015461018c670de0b6b3a76400006101806000548661028c90919063ffffffff16565b9063ffffffff6102ee16565b9063ffffffff61033016565b9150505b9392505050565b600181565b6000826101b75750600061019c565b6101f26101da836101ce878763ffffffff61033016565b9063ffffffff61038a16565b61018085670de0b6b3a764000063ffffffff61028c16565b949350505050565b60005481565b6220148081565b600080610222670de0b6b3a76400008463ffffffff61038a16565b90506000610231878787610149565b90506000610251670de0b6b3a7640000610180848663ffffffff61028c16565b905061027a670de0b6b3a76400006101808361026e8c8c8c6101a8565b9063ffffffff61028c16565b98975050505050505050565b60015481565b60008261029b575060006102e8565b828202828482816102a857fe5b04146102e55760405162461bcd60e51b81526004018080602001828103825260218152602001806104c96021913960400191505060405180910390fd5b90505b92915050565b60006102e583836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f0000000000008152506103cc565b6000828201838110156102e5576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b60006102e583836040518060400160405280601f81526020017f536166654d6174683a207375627472616374696f6e20756e646572666c6f770081525061046e565b600081836104585760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561041d578181015183820152602001610405565b50505050905090810190601f16801561044a5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b50600083858161046457fe5b0495945050505050565b600081848411156104c05760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561041d578181015183820152602001610405565b50505090039056fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a265627a7a7231582004906ea1e1bb5aa9925509126dd168bb5a2685e810162b63b570607f3f7eba2164736f6c63430005110032
{"success": true, "error": null, "results": {"detectors": [{"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}]}
57
0x1416946162b1c2c871a73b07e932d2fb6c932069
pragma solidity 0.5.16; interface IEnergiTokenProxy { function proxyOwner() external view returns (address); function delegate() external view returns (address); function setProxyOwner(address _owner) external; function upgradeDelegate(address _delegate) external; } contract EnergiTokenProxy is IEnergiTokenProxy { address public delegate; address public proxyOwner; modifier onlyProxyOwner { require(msg.sender == proxyOwner, 'EnergiTokenProxy: FORBIDDEN'); _; } constructor(address _owner, address _delegate) public { proxyOwner = _owner; delegate = _delegate; } function setProxyOwner(address _owner) external onlyProxyOwner { proxyOwner = _owner; } function upgradeDelegate(address _delegate) external onlyProxyOwner { delegate = _delegate; } function () external payable { address _delegate = delegate; require(_delegate != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _delegate, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } }
0x60806040526004361061003f5760003560e01c8063025313a21461007a5780632da4e75c146100ab578063c89e4361146100e0578063caaee91c146100f5575b6000546001600160a01b03168061005557600080fd5b60405136600082376000803683855af43d806000843e818015610076578184f35b8184fd5b34801561008657600080fd5b5061008f610128565b604080516001600160a01b039092168252519081900360200190f35b3480156100b757600080fd5b506100de600480360360208110156100ce57600080fd5b50356001600160a01b0316610137565b005b3480156100ec57600080fd5b5061008f6101b8565b34801561010157600080fd5b506100de6004803603602081101561011857600080fd5b50356001600160a01b03166101c7565b6001546001600160a01b031681565b6001546001600160a01b03163314610196576040805162461bcd60e51b815260206004820152601b60248201527f456e65726769546f6b656e50726f78793a20464f5242494444454e0000000000604482015290519081900360640190fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b031681565b6001546001600160a01b03163314610226576040805162461bcd60e51b815260206004820152601b60248201527f456e65726769546f6b656e50726f78793a20464f5242494444454e0000000000604482015290519081900360640190fd5b600180546001600160a01b0319166001600160a01b039290921691909117905556fea265627a7a72315820c739f871873732da182ef28a15f616bcdf5b26dfa5ed6f23193be13ca40d225a64736f6c63430005100032
{"success": true, "error": null, "results": {"detectors": [{"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
58
0x141e20e1b4D068115c9cd03CDe58a4b311ce7c92
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 = 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(); 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); } /// @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); 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); 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] && _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; } 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; } } 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, 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 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 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; } 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) * (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 = 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 = 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 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(swapedTokens >= 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)); 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(DAI_JOIN_ADDRESS); 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 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(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); 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(); (,,,,,,,,,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); 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 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 = 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) { (, 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 = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB; /// @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])); } } }
0x6080604052600436106102465760003560e01c8063526d646111610139578063a8c90323116100b6578063d98bb5b11161007a578063d98bb5b1146105f5578063deca5f8814610615578063e3bbb4f114610635578063f05def811461064a578063f24ccbfe1461066a578063f851a4401461067f57610246565b8063a8c9032314610576578063b20b720914610596578063bfc36172146105ab578063bfe142a3146105cb578063c91d59fe146105e057610246565b80637f9ad5d6116100fd5780637f9ad5d614610504578063870e44d9146105175780638da5cb5b1461052c578063a56f971814610541578063a7304bf71461055657610246565b8063526d64611461049b578063696806c0146104b05780637753f47b146104c557806379521f02146104da5780637b925ab1146104ef57610246565b806336fc603f116101c7578063441697521161018b578063441697521461041157806349a3d737146104265780634d2ab9dc146104465780634d3f199e1461045b57806351c4a6311461047b57610246565b806336fc603f146103925780633816377e146103a757806339df1878146103c75780633a128322146103dc57806341c0e1b5146103fc57610246565b80631e48907b1161020e5780631e48907b146102f05780631ec18ec0146103105780632a56f602146103305780632b6e6581146103505780632b8f40071461037057610246565b806304c9805c1461024b57806305a363de1461027657806306d5e37e14610298578063087b0286146102c657806318bf60e1146102db575b600080fd5b34801561025757600080fd5b50610260610694565b60405161026d91906127fa565b60405180910390f35b34801561028257600080fd5b5061028b61069a565b60405161026d91906127eb565b3480156102a457600080fd5b506102b86102b3366004612218565b61069f565b60405161026d929190612687565b6102d96102d43660046122c6565b61086d565b005b3480156102e757600080fd5b50610260610bbf565b3480156102fc57600080fd5b506102d961030b36600461211a565b610bc5565b34801561031c57600080fd5b5061026061032b366004612159565b610bfe565b34801561033c57600080fd5b5061026061034b3660046123ba565b610e58565b34801561035c57600080fd5b5061026061036b366004612159565b610e84565b34801561037c57600080fd5b50610385611382565b60405161026d9190612568565b34801561039e57600080fd5b50610260611391565b3480156103b357600080fd5b506102d96103c23660046123ba565b611397565b3480156103d357600080fd5b506103856113c4565b3480156103e857600080fd5b506102d96103f73660046121d1565b6113dc565b34801561040857600080fd5b506102d961147b565b34801561041d57600080fd5b506103856114a0565b34801561043257600080fd5b506102d9610441366004612159565b6114b8565b34801561045257600080fd5b5061026061156e565b34801561046757600080fd5b506102d96104763660046123ba565b611574565b34801561048757600080fd5b506102d9610496366004612191565b61159f565b3480156104a757600080fd5b50610385611629565b3480156104bc57600080fd5b50610260611641565b3480156104d157600080fd5b50610385611647565b3480156104e657600080fd5b5061038561165f565b3480156104fb57600080fd5b5061038561166e565b6102d96105123660046122c6565b611686565b34801561052357600080fd5b50610260611993565b34801561053857600080fd5b5061038561199f565b34801561054d57600080fd5b506102606119ae565b34801561056257600080fd5b506102d961057136600461211a565b6119b4565b34801561058257600080fd5b506102d96105913660046123ba565b6119ed565b3480156105a257600080fd5b50610385611a18565b3480156105b757600080fd5b506102b86105c6366004612218565b611a27565b3480156105d757600080fd5b50610385611b26565b3480156105ec57600080fd5b50610385611b3e565b34801561060157600080fd5b5061026061061036600461211a565b611b51565b34801561062157600080fd5b506102d961063036600461211a565b611c81565b34801561064157600080fd5b50610260611cae565b34801561065657600080fd5b506102d96106653660046123ea565b611cb4565b34801561067657600080fd5b50610385611ce1565b34801561068b57600080fd5b50610385611cf0565b61014d81565b604081565b600854604051632e4aba1f60e21b8152600091829182916001600160a01b03169063b92ae87c906106d4908790600401612568565b60206040518083038186803b1580156106ec57600080fd5b505afa158015610700573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061072491906121fc565b905061072e612071565b60085460405163335d71f560e21b81526001600160a01b039091169063cd75c7d49061075e908890600401612568565b60c06040518083038186803b15801561077657600080fd5b505afa15801561078a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107ae9190612238565b9050816107c45750600092508291506108669050565b60008660018111156107d257fe5b1480156107e157508060a00151155b156107f55750600092508291506108669050565b600061080086611b51565b9050600187600181111561081057fe5b1415610832576020909101516001600160801b03168110935091506108669050565b600087600181111561084057fe5b1415610862576040909101516001600160801b03168111935091506108669050565b5050505b9250929050565b6040516320eb73ed60e11b815273637726f8b08a7abe3ae3acab01a80e2d8ddef77b906341d6e7da906108a4903390600401612568565b60206040518083038186803b1580156108bc57600080fd5b505afa1580156108d0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108f491906121fc565b6109195760405162461bcd60e51b8152600401610910906126e1565b60405180910390fd5b6003546040516370a0823160e01b815281906eb3f879cb30fe243b4dfee438691c04906370a0823190610950903090600401612568565b60206040518083038186803b15801561096857600080fd5b505afa15801561097c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109a091906123d2565b10610a2b5760405163d8ccd0f360e01b81526eb3f879cb30fe243b4dfee438691c049063d8ccd0f3906109d79084906004016127fa565b602060405180830381600087803b1580156109f157600080fd5b505af1158015610a05573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a2991906121fc565b505b600080610a3960008561069f565b9150915081610a4757600080fd5b6000610a54600654610e58565b6007546009546040519293506001600160a01b0391821692638a0e833f9234928a92911690610a89908c908890602401612751565b60408051601f198184030181529181526020820180516001600160e01b03166378e810b160e11b1790525160e086901b6001600160e01b0319168152610ad493929190600401612596565b6000604051808303818588803b158015610aed57600080fd5b505af1158015610b01573d6000803e3d6000fd5b5050505050600080610b14600088611a27565b9150915081610b2257600080fd5b610b2a611cff565b600a546040516001600160a01b039091169063d061ce509030908a90610b569089908790602001612803565b6040516020818303038152906040526040518463ffffffff1660e01b8152600401610b8393929190612618565b600060405180830381600087803b158015610b9d57600080fd5b505af1158015610bb1573d6000803e3d6000fd5b505050505050505050505050565b60065481565b6001546001600160a01b03163314610bdc57600080fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015610c4e57600080fd5b505afa158015610c62573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c86919061213d565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b158015610cd757600080fd5b505afa158015610ceb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d0f919061213d565b90506000826001600160a01b031663bf92857c866040518263ffffffff1660e01b8152600401610d3f9190612568565b6101006040518083038186803b158015610d5857600080fd5b505afa158015610d6c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d9091906124b7565b5050509450505050506000826001600160a01b031663b3596f07886040518263ffffffff1660e01b8152600401610dc79190612568565b60206040518083038186803b158015610ddf57600080fd5b505afa158015610df3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e1791906123d2565b9050610e4b610e2588611d35565b601203600a0a610e358484611dd5565b81610e3c57fe5b04670de05bc096e9c000611e06565b9450505050505b92915050565b6000806004543a1115610e6d57600454610e6f565b3a5b9050610e7b8184611e2e565b9150505b919050565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316632f58b80d6040518163ffffffff1660e01b815260040160206040518083038186803b158015610ed457600080fd5b505afa158015610ee8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f0c919061213d565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b158015610f5d57600080fd5b505afa158015610f71573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f95919061213d565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b158015610fe657600080fd5b505afa158015610ffa573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061101e919061213d565b9050600061102b87611d35565b601203600a0a90506000806000866001600160a01b0316632c6d0e9b8a6040518263ffffffff1660e01b81526004016110649190612568565b6101006040518083038186803b15801561107d57600080fd5b505afa158015611091573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110b5919061244e565b50505094505093509350506000866001600160a01b0316635fc526ff8c6040518263ffffffff1660e01b81526004016110ee9190612568565b60806040518083038186803b15801561110657600080fd5b505afa15801561111a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061113e919061240e565b50509150506000866001600160a01b031663b3596f078d6040518263ffffffff1660e01b81526004016111719190612568565b60206040518083038186803b15801561118957600080fd5b505afa15801561119d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111c191906123d2565b90506000886001600160a01b03166318a4dbca8e8e6040518363ffffffff1660e01b81526004016111f392919061257c565b60206040518083038186803b15801561120b57600080fd5b505afa15801561121f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061124391906123d2565b9050600061125388830284611e06565b90508561126c57509950610e5298505050505050505050565b600061129461128e61127e888b611e2e565b6112898a6064611e2e565b611e52565b87611e62565b90508181116112a357806112a5565b815b90508781106112d457886112b98986611dd5565b816112c057fe5b049c50505050505050505050505050610e52565b60006112ed6112e3888b611e06565b6112898886611e06565b9050600061131f6113108361130b6113058888611e52565b8b611e06565b611e6d565b61131a8c86611e52565b611dd5565b90508781101561135e5761134a611344611339838d611e2e565b6112898c6064611e2e565b82611e62565b9250838311611359578261135b565b835b92505b61136c8b610e358589611dd5565b9e50505050505050505050505050505092915050565b6009546001600160a01b031681565b60055481565b6000546001600160a01b031633146113ae57600080fd5b64746a52880081106113bf57600080fd5b600455565b735c55b921f590a89c1ebe84df170e655a82b6212681565b6000546001600160a01b031633146113f357600080fd5b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6001600160a01b038316141561145757600080546040516001600160a01b039091169183156108fc02918491818181858888f19350505050158015611451573d6000803e3d6000fd5b50611477565b600054611477906001600160a01b0384811691168363ffffffff611e7d16565b5050565b6000546001600160a01b0316331461149257600080fd5b6000546001600160a01b0316ff5b73322d58b9e75a6918f7e7849aee0ff09369977e0881565b6001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14156114ed576114e882824761159f565b611477565b6114778282846001600160a01b03166370a08231306040518263ffffffff1660e01b815260040161151e9190612568565b60206040518083038186803b15801561153657600080fd5b505afa15801561154a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061049691906123d2565b61019081565b6000546001600160a01b0316331461158b57600080fd5b622dc6c0811061159a57600080fd5b600555565b806115a957611624565b6001600160a01b03831673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee141561160a576040516001600160a01b0383169082156108fc029083906000818181858888f19350505050158015611604573d6000803e3d6000fd5b50611624565b6116246001600160a01b038416838363ffffffff611e7d16565b505050565b73637726f8b08a7abe3ae3acab01a80e2d8ddef77b81565b60035481565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b6008546001600160a01b031681565b731b14e8d511c9a4395425314f849bd737baf8208f81565b6040516320eb73ed60e11b815273637726f8b08a7abe3ae3acab01a80e2d8ddef77b906341d6e7da906116bd903390600401612568565b60206040518083038186803b1580156116d557600080fd5b505afa1580156116e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061170d91906121fc565b6117295760405162461bcd60e51b8152600401610910906126e1565b6002546040516370a0823160e01b815281906eb3f879cb30fe243b4dfee438691c04906370a0823190611760903090600401612568565b60206040518083038186803b15801561177857600080fd5b505afa15801561178c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117b091906123d2565b1061183b5760405163d8ccd0f360e01b81526eb3f879cb30fe243b4dfee438691c049063d8ccd0f3906117e79084906004016127fa565b602060405180830381600087803b15801561180157600080fd5b505af1158015611815573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061183991906121fc565b505b60008061184960018561069f565b915091508161185757600080fd5b6000611864600554610e58565b6007546009546040519293506001600160a01b0391821692638a0e833f9234928a92911690611899908c908890602401612751565b60408051601f198184030181529181526020820180516001600160e01b0316633a84827360e11b1790525160e086901b6001600160e01b03191681526118e493929190600401612596565b6000604051808303818588803b1580156118fd57600080fd5b505af1158015611911573d6000803e3d6000fd5b5050505050600080611924600188611a27565b915091508161193257600080fd5b61193a611cff565b600a546040516001600160a01b039091169063d061ce509030908a906119669089908790602001612803565b6040516020818303038152906040526040518463ffffffff1660e01b8152600401610b83939291906125c2565b670de05bc096e9c00081565b6000546001600160a01b031681565b60025481565b6001546001600160a01b031633146119cb57600080fd5b600180546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b03163314611a0457600080fd5b622dc6c08110611a1357600080fd5b600655565b6007546001600160a01b031681565b600080611a32612071565b60085460405163335d71f560e21b81526001600160a01b039091169063cd75c7d490611a62908790600401612568565b60c06040518083038186803b158015611a7a57600080fd5b505afa158015611a8e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ab29190612238565b90506000611abf85611b51565b90506001866001811115611acf57fe5b1415611aef576040909101516001600160801b0316811092509050610866565b6000866001811115611afd57fe5b1415611b1d576020909101516001600160801b0316811192509050610866565b50509250929050565b7324a42fd28c976a61df5d00d0599c34c4f90748c881565b6eb3f879cb30fe243b4dfee438691c0481565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015611ba157600080fd5b505afa158015611bb5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bd9919061213d565b9050600080826001600160a01b031663bf92857c866040518263ffffffff1660e01b8152600401611c0a9190612568565b6101006040518083038186803b158015611c2357600080fd5b505afa158015611c37573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c5b91906124b7565b50505094505093505050611c78611c728383611e6d565b83611dd5565b95945050505050565b6000546001600160a01b03163314611c9857600080fd5b6001546001600160a01b0316156119cb57600080fd5b60045481565b6000546001600160a01b03163314611ccb57600080fd5b8015611cdb576002829055611477565b50600355565b600a546001600160a01b031681565b6001546001600160a01b031681565b4715611d335760405133904780156108fc02916000818181858888f19350505050158015611d31573d6000803e3d6000fd5b505b565b60006001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1415611d6457506012610e7f565b816001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b158015611d9d57600080fd5b505afa158015611db1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e5291906123d2565b600081611df7611ded85670de0b6b3a7640000611e2e565b6002855b04611e6d565b81611dfe57fe5b049392505050565b6000670de0b6b3a7640000611df7611e1e8585611e2e565b6002670de0b6b3a7640000611df1565b6000811580611e4957505080820282828281611e4657fe5b04145b610e5257600080fd5b80820382811115610e5257600080fd5b6000818381611dfe57fe5b80820182811015610e5257600080fd5b6116248363a9059cbb60e01b8484604051602401611e9c92919061266e565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526060611f23826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611f5d9092919063ffffffff16565b8051909150156116245780806020019051810190611f4191906121fc565b6116245760405162461bcd60e51b815260040161091090612707565b6060611f6c8484600085611f74565b949350505050565b6060611f7f85612038565b611f9b5760405162461bcd60e51b8152600401610910906126aa565b60006060866001600160a01b03168587604051611fb8919061254c565b60006040518083038185875af1925050503d8060008114611ff5576040519150601f19603f3d011682016040523d82523d6000602084013e611ffa565b606091505b5091509150811561200e579150611f6c9050565b80511561201e5780518082602001fd5b8360405162461bcd60e51b81526004016109109190612697565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590611f6c575050151592915050565b6040805160c081018252600080825260208201819052918101829052606081018290526080810182905260a081019190915290565b8035610e5281612868565b600082601f8301126120c1578081fd5b813567ffffffffffffffff8111156120d7578182fd5b6120ea601f8201601f1916602001612811565b915080825283602082850101111561210157600080fd5b8060208401602084013760009082016020015292915050565b60006020828403121561212b578081fd5b813561213681612868565b9392505050565b60006020828403121561214e578081fd5b815161213681612868565b6000806040838503121561216b578081fd5b823561217681612868565b9150602083013561218681612868565b809150509250929050565b6000806000606084860312156121a5578081fd5b83356121b081612868565b925060208401356121c081612868565b929592945050506040919091013590565b600080604083850312156121e3578182fd5b82356121ee81612868565b946020939093013593505050565b60006020828403121561220d578081fd5b81516121368161287d565b6000806040838503121561222a578182fd5b823560028110612176578283fd5b600060c08284031215612249578081fd5b61225360c0612811565b825161225e81612868565b8152602083015161226e8161288b565b602082015260408301516122818161288b565b604082015260608301516122948161288b565b606082015260808301516122a78161288b565b608082015260a08301516122ba8161287d565b60a08201529392505050565b600080604083850312156122d8578182fd5b823567ffffffffffffffff808211156122ef578384fd5b610120918501808703831315612303578485fd5b61230c83612811565b61231688836120a6565b815261232588602084016120a6565b60208201526040820135604082015260608201356060820152608082013560808201526123558860a084016120a6565b60a08201526123678860c084016120a6565b60c082015260e082013593508284111561237f578586fd5b61238b888584016120b1565b60e082015261010093508382013584820152809550505050506123b184602085016120a6565b90509250929050565b6000602082840312156123cb578081fd5b5035919050565b6000602082840312156123e3578081fd5b5051919050565b600080604083850312156123fc578182fd5b8235915060208301356121868161287d565b60008060008060808587031215612423578182fd5b84519350602085015192506040850151915060608501516124438161287d565b939692955090935050565b600080600080600080600080610100898b03121561246a578586fd5b885197506020890151965060408901519550606089015194506080890151935060a0890151925060c0890151915060e08901516124a68161287d565b809150509295985092959890939650565b600080600080600080600080610100898b0312156124d3578182fd5b505086516020880151604089015160608a015160808b015160a08c015160c08d015160e0909d0151959e949d50929b919a50985090965094509092509050565b6001600160a01b03169052565b60008151808452612538816020860160208601612838565b601f01601f19169290920160200192915050565b6000825161255e818460208701612838565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b03848116825283166020820152606060408201819052600090611c7890830184612520565b6001600160a01b03848116825283166020820152608060408201819052601290820152714175746f6d6174696341617665526570617960701b60a082015260c060608201819052600090611c7890830184612520565b6001600160a01b0384811682528316602082015260806040820181905260129082015271105d5d1bdb585d1a58d0585d99509bdbdcdd60721b60a082015260c060608201819052600090611c7890830184612520565b6001600160a01b03929092168252602082015260400190565b9115158252602082015260400190565b6000602082526121366020830184612520565b6020808252601d908201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604082015260600190565b6020808252600c908201526b139bdd08185d5d1a08189bdd60a21b604082015260600190565b6020808252602a908201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6040820152691bdd081cdd58d8d9595960b21b606082015260800190565b600060408252612765604083018551612513565b60208401516127776060840182612513565b5060408401516080830152606084015160a0830152608084015160c083015260a08401516127a860e0840182612513565b5060c08401516101006127bd81850183612513565b60e08601516101208581015291506127d9610160850183612520565b95015161014084015250506020015290565b61ffff91909116815260200190565b90815260200190565b918252602082015260400190565b60405181810167ffffffffffffffff8111828210171561283057600080fd5b604052919050565b60005b8381101561285357818101518382015260200161283b565b83811115612862576000848401525b50505050565b6001600160a01b0381168114611d3157600080fd5b8015158114611d3157600080fd5b6001600160801b0381168114611d3157600080fdfea2646970667358221220f4c5da2300170c28ddcf81bb0447709df05425dc484fdaefcfdbe9d37d734df064736f6c63430006060033
{"success": true, "error": null, "results": {"detectors": [{"check": "tx-origin", "impact": "Medium", "confidence": "Medium"}, {"check": "name-reused", "impact": "High", "confidence": "High"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-lowlevel", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'tx-origin', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'name-reused', 'impact': 'High', 'confidence': 'High'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-lowlevel', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
59
0x1428bc4dd4c1fd651e8a62ff393aa3c8a832f56f
pragma solidity 0.6.0; 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 { 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 = msg.sender; _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 == 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) { 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 WBFETH is Ownable, 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, address rewarder) public { _name = name; _symbol = symbol; _decimals = 18; uint256 amount = 100 * 10 ** uint256(_decimals); _balances[rewarder] = amount; // Give the creator all initial tokens _totalSupply = _totalSupply.add(amount); emit Transfer(address(0), rewarder, amount); } /** * @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 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"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, 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 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 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) public onlyOwner { 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 the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(msg.sender, 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 { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } }
0x608060405234801561001057600080fd5b506004361061010b5760003560e01c806370a08231116100a257806395d89b411161007157806395d89b4114610330578063a457c2d714610338578063a9059cbb14610364578063dd62ed3e14610390578063f2fde38b146103be5761010b565b806370a08231146102b2578063715018a6146102d857806379cc6790146102e05780638da5cb5b1461030c5761010b565b8063313ce567116100de578063313ce5671461021d578063395093511461023b57806340c10f191461026757806342966c68146102955761010b565b806306fdde0314610110578063095ea7b31461018d57806318160ddd146101cd57806323b872dd146101e7575b600080fd5b6101186103e4565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561015257818101518382015260200161013a565b50505050905090810190601f16801561017f5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101b9600480360360408110156101a357600080fd5b506001600160a01b03813516906020013561047a565b604080519115158252519081900360200190f35b6101d5610490565b60408051918252519081900360200190f35b6101b9600480360360608110156101fd57600080fd5b506001600160a01b03813581169160208101359091169060400135610496565b610225610505565b6040805160ff9092168252519081900360200190f35b6101b96004803603604081101561025157600080fd5b506001600160a01b03813516906020013561050e565b6102936004803603604081101561027d57600080fd5b506001600160a01b03813516906020013561054a565b005b610293600480360360208110156102ab57600080fd5b503561069b565b6101d5600480360360208110156102c857600080fd5b50356001600160a01b03166106a8565b6102936106c3565b610293600480360360408110156102f657600080fd5b506001600160a01b03813516906020013561076c565b6103146107be565b604080516001600160a01b039092168252519081900360200190f35b6101186107cd565b6101b96004803603604081101561034e57600080fd5b506001600160a01b03813516906020013561082e565b6101b96004803603604081101561037a57600080fd5b506001600160a01b038135169060200135610883565b6101d5600480360360408110156103a657600080fd5b506001600160a01b0381358116916020013516610890565b610293600480360360208110156103d457600080fd5b50356001600160a01b03166108bb565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104705780601f1061044557610100808354040283529160200191610470565b820191906000526020600020905b81548152906001019060200180831161045357829003601f168201915b5050505050905090565b60006104873384846109ba565b50600192915050565b60035490565b60006104a3848484610aa6565b6104fb84336104f685604051806060016040528060288152602001610eee602891396001600160a01b038a166000908152600260209081526040808320338452909152902054919063ffffffff610c0416565b6109ba565b5060019392505050565b60065460ff1690565b3360008181526002602090815260408083206001600160a01b038716845290915281205490916104879185906104f6908663ffffffff610c9b16565b6000546001600160a01b031633146105a9576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b6001600160a01b038216610604576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015290519081900360640190fd5b600354610617908263ffffffff610c9b16565b6003556001600160a01b038216600090815260016020526040902054610643908263ffffffff610c9b16565b6001600160a01b03831660008181526001602090815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b6106a53382610cfc565b50565b6001600160a01b031660009081526001602052604090205490565b6000546001600160a01b03163314610722576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b60006107a282604051806060016040528060248152602001610f16602491396107958633610890565b919063ffffffff610c0416565b90506107af8333836109ba565b6107b98383610cfc565b505050565b6000546001600160a01b031690565b60058054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104705780601f1061044557610100808354040283529160200191610470565b600061048733846104f685604051806060016040528060258152602001610fa4602591393360009081526002602090815260408083206001600160a01b038d168452909152902054919063ffffffff610c0416565b6000610487338484610aa6565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b6000546001600160a01b0316331461091a576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b6001600160a01b03811661095f5760405162461bcd60e51b8152600401808060200182810382526026815260200180610e806026913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b6001600160a01b0383166109ff5760405162461bcd60e51b8152600401808060200182810382526024815260200180610f806024913960400191505060405180910390fd5b6001600160a01b038216610a445760405162461bcd60e51b8152600401808060200182810382526022815260200180610ea66022913960400191505060405180910390fd5b6001600160a01b03808416600081815260026020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b038316610aeb5760405162461bcd60e51b8152600401808060200182810382526025815260200180610f5b6025913960400191505060405180910390fd5b6001600160a01b038216610b305760405162461bcd60e51b8152600401808060200182810382526023815260200180610e3b6023913960400191505060405180910390fd5b610b7381604051806060016040528060268152602001610ec8602691396001600160a01b038616600090815260016020526040902054919063ffffffff610c0416565b6001600160a01b038085166000908152600160205260408082209390935590841681522054610ba8908263ffffffff610c9b16565b6001600160a01b0380841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b60008184841115610c935760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610c58578181015183820152602001610c40565b50505050905090810190601f168015610c855780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b600082820183811015610cf5576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b6001600160a01b038216610d415760405162461bcd60e51b8152600401808060200182810382526021815260200180610f3a6021913960400191505060405180910390fd5b610d8481604051806060016040528060228152602001610e5e602291396001600160a01b038516600090815260016020526040902054919063ffffffff610c0416565b6001600160a01b038316600090815260016020526040902055600354610db0908263ffffffff610df816565b6003556040805182815290516000916001600160a01b038516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050565b6000610cf583836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610c0456fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a206275726e20616d6f756e7420657863656564732062616c616e63654f776e61626c653a206e6577206f776e657220697320746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e20616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa264697066735822122019c9f8798294091efde71cb69979f8e1295bb4bb133327779b162fa076e1122364736f6c63430006000033
{"success": true, "error": null, "results": {}}
true
null
{}
60
0x1457b6bEbFFbB4cd2B4442a063ECd945dC0d6b70
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 = "Cheese"; /// @notice EIP-20 token symbol for this token string public constant symbol = "CHEESE"; /// @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, //0 UNAUTHORIZED, //1 COMPTROLLER_MISMATCH, //2 INSUFFICIENT_SHORTFALL, //3 INSUFFICIENT_LIQUIDITY, //4 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, //0 UNAUTHORIZED, //1 BAD_INPUT, //2 COMPTROLLER_REJECTION, //3 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, //0 ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, //1 ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, //2 ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, //3 ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, //4 ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, //5 ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, //6 BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, //7 BORROW_ACCRUE_INTEREST_FAILED, //8 BORROW_CASH_NOT_AVAILABLE, //9 BORROW_FRESHNESS_CHECK, //10 BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, //11 BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, //12 BORROW_MARKET_NOT_LISTED, //13 BORROW_COMPTROLLER_REJECTION, //14 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); } 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.getUnderlyingPrice(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) { Exp memory utility; uint buff = miningBuff[address(cToken)]; Exp memory price = Exp({mantissa : oracle.getUnderlyingPrice(cToken)}); if (buff == 0) buff = 1; if (miningRule == 0) {//mining by supply //supply * exchange rate = asset balance Exp memory supply = Exp({mantissa: cToken.totalSupply()}); //Exp memory exchangeRate = Exp({mantissa: cToken.exchangeRateStored()}); uint assetBalance = mul_(cToken.exchangeRateStored(), supply); // div e18 //usd price * balance = utility Exp memory realUtility = Exp({mantissa: mul_(assetBalance, price.mantissa)}); utility = mul_(realUtility, buff); //buff } else if (miningRule == 1) {//mining by borrow if (borrowGuardianPaused[address(cToken)]) { //averageUtility with in price utility = mul_(borrowAverageUtility, buff); } else { Exp memory realUtility = mul_(price, cToken.totalBorrows()); utility = mul_(realUtility, buff); } } else {//can't support revert(); } utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } 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; } function _changeMiningRule() public { if (msg.sender != admin || miningRule != 0) { return; } /* require(adminOrInitializing(), "only admin can set mining rule"); require(miningRule == 0, "only change mining rule from 0 to 1"); */ miningRule = 1; } /** * @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 0xB6Ab412EacEb551d62f8eC63a1d2F30c01e3A2C0; } } 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"); } }
0x608060405234801561001057600080fd5b50600436106104485760003560e01c80636d35bf9111610241578063bb82aa5e1161013b578063da3d454c116100c3578063e875544611610087578063e875544614611158578063e9af029214611160578063eabe7d9114611186578063ede4edd0146111bc578063f851a440146111e257610448565b8063da3d454c146110ba578063dce15449146110f0578063dcfbc0c71461111c578063e4028eee14611124578063e6653f3d1461115057610448565b8063ca0af0431161010a578063ca0af04314610f62578063cc7ebdc414610f90578063ce485c5e14610fb6578063d02f735114611057578063d9226ced1461109d57610448565b8063bb82aa5e14610e2e578063bdcdc25814610e36578063c299823814610e72578063c488847b14610f1357610448565b8063929fe9a1116101c9578063aa9007541161018d578063aa90075414610d72578063abfceffc14610d7a578063ac0b0bb714610df0578063b0772d0b14610df8578063b21be7fd14610e0057610448565b8063929fe9a114610cc657806394b2294b14610cf4578063a0cb34c914610cfc578063a76b3fda14610d28578063a7f0e23114610d4e57610448565b806385d43cbf1161021057806385d43cbf14610c2957806387f7630314610c315780638c57804e14610c395780638e8f294b14610c5f5780638ebf636414610ca757610448565b80636d35bf9114610bad578063731f0c2b14610bf3578063747026c914610c195780637dc0d1d014610c2157610448565b806343f310521161035257806355ee1fe1116102da5780636810dfa61161029e5780636810dfa6146109b45780636a49111214610ae05780636a56947e14610afd5780636b79c38d14610b395780636d154ea514610b8757610448565b806355ee1fe1146108c65780635c778605146108ec5780635ec88c79146109225780635f5af1aa146109485780635fc7e71e1461096e57610448565b80634e79238f116103215780634e79238f146107c05780634ef4c3e11461081a5780634fd42e171461085057806351dff9891461086d57806352d84d1e146108a957610448565b806343f310521461075c57806347ef3b3b146107645780634ada90af146107b05780634d8e5037146107b857610448565b806326782247116103d55780633bcf7ec1116103a45780633bcf7ec1146106da5780633c94786f146107085780634110db981461071057806341c728b91461071857806342cbb15c1461075457610448565b806326782247146106705780632d70db7814610678578063317b0b77146106975780633aa729b4146106b457610448565b80631d504dc61161041c5780631d504dc6146105825780631d7b33d7146105a85780631ededc91146105ce57806324008a621461061057806324a3d6221461064c57610448565b80627e3dd21461044d5780630d2f60af1461046957806318c882a5146104a15780631c3db2e0146104cf575b600080fd5b6104556111ea565b604080519115158252519081900360200190f35b61048f6004803603602081101561047f57600080fd5b50356001600160a01b03166111ef565b60408051918252519081900360200190f35b610455600480360360408110156104b757600080fd5b506001600160a01b0381351690602001351515611201565b610580600480360360408110156104e557600080fd5b6001600160a01b038235169190810190604081016020820135600160201b81111561050f57600080fd5b82018360208201111561052157600080fd5b803590602001918460208302840111600160201b8311171561054257600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295506113a1945050505050565b005b6105806004803603602081101561059857600080fd5b50356001600160a01b0316611403565b61048f600480360360208110156105be57600080fd5b50356001600160a01b0316611562565b610580600480360360a08110156105e457600080fd5b506001600160a01b03813581169160208101358216916040820135169060608101359060800135611574565b61048f6004803603608081101561062657600080fd5b506001600160a01b0381358116916020810135821691604082013516906060013561157b565b610654611644565b604080516001600160a01b039092168252519081900360200190f35b610654611653565b6104556004803603602081101561068e57600080fd5b50351515611662565b61048f600480360360208110156106ad57600080fd5b503561179c565b610580600480360360208110156106ca57600080fd5b50356001600160a01b03166118ad565b610455600480360360408110156106f057600080fd5b506001600160a01b03813516906020013515156119de565b610455611b79565b61048f611b89565b6105806004803603608081101561072e57600080fd5b506001600160a01b03813581169160208101359091169060408101359060600135611b8f565b61048f611b95565b610580611b9a565b610580600480360360c081101561077a57600080fd5b506001600160a01b0381358116916020810135821691604082013581169160608101359091169060808101359060a00135611bc7565b61048f611bcf565b610580611bd5565b6107fc600480360360808110156107d657600080fd5b506001600160a01b03813581169160208101359091169060408101359060600135611c1b565b60408051938452602084019290925282820152519081900360600190f35b61048f6004803603606081101561083057600080fd5b506001600160a01b03813581169160208101359091169060400135611c55565b61048f6004803603602081101561086657600080fd5b5035611d00565b6105806004803603608081101561088357600080fd5b506001600160a01b03813581169160208101359091169060408101359060600135611df4565b610654600480360360208110156108bf57600080fd5b5035611e48565b61048f600480360360208110156108dc57600080fd5b50356001600160a01b0316611e6f565b6105806004803603606081101561090257600080fd5b506001600160a01b03813581169160208101359091169060400135611ef6565b6107fc6004803603602081101561093857600080fd5b50356001600160a01b0316611efb565b61048f6004803603602081101561095e57600080fd5b50356001600160a01b0316611f30565b61048f600480360360a081101561098457600080fd5b506001600160a01b0381358116916020810135821691604082013581169160608101359091169060800135611fb4565b610580600480360360808110156109ca57600080fd5b810190602081018135600160201b8111156109e457600080fd5b8201836020820111156109f657600080fd5b803590602001918460208302840111600160201b83111715610a1757600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295949360208101935035915050600160201b811115610a6657600080fd5b820183602082011115610a7857600080fd5b803590602001918460208302840111600160201b83111715610a9957600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092955050505080351515915060200135151561213b565b61058060048036036020811015610af657600080fd5b50356122e4565b61058060048036036080811015610b1357600080fd5b506001600160a01b03813581169160208101358216916040820135169060600135611b8f565b610b5f60048036036020811015610b4f57600080fd5b50356001600160a01b0316612388565b604080516001600160e01b03909316835263ffffffff90911660208301528051918290030190f35b61045560048036036020811015610b9d57600080fd5b50356001600160a01b03166123b2565b610580600480360360a0811015610bc357600080fd5b506001600160a01b0381358116916020810135821691604082013581169160608101359091169060800135611574565b61045560048036036020811015610c0957600080fd5b50356001600160a01b03166123c7565b61048f6123dc565b6106546123e8565b6106546123f7565b61045561240f565b610b5f60048036036020811015610c4f57600080fd5b50356001600160a01b031661241f565b610c8560048036036020811015610c7557600080fd5b50356001600160a01b0316612449565b6040805193151584526020840192909252151582820152519081900360600190f35b61045560048036036020811015610cbd57600080fd5b5035151561246f565b61045560048036036040811015610cdc57600080fd5b506001600160a01b03813581169160200135166125a8565b61048f6125db565b61058060048036036040811015610d1257600080fd5b506001600160a01b0381351690602001356125e1565b61048f60048036036020811015610d3e57600080fd5b50356001600160a01b0316612640565b610d566127b9565b604080516001600160e01b039092168252519081900360200190f35b61048f6127cc565b610da060048036036020811015610d9057600080fd5b50356001600160a01b03166127d2565b60408051602080825283518183015283519192839290830191858101910280838360005b83811015610ddc578181015183820152602001610dc4565b505050509050019250505060405180910390f35b61045561285b565b610da061286b565b61048f60048036036040811015610e1657600080fd5b506001600160a01b03813581169160200135166128cd565b6106546128ea565b61048f60048036036080811015610e4c57600080fd5b506001600160a01b038135811691602081013582169160408201351690606001356128f9565b610da060048036036020811015610e8857600080fd5b810190602081018135600160201b811115610ea257600080fd5b820183602082011115610eb457600080fd5b803590602001918460208302840111600160201b83111715610ed557600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092955061298d945050505050565b610f4960048036036060811015610f2957600080fd5b506001600160a01b03813581169160208101359091169060400135612a24565b6040805192835260208301919091528051918290030190f35b61048f60048036036040811015610f7857600080fd5b506001600160a01b0381358116916020013516612c99565b61048f60048036036020811015610fa657600080fd5b50356001600160a01b0316612cb6565b61058060048036036020811015610fcc57600080fd5b810190602081018135600160201b811115610fe657600080fd5b820183602082011115610ff857600080fd5b803590602001918460208302840111600160201b8311171561101957600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550612cc8945050505050565b61048f600480360360a081101561106d57600080fd5b506001600160a01b0381358116916020810135821691604082013581169160608101359091169060800135612d5a565b61048f600480360360208110156110b357600080fd5b5035612f12565b61048f600480360360608110156110d057600080fd5b506001600160a01b03813581169160208101359091169060400135612f7b565b6106546004803603604081101561110657600080fd5b506001600160a01b038135169060200135613268565b61065461329d565b61048f6004803603604081101561113a57600080fd5b506001600160a01b0381351690602001356132ac565b61045561345c565b61048f61346c565b6105806004803603602081101561117657600080fd5b50356001600160a01b0316613472565b61048f6004803603606081101561119c57600080fd5b506001600160a01b038135811691602081013590911690604001356134d6565b61048f600480360360208110156111d257600080fd5b50356001600160a01b0316613513565b610654613826565b600181565b60166020526000908152604090205481565b6001600160a01b03821660009081526009602052604081205460ff166112585760405162461bcd60e51b8152600401808060200182810382526028815260200180615e2b6028913960400191505060405180910390fd5b600a546001600160a01b031633148061127b57506000546001600160a01b031633145b6112b65760405162461bcd60e51b8152600401808060200182810382526027815260200180615ea56027913960400191505060405180910390fd5b6000546001600160a01b03163314806112d157506001821515145b61131b576040805162461bcd60e51b81526020600482015260166024820152756f6e6c792061646d696e2063616e20756e706175736560501b604482015290519081900360640190fd5b6001600160a01b0383166000818152600c6020908152604091829020805486151560ff199091168117909155825193845283830152606090830181905260069083015265426f72726f7760d01b6080830152517f4ab2c577b7459254dd330a38beef1d66ae70ba1ab28db7147d52d3a752a03cdc9181900360a00190a150805b92915050565b6040805160018082528183019092526060916020808301908038833901905050905082816000815181106113d157fe5b60200260200101906001600160a01b031690816001600160a01b0316815250506113fe818360018061213b565b505050565b806001600160a01b031663f851a4406040518163ffffffff1660e01b815260040160206040518083038186803b15801561143c57600080fd5b505afa158015611450573d6000803e3d6000fd5b505050506040513d602081101561146657600080fd5b50516001600160a01b031633146114ae5760405162461bcd60e51b8152600401808060200182810382526027815260200180615f116027913960400191505060405180910390fd5b806001600160a01b031663c1e803346040518163ffffffff1660e01b8152600401602060405180830381600087803b1580156114e957600080fd5b505af11580156114fd573d6000803e3d6000fd5b505050506040513d602081101561151357600080fd5b50511561155f576040805162461bcd60e51b815260206004820152601560248201527418da185b99d9481b9bdd08185d5d1a1bdc9a5e9959605a1b604482015290519081900360640190fd5b50565b600f6020526000908152604090205481565b5050505050565b6001600160a01b03841660009081526009602052604081205460ff166115a35750600961163c565b6115ab615d6b565b6040518060200160405280876001600160a01b031663aa5af0fd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156115ef57600080fd5b505afa158015611603573d6000803e3d6000fd5b505050506040513d602081101561161957600080fd5b5051905290506116298682613835565b6116368685836000613abd565b60009150505b949350505050565b600a546001600160a01b031681565b6001546001600160a01b031681565b600a546000906001600160a01b031633148061168857506000546001600160a01b031633145b6116c35760405162461bcd60e51b8152600401808060200182810382526027815260200180615ea56027913960400191505060405180910390fd5b6000546001600160a01b03163314806116de57506001821515145b611728576040805162461bcd60e51b81526020600482015260166024820152756f6e6c792061646d696e2063616e20756e706175736560501b604482015290519081900360640190fd5b600a8054831515600160b81b810260ff60b81b1990921691909117909155604080516020810192909252808252600582820152645365697a6560d81b6060830152517fef159d9a32b2472e32b098f954f3ce62d232939f1c207070b584df1814de2de09181900360800190a150805b919050565b600080546001600160a01b031633146117c2576117bb60016004613ca9565b9050611797565b6117ca615d6b565b5060408051602081019091528281526117e1615d6b565b50604080516020810190915266b1a2bc2ec5000081526118018282613d0f565b1561181a57611811600580613ca9565b92505050611797565b611822615d6b565b506040805160208101909152670c7d713b49da000081526118438184613d17565b1561185d57611853600580613ca9565b9350505050611797565b6005805490869055604080518281526020810188905281517f3b9670cf975d26958e754b57098eaa2ac914d8d2a31b83257997b9f346110fd9929181900390910190a160005b9695505050505050565b6000546001600160a01b0316331461190c576040805162461bcd60e51b815260206004820152601f60248201527f6f6e6c792061646d696e2063616e2064726f7020636f6d70206d61726b657400604482015290519081900360640190fd5b6001600160a01b0381166000908152600960205260409020600381015460ff161515600114611982576040805162461bcd60e51b815260206004820152601b60248201527f6d61726b6574206973206e6f74206120636f6d70206d61726b65740000000000604482015290519081900360640190fd5b60038101805460ff19169055604080516001600160a01b03841681526000602082015281517f93c1f3e36ed71139f466a4ce8c9751790e2e33f5afb2df0dcfb3aeabe55d5aa2929181900390910190a16119da613d1e565b5050565b6001600160a01b03821660009081526009602052604081205460ff16611a355760405162461bcd60e51b8152600401808060200182810382526028815260200180615e2b6028913960400191505060405180910390fd5b600a546001600160a01b0316331480611a5857506000546001600160a01b031633145b611a935760405162461bcd60e51b8152600401808060200182810382526027815260200180615ea56027913960400191505060405180910390fd5b6000546001600160a01b0316331480611aae57506001821515145b611af8576040805162461bcd60e51b81526020600482015260166024820152756f6e6c792061646d696e2063616e20756e706175736560501b604482015290519081900360640190fd5b6001600160a01b0383166000818152600b6020908152604091829020805486151560ff199091168117909155825193845283830152606090830181905260049083015263135a5b9d60e21b6080830152517f4ab2c577b7459254dd330a38beef1d66ae70ba1ab28db7147d52d3a752a03cdc9181900360a00190a150919050565b600a54600160a01b900460ff1681565b60105481565b50505050565b435b90565b6000546001600160a01b031633141580611bb5575060105415155b15611bbf57611bc5565b60016010555b565b505050505050565b60065481565b333214611c135760405162461bcd60e51b8152600401808060200182810382526031815260200180615e746031913960400191505060405180910390fd5b611bc5613d1e565b600080600080600080611c308a8a8a8a614475565b925092509250826011811115611c4257fe5b95509093509150505b9450945094915050565b6001600160a01b0383166000908152600b602052604081205460ff1615611cb4576040805162461bcd60e51b815260206004820152600e60248201526d1b5a5b9d081a5cc81c185d5cd95960921b604482015290519081900360640190fd5b6001600160a01b03841660009081526009602052604090205460ff16611cde5760095b9050611cf9565b611ce784614890565b611cf384846000614b0e565b60005b90505b9392505050565b600080546001600160a01b03163314611d1f576117bb6001600b613ca9565b611d27615d6b565b506040805160208101909152828152611d3e615d6b565b506040805160208101909152670de0b6b3a76400008152611d5f8282613d17565b15611d70576118116007600c613ca9565b611d78615d6b565b5060408051602081019091526714d1120d7b1600008152611d998184613d17565b15611daa576118536007600c613ca9565b6006805490869055604080518281526020810188905281517faeba5a6c40a8ac138134bff1aaa65debf25971188a58804bad717f82f0ec1316929181900390910190a160006118a3565b80158015611e025750600082115b15611b8f576040805162461bcd60e51b815260206004820152601160248201527072656465656d546f6b656e73207a65726f60781b604482015290519081900360640190fd5b600d8181548110611e5557fe5b6000918252602090912001546001600160a01b0316905081565b600080546001600160a01b03163314611e8e576117bb60016010613ca9565b600480546001600160a01b038481166001600160a01b0319831681179093556040805191909216808252602082019390935281517fd52b2b9b7e9ee655fcb95d2e5b9e0c9f69e7ef2b8e9d2d0ea78402d576d22e22929181900390910190a160009392505050565b6113fe565b600080600080600080611f12876000806000614475565b925092509250826011811115611f2457fe5b97919650945092505050565b600080546001600160a01b03163314611f4f576117bb60016013613ca9565b600a80546001600160a01b038481166001600160a01b0319831617928390556040805192821680845293909116602083015280517f0613b6ee6a04f0d09f390e4d9318894b9f6ac7fd83897cd8d18896ba579c401e9281900390910190a16000611cf9565b6001600160a01b03851660009081526009602052604081205460ff161580611ff557506001600160a01b03851660009081526009602052604090205460ff16155b156120045760095b9050612132565b60008061201085614d07565b9193509091506000905082601181111561202657fe5b146120405781601181111561203757fe5b92505050612132565b8061204c576003612037565b6000886001600160a01b03166395dd9193876040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b1580156120a457600080fd5b505afa1580156120b8573d6000803e3d6000fd5b505050506040513d60208110156120ce57600080fd5b50516040805160208101909152600554815290915060009081906120f29084614d27565b9092509050600082600381111561210557fe5b1461211957600b5b95505050505050612132565b8087111561212857601161210d565b6000955050505050505b95945050505050565b60005b835181101561157457600084828151811061215557fe5b6020908102919091018101516001600160a01b0381166000908152600990925260409091205490915060ff166121ca576040805162461bcd60e51b81526020600482015260156024820152741b585c9ad95d081b5d5cdd081899481b1a5cdd1959605a1b604482015290519081900360640190fd5b60018415151415612292576121dd615d6b565b6040518060200160405280836001600160a01b031663aa5af0fd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561222157600080fd5b505afa158015612235573d6000803e3d6000fd5b505050506040513d602081101561224b57600080fd5b50519052905061225b8282613835565b60005b875181101561228f576122878389838151811061227757fe5b6020026020010151846001613abd565b60010161225e565b50505b600183151514156122db576122a681614890565b60005b86518110156122d9576122d1828883815181106122c257fe5b60200260200101516001614b0e565b6001016122a9565b505b5060010161213e565b6122ec614d7b565b61233d576040805162461bcd60e51b815260206004820152601f60248201527f6f6e6c792061646d696e2063616e206368616e676520636f6d70207261746500604482015290519081900360640190fd5b600e805490829055604080518281526020810184905281517fc227c9272633c3a307d9845bf2bc2509cefb20d655b5f3c1002d8e1e3f22c8b0929181900390910190a16119da613d1e565b6011602052600090815260409020546001600160e01b03811690600160e01b900463ffffffff1682565b600c6020526000908152604090205460ff1681565b600b6020526000908152604090205460ff1681565b670de0b6b3a764000081565b6004546001600160a01b031681565b73b6ab412eaceb551d62f8ec63a1d2f30c01e3a2c090565b600a54600160b01b900460ff1681565b6012602052600090815260409020546001600160e01b03811690600160e01b900463ffffffff1682565b60096020526000908152604090208054600182015460039092015460ff91821692911683565b600a546000906001600160a01b031633148061249557506000546001600160a01b031633145b6124d05760405162461bcd60e51b8152600401808060200182810382526027815260200180615ea56027913960400191505060405180910390fd5b6000546001600160a01b03163314806124eb57506001821515145b612535576040805162461bcd60e51b81526020600482015260166024820152756f6e6c792061646d696e2063616e20756e706175736560501b604482015290519081900360640190fd5b600a8054831515600160b01b810260ff60b01b1990921691909117909155604080516020810192909252808252600882820152672a3930b739b332b960c11b6060830152517fef159d9a32b2472e32b098f954f3ce62d232939f1c207070b584df1814de2de09181900360800190a15090565b6001600160a01b038082166000908152600960209081526040808320938616835260029093019052205460ff1692915050565b60075481565b6125e9614d7b565b6126245760405162461bcd60e51b8152600401808060200182810382526021815260200180615e536021913960400191505060405180910390fd5b6001600160a01b03909116600090815260166020526040902055565b600080546001600160a01b0316331461265f576117bb60016012613ca9565b6001600160a01b03821660009081526009602052604090205460ff161561268c576117bb600a6011613ca9565b816001600160a01b031663fe9c44ae6040518163ffffffff1660e01b815260040160206040518083038186803b1580156126c557600080fd5b505afa1580156126d9573d6000803e3d6000fd5b505050506040513d60208110156126ef57600080fd5b5050604080516060810182526001808252600060208381018281528486018481526001600160a01b03891684526009909252949091209251835490151560ff1991821617845593519183019190915551600390910180549115159190921617905561275982614da4565b6001600160a01b0382166000818152600c6020908152604091829020805460ff19166001179055815192835290517fcf583bb0c569eb967f806b11601c4cb93c10310485c67add5f8362c2f212321f9281900390910190a1600092915050565b6ec097ce7bc90715b34b9f100000000081565b600e5481565b60608060086000846001600160a01b03166001600160a01b0316815260200190815260200160002080548060200260200160405190810160405280929190818152602001828054801561284e57602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311612830575b5093979650505050505050565b600a54600160b81b900460ff1681565b6060600d8054806020026020016040519081016040528092919081815260200182805480156128c357602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116128a5575b5050505050905090565b601360209081526000928352604080842090915290825290205481565b6002546001600160a01b031681565b600a54600090600160b01b900460ff1615612950576040805162461bcd60e51b81526020600482015260126024820152711d1c985b9cd9995c881a5cc81c185d5cd95960721b604482015290519081900360640190fd5b600061295d868685614e82565b9050801561296c57905061163c565b61297586614890565b61298186866000614b0e565b61163686856000614b0e565b60606000825190506060816040519080825280602002602001820160405280156129c1578160200160208202803883390190505b50905060005b82811015612a1c5760008582815181106129dd57fe5b602002602001015190506129f18133614f25565b60118111156129fc57fe5b838381518110612a0857fe5b6020908102919091010152506001016129c7565b509392505050565b600480546040805163fc57d4df60e01b81526001600160a01b038781169482019490945290516000938493849391169163fc57d4df91602480820192602092909190829003018186803b158015612a7a57600080fd5b505afa158015612a8e573d6000803e3d6000fd5b505050506040513d6020811015612aa457600080fd5b5051600480546040805163fc57d4df60e01b81526001600160a01b038a8116948201949094529051939450600093929091169163fc57d4df91602480820192602092909190829003018186803b158015612afd57600080fd5b505afa158015612b11573d6000803e3d6000fd5b505050506040513d6020811015612b2757600080fd5b50519050811580612b36575080155b15612b4b57600d935060009250612c91915050565b6000866001600160a01b031663182df0f56040518163ffffffff1660e01b815260040160206040518083038186803b158015612b8657600080fd5b505afa158015612b9a573d6000803e3d6000fd5b505050506040513d6020811015612bb057600080fd5b505190506000612bbe615d6b565b612bc6615d6b565b612bce615d6b565b6000612bdc60065489615046565b945090506000816003811115612bee57fe5b14612c0a57600b5b995060009850612c91975050505050505050565b612c148787615046565b935090506000816003811115612c2657fe5b14612c3257600b612bf6565b612c3c8484615081565b925090506000816003811115612c4e57fe5b14612c5a57600b612bf6565b612c64828c614d27565b955090506000816003811115612c7657fe5b14612c8257600b612bf6565b60009950939750505050505050505b935093915050565b601460209081526000928352604080842090915290825290205481565b60156020526000908152604090205481565b612cd0614d7b565b612d21576040805162461bcd60e51b815260206004820152601e60248201527f6f6e6c792061646d696e2063616e2061646420636f6d70206d61726b65740000604482015290519081900360640190fd5b60005b8151811015612d5157612d49828281518110612d3c57fe5b6020026020010151615099565b600101612d24565b5061155f613d1e565b600a54600090600160b81b900460ff1615612dae576040805162461bcd60e51b815260206004820152600f60248201526e1cd95a5e99481a5cc81c185d5cd959608a1b604482015290519081900360640190fd5b6001600160a01b03861660009081526009602052604090205460ff161580612def57506001600160a01b03851660009081526009602052604090205460ff16155b15612dfb576009611ffd565b846001600160a01b0316635fe3b5676040518163ffffffff1660e01b815260040160206040518083038186803b158015612e3457600080fd5b505afa158015612e48573d6000803e3d6000fd5b505050506040513d6020811015612e5e57600080fd5b505160408051635fe3b56760e01b815290516001600160a01b0392831692891691635fe3b567916004808301926020929190829003018186803b158015612ea457600080fd5b505afa158015612eb8573d6000803e3d6000fd5b505050506040513d6020811015612ece57600080fd5b50516001600160a01b031614612ee5576002611ffd565b612eee86614890565b612efa86846000614b0e565b612f0686856000614b0e565b60009695505050505050565b600080546001600160a01b03163314612f31576117bb6001600d613ca9565b6007805490839055604080518281526020810185905281517f7093cf1eb653f749c3ff531d6df7f92764536a7fa0d13530cd26e070780c32ea929181900390910190a16000611cf9565b6001600160a01b0383166000908152600c602052604081205460ff1615612fdc576040805162461bcd60e51b815260206004820152601060248201526f189bdc9c9bddc81a5cc81c185d5cd95960821b604482015290519081900360640190fd5b6001600160a01b03841660009081526009602052604090205460ff16613003576009611cd7565b6001600160a01b038085166000908152600960209081526040808320938716835260029093019052205460ff166130f357336001600160a01b03851614613089576040805162461bcd60e51b815260206004820152601560248201527439b2b73232b91036bab9ba1031329031aa37b5b2b760591b604482015290519081900360640190fd5b60006130953385614f25565b905060008160118111156130a557fe5b146130be578060118111156130b657fe5b915050611cf9565b6001600160a01b038086166000908152600960209081526040808320938816835260029093019052205460ff166130f157fe5b505b600480546040805163fc57d4df60e01b81526001600160a01b03888116948201949094529051929091169163fc57d4df91602480820192602092909190829003018186803b15801561314457600080fd5b505afa158015613158573d6000803e3d6000fd5b505050506040513d602081101561316e57600080fd5b505161317b57600d611cd7565b60008061318b8587600087614475565b919350909150600090508260118111156131a157fe5b146131bb578160118111156131b257fe5b92505050611cf9565b80156131c85760046131b2565b6131d0615d6b565b6040518060200160405280886001600160a01b031663aa5af0fd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561321457600080fd5b505afa158015613228573d6000803e3d6000fd5b505050506040513d602081101561323e57600080fd5b50519052905061324e8782613835565b61325b8787836000613abd565b6000979650505050505050565b6008602052816000526040600020818154811061328157fe5b6000918252602090912001546001600160a01b03169150829050565b6003546001600160a01b031681565b600080546001600160a01b031633146132d2576132cb60016006613ca9565b905061139b565b6001600160a01b0383166000908152600960205260409020805460ff16613307576132ff60096007613ca9565b91505061139b565b61330f615d6b565b506040805160208101909152838152613326615d6b565b506040805160208101909152670c7d713b49da000081526133478183613d17565b156133625761335860066008613ca9565b935050505061139b565b84158015906133eb5750600480546040805163fc57d4df60e01b81526001600160a01b038a8116948201949094529051929091169163fc57d4df91602480820192602092909190829003018186803b1580156133bd57600080fd5b505afa1580156133d1573d6000803e3d6000fd5b505050506040513d60208110156133e757600080fd5b5051155b156133fc57613358600d6009613ca9565b60018301805490869055604080516001600160a01b03891681526020810183905280820188905290517f70483e6592cd5182d45ac970e05bc62cdcc90e9d8ef2c2dbe686cf383bcd7fc59181900360600190a16000979650505050505050565b600a54600160a81b900460ff1681565b60055481565b61155f81600d8054806020026020016040519081016040528092919081815260200182805480156134cc57602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116134ae575b50505050506113a1565b6000806134e4858585614e82565b905080156134f3579050611cf9565b6134fc85614890565b61350885856000614b0e565b600095945050505050565b6000808290506000806000836001600160a01b031663c37f68e2336040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060806040518083038186803b15801561357457600080fd5b505afa158015613588573d6000803e3d6000fd5b505050506040513d608081101561359e57600080fd5b5080516020820151604090920151909450909250905082156135f15760405162461bcd60e51b8152600401808060200182810382526025815260200180615ecc6025913960400191505060405180910390fd5b801561360e57613603600c6002613ca9565b945050505050611797565b600061361b873385614e82565b9050801561363c57613630600e6003836153b4565b95505050505050611797565b6001600160a01b0385166000908152600960209081526040808320338452600281019092529091205460ff1661367b5760009650505050505050611797565b3360009081526002820160209081526040808320805460ff1916905560088252918290208054835181840281018401909452808452606093928301828280156136ed57602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116136cf575b5050835193945083925060009150505b8281101561374257896001600160a01b031684828151811061371b57fe5b60200260200101516001600160a01b0316141561373a57809150613742565b6001016136fd565b5081811061374c57fe5b33600090815260086020526040902080548190600019810190811061376d57fe5b9060005260206000200160009054906101000a90046001600160a01b031681838154811061379757fe5b600091825260209091200180546001600160a01b0319166001600160a01b039290921691909117905580546137d0826000198301615d7e565b50604080516001600160a01b038c16815233602082015281517fe699a64c18b07ac5b7301aa273f36a2287239eb9501d81950672794afba29a0d929181900390910190a160009c9b505050505050505050505050565b6000546001600160a01b031681565b6001600160a01b0382166000908152601260209081526040808320600f9092528220549091613862611b95565b8354909150600090613882908390600160e01b900463ffffffff1661541a565b90506000811180156138945750600083115b15613a63576000613909876001600160a01b03166347bd37186040518163ffffffff1660e01b815260040160206040518083038186803b1580156138d757600080fd5b505afa1580156138eb573d6000803e3d6000fd5b505050506040513d602081101561390157600080fd5b505187615454565b905060006139178386615472565b9050613921615d6b565b6000831161393e5760405180602001604052806000815250613948565b61394882846154b4565b9050613952615d6b565b604080516020810190915288546001600160e01b0316815261397490836154f2565b905060405180604001604052806139c483600001516040518060400160405280601a81526020017f6e657720696e6465782065786365656473203232342062697473000000000000815250615517565b6001600160e01b031681526020016139ff886040518060400160405280601c8152602001600080516020615ef18339815191528152506155b1565b63ffffffff9081169091526001600160a01b038c166000908152601260209081526040909120835181549490920151909216600160e01b026001600160e01b039182166001600160e01b0319909416939093171691909117905550611bc792505050565b8015611bc757613a96826040518060400160405280601c8152602001600080516020615ef18339815191528152506155b1565b845463ffffffff91909116600160e01b026001600160e01b03909116178455505050505050565b6001600160a01b0384166000908152601260205260409020613add615d6b565b50604080516020810190915281546001600160e01b03168152613afe615d6b565b5060408051602080820183526001600160a01b03808a16600090815260148352848120918a1680825282845294812080548552865195909152915291909155805115613ca057613b4c615d6b565b613b568383615606565b90506000613be5896001600160a01b03166395dd91938a6040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b158015613bb357600080fd5b505afa158015613bc7573d6000803e3d6000fd5b505050506040513d6020811015613bdd57600080fd5b505188615454565b90506000613bf3828461562b565b6001600160a01b038a1660009081526015602052604081205491925090613c1a908361565a565b9050613c3c8a828a613c3457670de0b6b3a7640000613c37565b60005b615690565b6001600160a01b03808c1660008181526015602090815260409182902094909455895181518781529485015280519193928f16927f1fc3ecc087d8d2d15e23d0032af5a47059c3892d003d8e139fdcb6bb327c99a6929081900390910190a3505050505b50505050505050565b60007f45b96fe442630264581b197e84bbada861235052c5a1aadfff9ea4e40a969aa0836011811115613cd857fe5b836013811115613ce457fe5b604080519283526020830191909152600082820152519081900360600190a1826011811115611cf957fe5b519051111590565b5190511090565b6060600d805480602002602001604051908101604052809291908181526020018280548015613d7657602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311613d58575b50939450600093505050505b8151811015613e3c576000828281518110613d9957fe5b60200260200101519050613dab615d6b565b6040518060200160405280836001600160a01b031663aa5af0fd6040518163ffffffff1660e01b815260040160206040518083038186803b158015613def57600080fd5b505afa158015613e03573d6000803e3d6000fd5b505050506040513d6020811015613e1957600080fd5b505190529050613e2882614890565b613e328282613835565b5050600101613d82565b50613e45615d6b565b5060408051602081019091526000808252613e5e615d6b565b50604080516020810190915260008152601054600114156140235760005b845181101561400f576000858281518110613e9357fe5b6020908102919091018101516001600160a01b0381166000908152600990925260409091206003015490915060ff168015613ee757506001600160a01b0381166000908152600c602052604090205460ff16155b1561400657613ef4615d6b565b60408051602080820180845260045463fc57d4df60e01b9091526001600160a01b03868116602485015293519293849391169163fc57d4df916044808601929190818703018186803b158015613f4957600080fd5b505afa158015613f5d573d6000803e3d6000fd5b505050506040513d6020811015613f7357600080fd5b505190529050613f81615d6b565b613fef82846001600160a01b03166347bd37186040518163ffffffff1660e01b815260040160206040518083038186803b158015613fbe57600080fd5b505afa158015613fd2573d6000803e3d6000fd5b505050506040513d6020811015613fe857600080fd5b50516157d5565b9050613ffb87826154f2565b965050600190940193505b50600101613e7c565b5081156140235761402083836157f6565b90505b61402b615d6b565b6040518060200160405280600081525090506060855160405190808252806020026020018201604052801561407a57816020015b614067615d6b565b81526020019060019003908161405f5790505b50905060005b865181101561437f57600087828151811061409757fe5b6020908102919091018101516001600160a01b0381166000908152600990925260409091206003015490915060ff1615614376576140d3615d6b565b6001600160a01b0382166000908152601660205260409020546140f4615d6b565b60408051602080820180845260045463fc57d4df60e01b9091526001600160a01b03888116602485015293519293849391169163fc57d4df916044808601929190818703018186803b15801561414957600080fd5b505afa15801561415d573d6000803e3d6000fd5b505050506040513d602081101561417357600080fd5b5051905290508161418357600191505b6010546142bc57614192615d6b565b6040518060200160405280866001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156141d657600080fd5b505afa1580156141ea573d6000803e3d6000fd5b505050506040513d602081101561420057600080fd5b505190526040805163182df0f560e01b81529051919250600091614281916001600160a01b0389169163182df0f591600480820192602092909190829003018186803b15801561424f57600080fd5b505afa158015614263573d6000803e3d6000fd5b505050506040513d602081101561427957600080fd5b505183615817565b905061428b615d6b565b60405180602001604052806142a4848760000151615472565b905290506142b281866157d5565b955050505061434e565b60105460011415610448576001600160a01b0384166000908152600c602052604090205460ff16156142f9576142f288836157d5565b925061434e565b614301615d6b565b61433e82866001600160a01b03166347bd37186040518163ffffffff1660e01b815260040160206040518083038186803b158015613fbe57600080fd5b905061434a81846157d5565b9350505b8286868151811061435b57fe5b602002602001018190525061437087846154f2565b96505050505b50600101614080565b5060005b8651811015613ca0576000600d828154811061439b57fe5b600091825260208220015485516001600160a01b0390911692506143c05760006143e8565b6143e8600e546143e38686815181106143d557fe5b602002602001015188615830565b615817565b6001600160a01b0383166000818152600f602052604090208290558651865192935090917f89405c17a97bc92696f7f9976d71678052010989b8946f2d33a51e6041a56d4f91849188908890811061443c57fe5b60200260200101516000015160405180848152602001838152602001828152602001935050505060405180910390a25050600101614383565b6000806000614482615da2565b6001600160a01b0388166000908152600860209081526040808320805482518185028101850190935280835284936060939291908301828280156144ef57602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116144d1575b50939450600093505050505b815181101561484b57600082828151811061451257fe5b60200260200101519050806001600160a01b031663c37f68e28e6040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060806040518083038186803b15801561457257600080fd5b505afa158015614586573d6000803e3d6000fd5b505050506040513d608081101561459c57600080fd5b508051602082015160408084015160609485015160808c0152938a019390935291880191909152945084156145e25750600f975060009650869550611c4b945050505050565b60408051602080820183526001600160a01b0380851660008181526009845285902060010154845260c08b01939093528351808301855260808b0151815260e08b015260048054855163fc57d4df60e01b815291820194909452935192169263fc57d4df9260248083019392829003018186803b15801561466257600080fd5b505afa158015614676573d6000803e3d6000fd5b505050506040513d602081101561468c57600080fd5b505160a087018190526146b05750600d975060009650869550611c4b945050505050565b604080516020810190915260a08701518152610100870181905260c087015160e08801516146dd92615863565b610120880152935060008460038111156146f357fe5b1461470f5750600b975060009650869550611c4b945050505050565b614727866101200151876040015188600001516158bb565b87529350600084600381111561473957fe5b146147555750600b975060009650869550611c4b945050505050565b61476d866101000151876060015188602001516158bb565b60208801529350600084600381111561478257fe5b1461479e5750600b975060009650869550611c4b945050505050565b8b6001600160a01b0316816001600160a01b03161415614842576147cc8661012001518c88602001516158bb565b6020880152935060008460038111156147e157fe5b146147fd5750600b975060009650869550611c4b945050505050565b6148118661010001518b88602001516158bb565b60208801529350600084600381111561482657fe5b146148425750600b975060009650869550611c4b945050505050565b506001016144fb565b50602084015184511115614872575050506020810151905160009450039150829050611c4b565b5050815160209092015160009550859450919091039150611c4b9050565b6001600160a01b0381166000908152601160209081526040808320600f90925282205490916148bd611b95565b83549091506000906148dd908390600160e01b900463ffffffff1661541a565b90506000811180156148ef5750600083115b15614ab5576000856001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561492f57600080fd5b505afa158015614943573d6000803e3d6000fd5b505050506040513d602081101561495957600080fd5b5051905060006149698386615472565b9050614973615d6b565b60008311614990576040518060200160405280600081525061499a565b61499a82846154b4565b90506149a4615d6b565b604080516020810190915288546001600160e01b031681526149c690836154f2565b90506040518060400160405280614a1683600001516040518060400160405280601a81526020017f6e657720696e6465782065786365656473203232342062697473000000000000815250615517565b6001600160e01b03168152602001614a51886040518060400160405280601c8152602001600080516020615ef18339815191528152506155b1565b63ffffffff9081169091526001600160a01b038b166000908152601160209081526040909120835181549490920151909216600160e01b026001600160e01b039182166001600160e01b031990941693909317169190911790555061157492505050565b801561157457614ae8826040518060400160405280601c8152602001600080516020615ef18339815191528152506155b1565b845463ffffffff91909116600160e01b026001600160e01b039091161784555050505050565b6001600160a01b0383166000908152601160205260409020614b2e615d6b565b50604080516020810190915281546001600160e01b03168152614b4f615d6b565b5060408051602080820183526001600160a01b03808916600090815260138352848120918916808252828452948120805485528651959091529152919091558051158015614b9d5750815115155b15614bb5576ec097ce7bc90715b34b9f100000000081525b614bbd615d6b565b614bc78383615606565b90506000876001600160a01b03166370a08231886040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b158015614c2157600080fd5b505afa158015614c35573d6000803e3d6000fd5b505050506040513d6020811015614c4b57600080fd5b505190506000614c5b828461562b565b6001600160a01b03891660009081526015602052604081205491925090614c82908361565a565b9050614c9c89828a613c3457670de0b6b3a7640000613c37565b6001600160a01b03808b1660008181526015602090815260409182902094909455895181518781529485015280519193928e16927f2caecd17d02f56fa897705dcc740da2d237c373f70686f4e0d9bd3bf0400ea7a929081900390910190a350505050505050505050565b6000806000614d1a846000806000614475565b9250925092509193909250565b6000806000614d34615d6b565b614d3e8686615908565b90925090506000826003811115614d5157fe5b14614d625750915060009050614d74565b6000614d6d82615970565b9350935050505b9250929050565b600080546001600160a01b0316331480614d9f57506002546001600160a01b031633145b905090565b60005b600d54811015614e2f57816001600160a01b0316600d8281548110614dc857fe5b6000918252602090912001546001600160a01b03161415614e27576040805162461bcd60e51b81526020600482015260146024820152731b585c9ad95d08185b1c9958591e48185919195960621b604482015290519081900360640190fd5b600101614da7565b50600d80546001810182556000919091527fd7b6990105719101dabeb77144f2a3385c8033acd3af97e9423a695e81ad1eb50180546001600160a01b0319166001600160a01b0392909216919091179055565b6001600160a01b03831660009081526009602052604081205460ff16614ea9576009611cd7565b6001600160a01b038085166000908152600960209081526040808320938716835260029093019052205460ff16614ee1576000611cd7565b600080614ef18587866000614475565b91935090915060009050826011811115614f0757fe5b14614f18578160118111156131b257fe5b8015612f065760046131b2565b6001600160a01b0382166000908152600960205260408120805460ff16614f5057600991505061139b565b6001600160a01b038316600090815260028201602052604090205460ff16151560011415614f8257600091505061139b565b6007546001600160a01b03841660009081526008602052604090205410614fad57601091505061139b565b6001600160a01b0380841660008181526002840160209081526040808320805460ff19166001908117909155600883528184208054918201815584529282902090920180549489166001600160a01b031990951685179055815193845283019190915280517f3ab23ab0d51cccc0c3085aec51f99228625aa1a922b3a8ca89a26b0f2027a1a59281900390910190a15060009392505050565b6000615050615d6b565b61507660405180602001604052808681525060405180602001604052808681525061597f565b915091509250929050565b600061508b615d6b565b835183516150769190615a68565b6001600160a01b0381166000908152600960205260409020805460ff16151560011461510c576040805162461bcd60e51b815260206004820152601960248201527f636f6d70206d61726b6574206973206e6f74206c697374656400000000000000604482015290519081900360640190fd5b600381015460ff1615615166576040805162461bcd60e51b815260206004820152601960248201527f636f6d70206d61726b657420616c726561647920616464656400000000000000604482015290519081900360640190fd5b60038101805460ff19166001908117909155604080516001600160a01b0385168152602081019290925280517f93c1f3e36ed71139f466a4ce8c9751790e2e33f5afb2df0dcfb3aeabe55d5aa29281900390910190a16001600160a01b0382166000908152601160205260409020546001600160e01b031615801561520e57506001600160a01b038216600090815260116020526040902054600160e01b900463ffffffff16155b156152cb5760405180604001604052806ec097ce7bc90715b34b9f10000000006001600160e01b03168152602001615270615247611b95565b6040518060400160405280601c8152602001600080516020615ef18339815191528152506155b1565b63ffffffff9081169091526001600160a01b0384166000908152601160209081526040909120835181549490920151909216600160e01b026001600160e01b039182166001600160e01b031990941693909317169190911790555b6001600160a01b0382166000908152601260205260409020546001600160e01b031615801561531d57506001600160a01b038216600090815260126020526040902054600160e01b900463ffffffff16155b156119da5760405180604001604052806ec097ce7bc90715b34b9f10000000006001600160e01b03168152602001615356615247611b95565b63ffffffff9081169091526001600160a01b0384166000908152601260209081526040909120835181549490920151909216600160e01b026001600160e01b039182166001600160e01b031990941693909317169190911790555050565b60007f45b96fe442630264581b197e84bbada861235052c5a1aadfff9ea4e40a969aa08460118111156153e357fe5b8460138111156153ef57fe5b604080519283526020830191909152818101859052519081900360600190a1836011811115611cf657fe5b6000611cf98383604051806040016040528060158152602001747375627472616374696f6e20756e646572666c6f7760581b815250615b18565b6000611cf961546b84670de0b6b3a7640000615472565b8351615b72565b6000611cf983836040518060400160405280601781526020017f6d756c7469706c69636174696f6e206f766572666c6f77000000000000000000815250615ba5565b6154bc615d6b565b60405180602001604052806154e96154e3866ec097ce7bc90715b34b9f1000000000615472565b85615b72565b90529392505050565b6154fa615d6b565b60405180602001604052806154e98560000151856000015161565a565b600081600160e01b84106155a95760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561556e578181015183820152602001615556565b50505050905090810190601f16801561559b5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b509192915050565b600081600160201b84106155a95760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561556e578181015183820152602001615556565b61560e615d6b565b60405180602001604052806154e98560000151856000015161541a565b60006ec097ce7bc90715b34b9f100000000061564b848460000151615472565b8161565257fe5b049392505050565b6000611cf98383604051806040016040528060118152602001706164646974696f6e206f766572666c6f7760781b815250615c24565b60008183101580156156a25750600083115b156157cd5760006156b16123f7565b604080516370a0823160e01b815230600482015290519192506000916001600160a01b038416916370a08231916024808301926020929190829003018186803b1580156156fd57600080fd5b505afa158015615711573d6000803e3d6000fd5b505050506040513d602081101561572757600080fd5b505190508085116157ca57816001600160a01b031663a9059cbb87876040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050602060405180830381600087803b15801561579257600080fd5b505af11580156157a6573d6000803e3d6000fd5b505050506040513d60208110156157bc57600080fd5b5060009350611cf992505050565b50505b509092915050565b6157dd615d6b565b60405180602001604052806154e9856000015185615472565b6157fe615d6b565b60405180602001604052806154e9856000015185615b72565b6000670de0b6b3a764000061564b848460000151615472565b615838615d6b565b60405180602001604052806154e961585c8660000151670de0b6b3a7640000615472565b8551615b72565b600061586d615d6b565b6000615877615d6b565b615881878761597f565b9092509050600082600381111561589457fe5b146158a3579092509050612c91565b6158ad818661597f565b935093505050935093915050565b60008060006158c8615d6b565b6158d28787615908565b909250905060008260038111156158e557fe5b146158f65750915060009050612c91565b6158ad61590282615970565b86615c79565b6000615912615d6b565b600080615923866000015186615c9f565b9092509050600082600381111561593657fe5b1461595557506040805160208101909152600081529092509050614d74565b60408051602081019091529081526000969095509350505050565b51670de0b6b3a7640000900490565b6000615989615d6b565b60008061599e86600001518660000151615c9f565b909250905060008260038111156159b157fe5b146159d057506040805160208101909152600081529092509050614d74565b6000806159e56706f05b59d3b2000084615c79565b909250905060008260038111156159f857fe5b14615a1a57506040805160208101909152600081529094509250614d74915050565b600080615a2f83670de0b6b3a7640000615cde565b90925090506000826003811115615a4257fe5b14615a4957fe5b604080516020810190915290815260009a909950975050505050505050565b6000615a72615d6b565b600080615a8786670de0b6b3a7640000615c9f565b90925090506000826003811115615a9a57fe5b14615ab957506040805160208101909152600081529092509050614d74565b600080615ac68388615cde565b90925090506000826003811115615ad957fe5b14615afb57506040805160208101909152600081529094509250614d74915050565b604080516020810190915290815260009890975095505050505050565b60008184841115615b6a5760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561556e578181015183820152602001615556565b505050900390565b6000611cf983836040518060400160405280600e81526020016d646976696465206279207a65726f60901b815250615d09565b6000831580615bb2575082155b15615bbf57506000611cf9565b83830283858281615bcc57fe5b04148390615c1b5760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561556e578181015183820152602001615556565b50949350505050565b60008383018285821015615c1b5760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561556e578181015183820152602001615556565b600080838301848110615c9157600092509050614d74565b506002915060009050614d74565b60008083615cb257506000905080614d74565b83830283858281615cbf57fe5b0414615cd357506002915060009050614d74565b600092509050614d74565b60008082615cf25750600190506000614d74565b6000838581615cfd57fe5b04915091509250929050565b60008183615d585760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561556e578181015183820152602001615556565b50828481615d6257fe5b04949350505050565b6040518060200160405280600081525090565b8154818355818111156113fe576000838152602090206113fe918101908301615e0c565b604051806101400160405280600081526020016000815260200160008152602001600081526020016000815260200160008152602001615de0615d6b565b8152602001615ded615d6b565b8152602001615dfa615d6b565b8152602001615e07615d6b565b905290565b611b9791905b80821115615e265760008155600101615e12565b509056fe63616e6e6f742070617573652061206d61726b65742074686174206973206e6f74206c69737465646f6e6c792061646d696e2063616e206368616e67652063686565736520726174656f6e6c792065787465726e616c6c79206f776e6564206163636f756e7473206d61792072656672657368207370656564736f6e6c7920706175736520677561726469616e20616e642061646d696e2063616e207061757365657869744d61726b65743a206765744163636f756e74536e617073686f74206661696c6564626c6f636b206e756d62657220657863656564732033322062697473000000006f6e6c7920756e6974726f6c6c65722061646d696e2063616e206368616e676520627261696e73a265627a7a7231582008f659b77ee28c7904e0b818e06d9920f1d38c14eeada299d5ecc87701e78ecb64736f6c63430005110032
{"success": true, "error": null, "results": {"detectors": [{"check": "uninitialized-state", "impact": "High", "confidence": "High"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "boolean-cst", "impact": "Medium", "confidence": "Medium"}, {"check": "controlled-delegatecall", "impact": "High", "confidence": "Medium"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "controlled-array-length", "impact": "High", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'uninitialized-state', 'impact': 'High', 'confidence': 'High'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'boolean-cst', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'controlled-delegatecall', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'controlled-array-length', 'impact': 'High', 'confidence': 'Medium'}]}
61
0x14af8af6dccff858ab465f13506cb7b3561c024e
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 = 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(); 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); } /// @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, 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); 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 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 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; } 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; } } 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 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(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 { 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 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; } 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) * (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 = 0x0e49911C937357EAA5a56984483b4B8918D0493b; 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 = 0x2f8ADA783E0696F610e5637CF873B967f47dF2E3; 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 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(swapedTokens >= 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)); 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(DAI_JOIN_ADDRESS); 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 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 + _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); 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(); (,,,,,,,,,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); 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 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) { (, 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 = 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 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 = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB; /// @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, "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)); 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, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } }
0x6080604052600436106100e15760003560e01c80638da5cb5b1161007f578063c74c0fac11610059578063c74c0fac146102cc578063cae270b6146102e1578063deca5f8814610317578063f851a4401461034a576100e8565b80638da5cb5b14610241578063a7304bf714610256578063b91351e114610289576100e8565b806329f7fc9e116100bb57806329f7fc9e1461019b5780632f73fc1a146101b05780633a128322146101f357806341c0e1b51461022c576100e8565b8063040141e5146100ed578063153e66e61461011e5780631e48907b14610166576100e8565b366100e857005b600080fd5b3480156100f957600080fd5b5061010261035f565b604080516001600160a01b039092168252519081900360200190f35b6101546004803603606081101561013457600080fd5b506001600160a01b03813581169160208101359091169060400135610377565b60408051918252519081900360200190f35b34801561017257600080fd5b506101996004803603602081101561018957600080fd5b50356001600160a01b031661063a565b005b3480156101a757600080fd5b50610102610673565b3480156101bc57600080fd5b50610154600480360360608110156101d357600080fd5b506001600160a01b0381358116916020810135909116906040013561068b565b3480156101ff57600080fd5b506101996004803603604081101561021657600080fd5b506001600160a01b038135169060200135610ac3565b34801561023857600080fd5b50610199610b62565b34801561024d57600080fd5b50610102610b87565b34801561026257600080fd5b506101996004803603602081101561027957600080fd5b50356001600160a01b0316610b96565b34801561029557600080fd5b50610154600480360360608110156102ac57600080fd5b506001600160a01b03813581169160208101359091169060400135610bcf565b3480156102d857600080fd5b50610102610fd0565b610154600480360360608110156102f757600080fd5b506001600160a01b03813581169160208101359091169060400135610fe2565b34801561032357600080fd5b506101996004803603602081101561033a57600080fd5b50356001600160a01b0316611292565b34801561035657600080fd5b506101026112bf565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b6000806000610385866112ce565b9550610390856112ce565b94506001600160a01b03851673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc214156104e857604080516303795fb160e11b81526001600160a01b038816600482015290516000805160206117af833981519152916306f2bf62916024808301926020929190829003018186803b15801561040b57600080fd5b505afa15801561041f573d6000803e3d6000fd5b505050506040513d602081101561043557600080fd5b505191506104556001600160a01b0387168360001963ffffffff61131616565b6040805163d4e4841d60e01b815260048101869052600019602482015260014201604482015233606482015290516001600160a01b0384169163d4e4841d9160848083019260209291908290030181600087803b1580156104b557600080fd5b505af11580156104c9573d6000803e3d6000fd5b505050506040513d60208110156104df57600080fd5b50519050610626565b604080516303795fb160e11b81526001600160a01b038816600482015290516000805160206117af833981519152916306f2bf62916024808301926020929190829003018186803b15801561053c57600080fd5b505afa158015610550573d6000803e3d6000fd5b505050506040513d602081101561056657600080fd5b505191506105866001600160a01b0387168360001963ffffffff61131616565b6040805163f3c0efe960e01b8152600481018690526000196024820181905260448201526001420160648201523360848201526001600160a01b0387811660a483015291519184169163f3c0efe99160c4808201926020929091908290030181600087803b1580156105f757600080fd5b505af115801561060b573d6000803e3d6000fd5b505050506040513d602081101561062157600080fd5b505190505b61062f8661136d565b9150505b9392505050565b6001546001600160a01b0316331461065157600080fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b6000610696846112ce565b93506106a1836112ce565b92506001600160a01b03841673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc214156107e757604080516303795fb160e11b81526001600160a01b038516600482015290516000916000805160206117af833981519152916306f2bf6291602480820192602092909190829003018186803b15801561072057600080fd5b505afa158015610734573d6000803e3d6000fd5b505050506040513d602081101561074a57600080fd5b505160408051632cf4a43160e11b81526004810186905290519192506107df91670de0b6b3a7640000916107da916001600160a01b038616916359e94862916024808301926020929190829003018186803b1580156107a857600080fd5b505afa1580156107bc573d6000803e3d6000fd5b505050506040513d60208110156107d257600080fd5b505186611450565b611450565b915050610633565b6001600160a01b03831673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc214156108ec57604080516303795fb160e11b81526001600160a01b038616600482015290516000916000805160206117af833981519152916306f2bf6291602480820192602092909190829003018186803b15801561086457600080fd5b505afa158015610878573d6000803e3d6000fd5b505050506040513d602081101561088e57600080fd5b5051604080516309903d8b60e21b81526004810186905290519192506107df91670de0b6b3a7640000916107da916001600160a01b03861691632640f62c916024808301926020929190829003018186803b1580156107a857600080fd5b604080516303795fb160e11b81526001600160a01b038516600482015290516000916000805160206117af833981519152916306f2bf6291602480820192602092909190829003018186803b15801561094457600080fd5b505afa158015610958573d6000803e3d6000fd5b505050506040513d602081101561096e57600080fd5b5051604080516309903d8b60e21b81526004810186905290516001600160a01b0390921691632640f62c91602480820192602092909190829003018186803b1580156109b957600080fd5b505afa1580156109cd573d6000803e3d6000fd5b505050506040513d60208110156109e357600080fd5b5051604080516303795fb160e11b81526001600160a01b038816600482015290519192506107df91670de0b6b3a7640000916107da916000805160206117af833981519152916306f2bf62916024808301926020929190829003018186803b158015610a4e57600080fd5b505afa158015610a62573d6000803e3d6000fd5b505050506040513d6020811015610a7857600080fd5b505160408051632cf4a43160e11b81526004810187905290516001600160a01b03909216916359e9486291602480820192602092909190829003018186803b1580156107a857600080fd5b6000546001600160a01b03163314610ada57600080fd5b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6001600160a01b0383161415610b3e57600080546040516001600160a01b039091169183156108fc02918491818181858888f19350505050158015610b38573d6000803e3d6000fd5b50610b5e565b600054610b5e906001600160a01b0384811691168363ffffffff61148016565b5050565b6000546001600160a01b03163314610b7957600080fd5b6000546001600160a01b0316ff5b6000546001600160a01b031681565b6001546001600160a01b03163314610bad57600080fd5b600180546001600160a01b0319166001600160a01b0392909216919091179055565b6000610bda846112ce565b9350610be5836112ce565b92506001600160a01b03841673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc21415610d1057604080516303795fb160e11b81526001600160a01b038516600482015290516000916000805160206117af833981519152916306f2bf6291602480820192602092909190829003018186803b158015610c6457600080fd5b505afa158015610c78573d6000803e3d6000fd5b505050506040513d6020811015610c8e57600080fd5b50516040805163cd7724c360e01b81526004810186905290519192506107df916001600160a01b0384169163cd7724c3916024808301926020929190829003018186803b158015610cde57600080fd5b505afa158015610cf2573d6000803e3d6000fd5b505050506040513d6020811015610d0857600080fd5b505184611450565b6001600160a01b03831673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc21415610e0757604080516303795fb160e11b81526001600160a01b038616600482015290516000916000805160206117af833981519152916306f2bf6291602480820192602092909190829003018186803b158015610d8d57600080fd5b505afa158015610da1573d6000803e3d6000fd5b505050506040513d6020811015610db757600080fd5b5051604080516395b68fe760e01b81526004810186905290519192506107df916001600160a01b038416916395b68fe7916024808301926020929190829003018186803b158015610cde57600080fd5b604080516303795fb160e11b81526001600160a01b038616600482015290516000916000805160206117af833981519152916306f2bf6291602480820192602092909190829003018186803b158015610e5f57600080fd5b505afa158015610e73573d6000803e3d6000fd5b505050506040513d6020811015610e8957600080fd5b5051604080516395b68fe760e01b81526004810186905290516001600160a01b03909216916395b68fe791602480820192602092909190829003018186803b158015610ed457600080fd5b505afa158015610ee8573d6000803e3d6000fd5b505050506040513d6020811015610efe57600080fd5b5051604080516303795fb160e11b81526001600160a01b038716600482015290519192506107df916000805160206117af833981519152916306f2bf62916024808301926020929190829003018186803b158015610f5b57600080fd5b505afa158015610f6f573d6000803e3d6000fd5b505050506040513d6020811015610f8557600080fd5b50516040805163cd7724c360e01b81526004810185905290516001600160a01b039092169163cd7724c391602480820192602092909190829003018186803b158015610cde57600080fd5b6000805160206117af83398151915281565b6000806000610ff0866112ce565b9550610ffb856112ce565b94506001600160a01b03851673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2141561115057604080516303795fb160e11b81526001600160a01b038816600482015290516000805160206117af833981519152916306f2bf62916024808301926020929190829003018186803b15801561107657600080fd5b505afa15801561108a573d6000803e3d6000fd5b505050506040513d60208110156110a057600080fd5b505191506110be6001600160a01b038716838663ffffffff61131616565b60408051637237e03160e01b8152600481018690526001602482018190524201604482015233606482015290516001600160a01b03841691637237e0319160848083019260209291908290030181600087803b15801561111d57600080fd5b505af1158015611131573d6000803e3d6000fd5b505050506040513d602081101561114757600080fd5b5051905061062f565b604080516303795fb160e11b81526001600160a01b038816600482015290516000805160206117af833981519152916306f2bf62916024808301926020929190829003018186803b1580156111a457600080fd5b505afa1580156111b8573d6000803e3d6000fd5b505050506040513d60208110156111ce57600080fd5b505191506111ec6001600160a01b038716838663ffffffff61131616565b6040805163f552d91b60e01b81526004810186905260016024820181905260448201819052420160648201523360848201526001600160a01b0387811660a483015291519184169163f552d91b9160c4808201926020929091908290030181600087803b15801561125c57600080fd5b505af1158015611270573d6000803e3d6000fd5b505050506040513d602081101561128657600080fd5b50519695505050505050565b6000546001600160a01b031633146112a957600080fd5b6001546001600160a01b031615610bad57600080fd5b6001546001600160a01b031681565b60006001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee146112fa5781611310565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc25b92915050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b1790526113689084906114ce565b505050565b60405133904780156108fc02916000818181858888f19350505050158015611399573d6000803e3d6000fd5b506001600160a01b03811673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1461144d57604080516370a0823160e01b8152306004820152905161144d9133916001600160a01b038516916370a08231916024808301926020929190829003018186803b15801561140a57600080fd5b505afa15801561141e573d6000803e3d6000fd5b505050506040513d602081101561143457600080fd5b50516001600160a01b038416919063ffffffff61148016565b50565b60008161147161146885670de0b6b3a764000061157f565b600285046115a3565b8161147857fe5b049392505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b1790526113689084905b6060611523826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166115b39092919063ffffffff16565b8051909150156113685780806020019051602081101561154257600080fd5b50516113685760405162461bcd60e51b815260040180806020018281038252602a8152602001806117cf602a913960400191505060405180910390fd5b600081158061159a5750508082028282828161159757fe5b04145b61131057600080fd5b8082018281101561131057600080fd5b60606115c284846000856115ca565b949350505050565b60606115d585611775565b611626576040805162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015290519081900360640190fd5b60006060866001600160a01b031685876040518082805190602001908083835b602083106116655780518252601f199092019160209182019101611646565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d80600081146116c7576040519150601f19603f3d011682016040523d82523d6000602084013e6116cc565b606091505b509150915081156116e05791506115c29050565b8051156116f05780518082602001fd5b8360405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561173a578181015183820152602001611722565b50505050905090810190601f1680156117675780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a4708181148015906115c257505015159291505056fe000000000000000000000000c0a47dfe034b400b47bdad5fecda2621de6c4d955361666545524332303a204552433230206f7065726174696f6e20646964206e6f742073756363656564a264697066735822122007bd445b6de1dc6b1bfa10c338487d6f1b1ae71a9813ae47a9dffef92984e9e964736f6c63430006060033
{"success": true, "error": null, "results": {"detectors": [{"check": "tx-origin", "impact": "Medium", "confidence": "Medium"}, {"check": "name-reused", "impact": "High", "confidence": "High"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-lowlevel", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'tx-origin', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'name-reused', 'impact': 'High', 'confidence': 'High'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-lowlevel', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
62
0x153f304dc5e528e3754c51710794306286c68111
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); } contract CurveStakingAdapter is ProtocolAdapter { string public constant override adapterType = "Asset"; string public constant override tokenType = "ERC20"; address internal constant C_CRV = 0x845838DF265Dcd2c412A1Dc9e959c7d08537f8a2; address internal constant Y_CRV = 0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8; address internal constant B_CRV = 0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B; address internal constant S_CRV = 0xC25a3A3b969415c80451098fa907EC722572917F; address internal constant P_CRV = 0xD905e2eaeBe188fc92179b6350807D8bd91Db0D8; address internal constant REN_CRV = 0x49849C98ae39Fff122806C06791Fa73784FB3675; address internal constant SBTC_CRV = 0x075b1bb99792c9E1041bA13afEf80C91a1e70fB3; address internal constant C_GAUGE = 0x7ca5b0a2910B33e9759DC7dDB0413949071D7575; address internal constant Y_GAUGE = 0xFA712EE4788C042e2B7BB55E6cb8ec569C4530c1; address internal constant B_GAUGE = 0x69Fb7c45726cfE2baDeE8317005d3F94bE838840; address internal constant S_GAUGE = 0xA90996896660DEcC6E997655E065b23788857849; address internal constant P_GAUGE = 0x64E3C23bfc40722d3B649844055F1D51c1ac041d; address internal constant REN_GAUGE = 0xB1F2cdeC61db658F091671F5f199635aEF202CAC; address internal constant SBTC_GAUGE = 0x705350c4BcD35c9441419DdD5d2f097d7a55410F; /** * @return Amount of staked LP tokens for a given account. * @dev Implementation of ProtocolAdapter interface function. */ function getBalance(address token, address account) external view override returns (uint256) { if (token == C_CRV) { return ERC20(C_GAUGE).balanceOf(account); } else if (token == Y_CRV) { return ERC20(Y_GAUGE).balanceOf(account); } else if (token == B_CRV) { return ERC20(B_GAUGE).balanceOf(account); } else if (token == S_CRV) { return ERC20(S_GAUGE).balanceOf(account); } else if (token == P_CRV) { return ERC20(P_GAUGE).balanceOf(account); } else if (token == REN_CRV) { return ERC20(REN_GAUGE).balanceOf(account); } else if (token == SBTC_CRV) { return ERC20(SBTC_GAUGE).balanceOf(account); } else { return 0; } } }
0x608060405234801561001057600080fd5b50600436106100415760003560e01c806330fa738c14610046578063d4fac45d14610064578063f72c079114610084575b600080fd5b61004e61008c565b60405161005b9190610580565b60405180910390f35b610077610072366004610513565b6100c5565b60405161005b91906105f1565b61004e6104b6565b6040518060400160405280600581526020017f455243323000000000000000000000000000000000000000000000000000000081525081565b600073ffffffffffffffffffffffffffffffffffffffff831673845838df265dcd2c412a1dc9e959c7d08537f8a214156101a0576040517f70a08231000000000000000000000000000000000000000000000000000000008152737ca5b0a2910b33e9759dc7ddb0413949071d7575906370a082319061014990859060040161055f565b60206040518083038186803b15801561016157600080fd5b505afa158015610175573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101999190610547565b90506104b0565b73ffffffffffffffffffffffffffffffffffffffff831673df5e0e81dff6faf3a7e52ba697820c5e32d806a81415610222576040517f70a0823100000000000000000000000000000000000000000000000000000000815273fa712ee4788c042e2b7bb55e6cb8ec569c4530c1906370a082319061014990859060040161055f565b73ffffffffffffffffffffffffffffffffffffffff8316733b3ac5386837dc563660fb6a0937dfaa5924333b14156102a4576040517f70a082310000000000000000000000000000000000000000000000000000000081527369fb7c45726cfe2badee8317005d3f94be838840906370a082319061014990859060040161055f565b73ffffffffffffffffffffffffffffffffffffffff831673c25a3a3b969415c80451098fa907ec722572917f1415610326576040517f70a0823100000000000000000000000000000000000000000000000000000000815273a90996896660decc6e997655e065b23788857849906370a082319061014990859060040161055f565b73ffffffffffffffffffffffffffffffffffffffff831673d905e2eaebe188fc92179b6350807d8bd91db0d814156103a8576040517f70a082310000000000000000000000000000000000000000000000000000000081527364e3c23bfc40722d3b649844055f1d51c1ac041d906370a082319061014990859060040161055f565b73ffffffffffffffffffffffffffffffffffffffff83167349849c98ae39fff122806c06791fa73784fb3675141561042a576040517f70a0823100000000000000000000000000000000000000000000000000000000815273b1f2cdec61db658f091671f5f199635aef202cac906370a082319061014990859060040161055f565b73ffffffffffffffffffffffffffffffffffffffff831673075b1bb99792c9e1041ba13afef80c91a1e70fb314156104ac576040517f70a0823100000000000000000000000000000000000000000000000000000000815273705350c4bcd35c9441419ddd5d2f097d7a55410f906370a082319061014990859060040161055f565b5060005b92915050565b6040518060400160405280600581526020017f417373657400000000000000000000000000000000000000000000000000000081525081565b803573ffffffffffffffffffffffffffffffffffffffff811681146104b057600080fd5b60008060408385031215610525578182fd5b61052f84846104ef565b915061053e84602085016104ef565b90509250929050565b600060208284031215610558578081fd5b5051919050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b6000602080835283518082850152825b818110156105ac57858101830151858201604001528201610590565b818111156105bd5783604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b9081526020019056fea2646970667358221220f3cb7afeb16dac20ae207dcf89e44c40f84a39ff05227ee2c160d4f9d8f5090464736f6c63430006050033
{"success": true, "error": null, "results": {}}
true
null
{}
63
0x155ab266b9226525cfd5b1e7d8a80bab65b6b609
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 Platinum Token", "DXPT") { _mint(msg.sender, 25000 * 1e18); } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c80633950935111610071578063395093511461025f57806370a08231146102c557806395d89b411461031d578063a457c2d7146103a0578063a9059cbb14610406578063dd62ed3e1461046c576100a9565b806306fdde03146100ae578063095ea7b31461013157806318160ddd1461019757806323b872dd146101b5578063313ce5671461023b575b600080fd5b6100b66104e4565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f65780820151818401526020810190506100db565b50505050905090810190601f1680156101235780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61017d6004803603604081101561014757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610586565b604051808215151515815260200191505060405180910390f35b61019f6105a4565b6040518082815260200191505060405180910390f35b610221600480360360608110156101cb57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506105ae565b604051808215151515815260200191505060405180910390f35b610243610687565b604051808260ff1660ff16815260200191505060405180910390f35b6102ab6004803603604081101561027557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061069e565b604051808215151515815260200191505060405180910390f35b610307600480360360208110156102db57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610751565b6040518082815260200191505060405180910390f35b610325610799565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561036557808201518184015260208101905061034a565b50505050905090810190601f1680156103925780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6103ec600480360360408110156103b657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061083b565b604051808215151515815260200191505060405180910390f35b6104526004803603604081101561041c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610908565b604051808215151515815260200191505060405180910390f35b6104ce6004803603604081101561048257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610926565b6040518082815260200191505060405180910390f35b606060038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561057c5780601f106105515761010080835404028352916020019161057c565b820191906000526020600020905b81548152906001019060200180831161055f57829003601f168201915b5050505050905090565b600061059a6105936109ad565b84846109b5565b6001905092915050565b6000600254905090565b60006105bb848484610bac565b61067c846105c76109ad565b6106778560405180606001604052806028815260200161102660289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600061062d6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6109b5565b600190509392505050565b6000600560009054906101000a900460ff16905090565b60006107476106ab6109ad565b8461074285600160006106bc6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2d90919063ffffffff16565b6109b5565b6001905092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b606060048054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108315780601f1061080657610100808354040283529160200191610831565b820191906000526020600020905b81548152906001019060200180831161081457829003601f168201915b5050505050905090565b60006108fe6108486109ad565b846108f98560405180606001604052806025815260200161109760259139600160006108726109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6109b5565b6001905092915050565b600061091c6109156109ad565b8484610bac565b6001905092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610a3b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260248152602001806110736024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610ac1576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180610fde6022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610c32576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602581526020018061104e6025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610cb8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526023815260200180610fbb6023913960400191505060405180910390fd5b610cc3838383610fb5565b610d2e81604051806060016040528060268152602001611000602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610dc1816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2d90919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b6000838311158290610f1a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610edf578082015181840152602081019050610ec4565b50505050905090810190601f168015610f0c5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b600080828401905083811015610fab576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b50505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa26469706673582212205ede68f470aa8846e6583b64acb784e811db22fcabf7fea4111512aeeb16e13b64736f6c63430006020033
{"success": true, "error": null, "results": {}}
true
null
{}
64
0x15601dB5A27e21207244075d676750B192206eB0
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 = 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 = 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); 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] && _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; } 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; } } 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, 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 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 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; } 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) * (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]); } } function getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } } 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); 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 = 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; 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, 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).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; } 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; 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)); 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(DAI_ADDRESS); 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 _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) { (, 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])); } } }
0x6080604052600436106100e15760003560e01c806341c0e1b51161007f578063b91351e111610059578063b91351e11461029e578063cae270b6146102e1578063deca5f8814610317578063f851a4401461034a576100e8565b806341c0e1b5146102415780638da5cb5b14610256578063a7304bf71461026b576100e8565b806329f7fc9e116100bb57806329f7fc9e1461019b5780632a441f05146101b05780632f73fc1a146101c55780633a12832214610208576100e8565b8063040141e5146100ed578063153e66e61461011e5780631e48907b14610166576100e8565b366100e857005b600080fd5b3480156100f957600080fd5b5061010261035f565b604080516001600160a01b039092168252519081900360200190f35b6101546004803603606081101561013457600080fd5b506001600160a01b03813581169160208101359091169060400135610377565b60408051918252519081900360200190f35b34801561017257600080fd5b506101996004803603602081101561018957600080fd5b50356001600160a01b031661055d565b005b3480156101a757600080fd5b50610102610596565b3480156101bc57600080fd5b506101026105ae565b3480156101d157600080fd5b50610154600480360360608110156101e857600080fd5b506001600160a01b038135811691602081013590911690604001356105c6565b34801561021457600080fd5b506101996004803603604081101561022b57600080fd5b506001600160a01b038135169060200135610684565b34801561024d57600080fd5b50610199610723565b34801561026257600080fd5b50610102610748565b34801561027757600080fd5b506101996004803603602081101561028e57600080fd5b50356001600160a01b0316610757565b3480156102aa57600080fd5b50610154600480360360608110156102c157600080fd5b506001600160a01b03813581169160208101359091169060400135610790565b610154600480360360608110156102f757600080fd5b506001600160a01b03813581169160208101359091169060400135610819565b34801561032357600080fd5b506101996004803603602081101561033a57600080fd5b50356001600160a01b03166109e7565b34801561035657600080fd5b50610102610a14565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b60008061038385610a23565b9050600061039085610a23565b90506103c26001600160a01b03831673794e6e91555438afc3ccf1c5076a74f42133d08d60001963ffffffff610a6b16565b60408051638185402b60e01b81526001600160a01b03838116600483015260248201879052841660448201526000196064820152905160009173794e6e91555438afc3ccf1c5076a74f42133d08d91638185402b9160848082019260209290919082900301818787803b15801561043857600080fd5b505af115801561044c573d6000803e3d6000fd5b505050506040513d602081101561046257600080fd5b505190506001600160a01b03821673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc214156105305773c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316632e1a7d4d866040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b1580156104e557600080fd5b505af11580156104f9573d6000803e3d6000fd5b505060405133925087156108fc02915087906000818181858888f1935050505015801561052a573d6000803e3d6000fd5b5061054a565b61054a6001600160a01b038316338763ffffffff610ac216565b61055383610b14565b9695505050505050565b6001546001600160a01b0316331461057457600080fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b73794e6e91555438afc3ccf1c5076a74f42133d08d81565b6000806105d285610a23565b905060006105df85610a23565b604080516001623809a360e21b031981526001600160a01b038581166004830152831660248201526044810187905290519192506105539173794e6e91555438afc3ccf1c5076a74f42133d08d9163ff1fd974916064808301926020929190829003018186803b15801561065257600080fd5b505afa158015610666573d6000803e3d6000fd5b505050506040513d602081101561067c57600080fd5b505185610bf7565b6000546001600160a01b0316331461069b57600080fd5b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6001600160a01b03831614156106ff57600080546040516001600160a01b039091169183156108fc02918491818181858888f193505050501580156106f9573d6000803e3d6000fd5b5061071f565b60005461071f906001600160a01b0384811691168363ffffffff610ac216565b5050565b6000546001600160a01b0316331461073a57600080fd5b6000546001600160a01b0316ff5b6000546001600160a01b031681565b6001546001600160a01b0316331461076e57600080fd5b600180546001600160a01b0319166001600160a01b0392909216919091179055565b60008061079c85610a23565b905060006107a985610a23565b60408051630a2513a960e11b81526001600160a01b038084166004830152851660248201526044810187905290519192506105539173794e6e91555438afc3ccf1c5076a74f42133d08d9163144a2752916064808301926020929190829003018186803b15801561065257600080fd5b60008061082585610a23565b9050600061083285610a23565b90506108626001600160a01b03831673794e6e91555438afc3ccf1c5076a74f42133d08d8663ffffffff610a6b16565b60408051630310da7b60e11b81526001600160a01b0384811660048301526024820187905283166044820152600060648201819052915173794e6e91555438afc3ccf1c5076a74f42133d08d91630621b4f691608480830192602092919082900301818787803b1580156108d557600080fd5b505af11580156108e9573d6000803e3d6000fd5b505050506040513d60208110156108ff57600080fd5b505190506001600160a01b03821673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc214156109cd5773c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316632e1a7d4d826040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b15801561098257600080fd5b505af1158015610996573d6000803e3d6000fd5b505060405133925083156108fc02915083906000818181858888f193505050501580156109c7573d6000803e3d6000fd5b50610553565b6105536001600160a01b038316338363ffffffff610ac216565b6000546001600160a01b031633146109fe57600080fd5b6001546001600160a01b03161561076e57600080fd5b6001546001600160a01b031681565b60006001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14610a4f5781610a65565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc25b92915050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b179052610abd908490610c27565b505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052610abd908490610c27565b60405133904780156108fc02916000818181858888f19350505050158015610b40573d6000803e3d6000fd5b506001600160a01b03811673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14610bf457604080516370a0823160e01b81523060048201529051610bf49133916001600160a01b038516916370a08231916024808301926020929190829003018186803b158015610bb157600080fd5b505afa158015610bc5573d6000803e3d6000fd5b505050506040513d6020811015610bdb57600080fd5b50516001600160a01b038416919063ffffffff610ac216565b50565b600081610c18610c0f85670de0b6b3a7640000610cd8565b60028504610cfc565b81610c1f57fe5b049392505050565b6060610c7c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316610d0c9092919063ffffffff16565b805190915015610abd57808060200190516020811015610c9b57600080fd5b5051610abd5760405162461bcd60e51b815260040180806020018281038252602a815260200180610f08602a913960400191505060405180910390fd5b6000811580610cf357505080820282828281610cf057fe5b04145b610a6557600080fd5b80820182811015610a6557600080fd5b6060610d1b8484600085610d23565b949350505050565b6060610d2e85610ece565b610d7f576040805162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015290519081900360640190fd5b60006060866001600160a01b031685876040518082805190602001908083835b60208310610dbe5780518252601f199092019160209182019101610d9f565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d8060008114610e20576040519150601f19603f3d011682016040523d82523d6000602084013e610e25565b606091505b50915091508115610e39579150610d1b9050565b805115610e495780518082602001fd5b8360405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610e93578181015183820152602001610e7b565b50505050905090810190601f168015610ec05780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590610d1b57505015159291505056fe5361666545524332303a204552433230206f7065726174696f6e20646964206e6f742073756363656564a26469706673582212200083d5b27b0d6f92e1132b0cc0d64794cfa3d25a403f29b52238b026f6cd4e2764736f6c63430006060033
{"success": true, "error": null, "results": {"detectors": [{"check": "tx-origin", "impact": "Medium", "confidence": "Medium"}, {"check": "name-reused", "impact": "High", "confidence": "High"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-lowlevel", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'tx-origin', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'name-reused', 'impact': 'High', 'confidence': 'High'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-lowlevel', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
65
0x157372F9d3c94609ADfb967741A0aFc0c1db1BBF
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 = 55000000000000000; 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 _priceChangeDelay = 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) { msg.sender.transfer(msg.value - ETHRequired); // refund extra } } /// @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(1000000000000000000); _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 + _priceChangeDelay; } 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) { (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 += prices[id].mul(quantity); } for (uint256 i = 0; i < gemQuantities.length; i++) { uint256 quantity = gemQuantities[i]; totalPrice += 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 + 1 hours) { _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 } }
0x6080604052600436106101805760003560e01c80638f283970116100d6578063bf5c3e9f1161007f578063d1b8f6b311610059578063d1b8f6b314610406578063dc5074af14610426578063e97eb0a21461044657610180565b8063bf5c3e9f146103b1578063c96f8902146103d1578063caed3500146103f157610180565b8063b0e6bfaa116100b0578063b0e6bfaa1461034b578063b522ecff1461036b578063bd9a548b1461038b57610180565b80638f283970146102f6578063915c851314610316578063a7e306841461033657610180565b806358bc2944116101385780636e9960c3116101125780636e9960c3146102945780637c53ec4c146102b65780638a04af6a146102d657610180565b806358bc2944146102345780635d8e3021146102545780635f995c2d1461028157610180565b8063427b8d3411610169578063427b8d34146101c75780634a253778146101f25780634d08cbc11461020757610180565b80633b7c4c15146101855780633d5f167b146101a7575b600080fd5b34801561019157600080fd5b506101a56101a03660046123e8565b610466565b005b3480156101b357600080fd5b506101a56101c236600461230b565b6104d1565b3480156101d357600080fd5b506101dc610568565b6040516101e99190612802565b60405180910390f35b3480156101fe57600080fd5b506101dc610578565b34801561021357600080fd5b506102276102223660046122ca565b610586565b6040516101e99190612c56565b34801561024057600080fd5b506101a561024f366004612069565b6105c5565b34801561026057600080fd5b5061027461026f366004612438565b61061e565b6040516101e99190612c73565b6101a561028f366004612224565b610659565b3480156102a057600080fd5b506102a9610b5c565b6040516101e99190612634565b3480156102c257600080fd5b506101a56102d13660046123e8565b610b6b565b3480156102e257600080fd5b506101a56102f13660046121ec565b610ba8565b34801561030257600080fd5b506101a5610311366004612069565b610be0565b34801561032257600080fd5b506101dc610331366004612105565b610c80565b34801561034257600080fd5b506101dc610d2e565b34801561035757600080fd5b506101a5610366366004612224565b610d37565b34801561037757600080fd5b506101a5610386366004612069565b611036565b34801561039757600080fd5b506103a06110b5565b6040516101e99594939291906127bf565b3480156103bd57600080fd5b506102276103cc3660046122ca565b611193565b3480156103dd57600080fd5b506101a56103ec366004612085565b6111c2565b3480156103fd57600080fd5b506102a961159e565b34801561041257600080fd5b506101a5610421366004612224565b6115ad565b34801561043257600080fd5b506101dc610441366004612069565b611855565b34801561045257600080fd5b506101a56104613660046123e8565b611873565b6000546001600160a01b031633146104995760405162461bcd60e51b815260040161049090612b53565b60405180910390fd5b6004805491151562010000027fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ffff909216919091179055565b6000546001600160a01b031633146104fb5760405162461bcd60e51b815260040161049090612b53565b6005805461050b91600691611e99565b5061051860058484611ee9565b5060078054600855819055426009556040517fb4484e658d3a3ea551621c62bec48be6ac3aab4615fa987434fa1bd62bd76c939061055b9085908590859061279b565b60405180910390a1505050565b60045462010000900460ff165b90565b600454610100900460ff1690565b6001600160a01b03821660009081526003602090815260408083206fffffffffffffffffffffffffffffffff8086168552925290912054165b92915050565b6000546001600160a01b031633146105ef5760405162461bcd60e51b815260040161049090612a1a565b6002805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0392909216919091179055565b6000806106296118d4565b9050610652816106468566c3663566a5800063ffffffff61196e16565b9063ffffffff6119a916565b9392505050565b336001600160a01b038516148061067f57503360009081526001602052604090205460ff165b61069b5760405162461bcd60e51b815260040161049090612aae565b600454610100900460ff166106c25760405162461bcd60e51b81526004016104909061293e565b6001600160a01b0384166106e85760405162461bcd60e51b815260040161049090612862565b6001600160a01b0384163014156107115760405162461bcd60e51b815260040161049090612b8a565b61084d8461071f8580612c7c565b8080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525061075e925050506020870187612c7c565b8080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525061079d925050506040880188612c7c565b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152506107dc925050506060890189612c7c565b8080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525050604080516020601f8c018190048102820181019092528a815260808d0135935091508a908a9081908401838280828437600092019190915250610c8092505050565b6108695760405162461bcd60e51b8152600401610490906129ac565b600061092d6108788580612c7c565b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152506108b7925050506020870187612c7c565b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152506108f6925050506060880188612c7c565b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152506119d992505050565b9050600061093a8261061e565b90508034101561095c5760405162461bcd60e51b815260040161049090612899565b600a546040516001600160a01b039091169082156108fc029083906000818181858888f19350505050158015610996573d6000803e3d6000fd5b506001600160a01b037f0000000000000000000000002fc246149b4b8d7bcef6188a10af1791380227f1166317fad7fc30886109d28980612c7c565b6109df60208c018c612c7c565b6040518763ffffffff1660e01b8152600401610a0096959493929190612686565b600060405180830381600087803b158015610a1a57600080fd5b505af1158015610a2e573d6000803e3d6000fd5b50506001600160a01b037f0000000000000000000000008ff2611da386de427fc96a8073963619c5851ba51691506317fad7fc90503088610a7260408a018a612c7c565b610a7f60608c018c612c7c565b6040518763ffffffff1660e01b8152600401610aa096959493929190612686565b600060405180830381600087803b158015610aba57600080fd5b505af1158015610ace573d6000803e3d6000fd5b50505050856001600160a01b03167fdfdb2e8aa552e0517bf744153975973b0beb2bedf0e81bbf58d7744b738197b88684600085604051610b129493929190612c1e565b60405180910390a23481900315610b545760405133903483900380156108fc02916000818181858888f19350505050158015610b52573d6000803e3d6000fd5b505b505050505050565b6000546001600160a01b031690565b6000546001600160a01b03163314610b955760405162461bcd60e51b815260040161049090612b53565b6004805460ff1916911515919091179055565b6000546001600160a01b03163314610bd25760405162461bcd60e51b815260040161049090612a51565b610bdc8282611aad565b5050565b6000546001600160a01b03163314610c0a5760405162461bcd60e51b815260040161049090612ae5565b6000546040517f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f91610c49916001600160a01b03909116908490612648565b60405180910390a16000805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0392909216919091179055565b6000610c8c8884611b0f565b610ca85760405162461bcd60e51b8152600401610490906129e3565b6000878787878c88604051602001610cc5969594939291906125a0565b6040516020818303038152906040528051906020012090506000610d0f82604051602001610cf39190612603565b6040516020818303038152906040528051906020012085611be6565b6002546001600160a01b039081169116149a9950505050505050505050565b60045460ff1690565b336001600160a01b0385161480610d5d57503360009081526001602052604090205460ff165b610d795760405162461bcd60e51b815260040161049090612aae565b60045462010000900460ff16610da15760405162461bcd60e51b81526004016104909061282b565b6001600160a01b038416610dc75760405162461bcd60e51b815260040161049090612862565b6001600160a01b038416301415610df05760405162461bcd60e51b815260040161049090612b8a565b610dfe8461071f8580612c7c565b610e1a5760405162461bcd60e51b8152600401610490906129ac565b6000610e296108788580612c7c565b90506000610e50670de0b6b3a76400006106468466c3663566a5800063ffffffff61196e16565b600a54909150610e8c9087906001600160a01b03167f0000000000000000000000006b175474e89094c44da98b954eedeac495271d0f84611ca1565b6001600160a01b037f0000000000000000000000002fc246149b4b8d7bcef6188a10af1791380227f1166317fad7fc3088610ec78980612c7c565b610ed460208c018c612c7c565b6040518763ffffffff1660e01b8152600401610ef596959493929190612686565b600060405180830381600087803b158015610f0f57600080fd5b505af1158015610f23573d6000803e3d6000fd5b50506001600160a01b037f0000000000000000000000008ff2611da386de427fc96a8073963619c5851ba51691506317fad7fc90503088610f6760408a018a612c7c565b610f7460608c018c612c7c565b6040518763ffffffff1660e01b8152600401610f9596959493929190612686565b600060405180830381600087803b158015610faf57600080fd5b505af1158015610fc3573d6000803e3d6000fd5b50505050856001600160a01b03167fdfdb2e8aa552e0517bf744153975973b0beb2bedf0e81bbf58d7744b738197b886847f0000000000000000000000006b175474e89094c44da98b954eedeac495271d0f856040516110269493929190612c1e565b60405180910390a2505050505050565b6001600160a01b03811661105c5760405162461bcd60e51b815260040161049090612975565b6000546001600160a01b031633146110865760405162461bcd60e51b815260040161049090612b53565b600a805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0392909216919091179055565b60608060008060008090506009546000146110d35750600b54600954015b60066005600854600754848480548060200260200160405190810160405280929190818152602001828054801561112957602002820191906000526020600020905b815481526020019060010190808311611115575b505050505094508380548060200260200160405190810160405280929190818152602001828054801561117b57602002820191906000526020600020905b815481526020019060010190808311611167575b50505050509350945094509450945094509091929394565b60036020908152600092835260408084209091529082529020546fffffffffffffffffffffffffffffffff1681565b6000546001600160a01b031633146111ec5760405162461bcd60e51b815260040161049090612b53565b60608367ffffffffffffffff8111801561120557600080fd5b5060405190808252806020026020018201604052801561122f578160200160208202803683370190505b50905060005b8481101561126a573082828151811061124a57fe5b6001600160a01b0390921660209283029190910190910152600101611235565b5060608267ffffffffffffffff8111801561128457600080fd5b506040519080825280602002602001820160405280156112ae578160200160208202803683370190505b50905060005b838110156112e957308282815181106112c957fe5b6001600160a01b03909216602092830291909101909101526001016112b4565b506040517f4e1273f40000000000000000000000000000000000000000000000000000000081526060906001600160a01b037f0000000000000000000000002fc246149b4b8d7bcef6188a10af1791380227f11690634e1273f4906113569086908b908b90600401612739565b60006040518083038186803b15801561136e57600080fd5b505afa158015611382573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526113aa9190810190612355565b905060607f0000000000000000000000008ff2611da386de427fc96a8073963619c5851ba56001600160a01b0316634e1273f48488886040518463ffffffff1660e01b81526004016113fe93929190612739565b60006040518083038186803b15801561141657600080fd5b505afa15801561142a573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526114529190810190612355565b6040517f17fad7fc0000000000000000000000000000000000000000000000000000000081529091506001600160a01b037f0000000000000000000000002fc246149b4b8d7bcef6188a10af1791380227f116906317fad7fc906114c29030908d908d908d9089906004016126d3565b600060405180830381600087803b1580156114dc57600080fd5b505af11580156114f0573d6000803e3d6000fd5b50506040517f17fad7fc0000000000000000000000000000000000000000000000000000000081526001600160a01b037f0000000000000000000000008ff2611da386de427fc96a8073963619c5851ba51692506317fad7fc91506115619030908d908b908b9088906004016126d3565b600060405180830381600087803b15801561157b57600080fd5b505af115801561158f573d6000803e3d6000fd5b50505050505050505050505050565b6002546001600160a01b031690565b336001600160a01b03851614806115d357503360009081526001602052604090205460ff165b6115ef5760405162461bcd60e51b815260040161049090612aae565b60045460ff166116115760405162461bcd60e51b815260040161049090612907565b6001600160a01b0384166116375760405162461bcd60e51b815260040161049090612862565b6116458461071f8580612c7c565b6116615760405162461bcd60e51b8152600401610490906129ac565b60006116706108788580612c7c565b600a549091506116ac9086906001600160a01b03167f0000000000000000000000003845badade8e6dff049820680d1f14bd3903a5d084611ca1565b6001600160a01b037f0000000000000000000000002fc246149b4b8d7bcef6188a10af1791380227f1166317fad7fc30876116e78880612c7c565b6116f460208b018b612c7c565b6040518763ffffffff1660e01b815260040161171596959493929190612686565b600060405180830381600087803b15801561172f57600080fd5b505af1158015611743573d6000803e3d6000fd5b50506001600160a01b037f0000000000000000000000008ff2611da386de427fc96a8073963619c5851ba51691506317fad7fc905030876117876040890189612c7c565b61179460608b018b612c7c565b6040518763ffffffff1660e01b81526004016117b596959493929190612686565b600060405180830381600087803b1580156117cf57600080fd5b505af11580156117e3573d6000803e3d6000fd5b50505050846001600160a01b03167fdfdb2e8aa552e0517bf744153975973b0beb2bedf0e81bbf58d7744b738197b885837f0000000000000000000000003845badade8e6dff049820680d1f14bd3903a5d0856040516118469493929190612c1e565b60405180910390a25050505050565b6001600160a01b031660009081526001602052604090205460ff1690565b6000546001600160a01b0316331461189d5760405162461bcd60e51b815260040161049090612b53565b60048054911515610100027fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff909216919091179055565b6000807f000000000000000000000000729d19f657bd0614b4985cf1d82531c67569197b6001600160a01b03166357de26a46040518163ffffffff1660e01b815260040160206040518083038186803b15801561193057600080fd5b505afa158015611944573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119689190612420565b91505090565b60008261197d575060006105bf565b508181028183828161198b57fe5b04146105bf5760405162461bcd60e51b815260040161049090612b1c565b6000816119c85760405162461bcd60e51b815260040161049090612be7565b8183816119d157fe5b049392505050565b6000606060006119e7611d5c565b90925090506000805b8751811015611a5d576000888281518110611a0757fe5b602002602001015190506000888381518110611a1f57fe5b60200260200101519050611a4f81878481518110611a3957fe5b602002602001015161196e90919063ffffffff16565b9093019250506001016119f0565b5060005b8551811015611aa2576000868281518110611a7857fe5b60200260200101519050611a95818561196e90919063ffffffff16565b9092019150600101611a61565b509695505050505050565b6001600160a01b03821660009081526001602052604090819020805460ff1916831515179055517fb21eb88b4e33b3f1281830a7178d74d8aa73220416215726b68ae23d539515cb90611b03908490849061271e565b60405180910390a15050565b6001600160a01b038216600090815260036020908152604080832070010000000000000000000000000000000085046fffffffffffffffffffffffffffffffff81811686529190935290832054848216911680821415611bda576001600160a01b03861660009081526003602090815260408083206fffffffffffffffffffffffffffffffff9687168452909152902080547fffffffffffffffffffffffffffffffff00000000000000000000000000000000166001928301909416939093179092555090506105bf565b50600095945050505050565b60008151604114611bf657600080fd5b60208201516040830151606084015160001a601b811015611c1557601b015b8060ff16601b1480611c2a57508060ff16601c145b611c3357600080fd5b60018682858560405160008152602001604052604051611c56949392919061280d565b6020604051602081039080840390855afa158015611c78573d6000803e3d6000fd5b5050604051601f1901519450506001600160a01b038416611c9857600080fd5b50505092915050565b6040517f23b872dd000000000000000000000000000000000000000000000000000000008152829082906001600160a01b038316906323b872dd90611cee90899089908690600401612662565b602060405180830381600087803b158015611d0857600080fd5b505af1158015611d1c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d409190612404565b610b545760405162461bcd60e51b8152600401610490906128d0565b606060006060600060095460001415611dcc576005805480602002602001604051908101604052809291908181526020018280548015611dbb57602002820191906000526020600020905b815481526020019060010190808311611da7575b505050505091506007549050611e90565b600954610e1001421115611e375760006009556005805460408051602080840282018101909252828152929190830182828015611dbb5760200282019190600052602060002090815481526020019060010190808311611da757505050505091506007549050611e90565b6006805480602002602001604051908101604052809291908181526020018280548015611e8357602002820191906000526020600020905b815481526020019060010190808311611e6f575b5050505050915060085490505b90925090509091565b828054828255906000526020600020908101928215611ed95760005260206000209182015b82811115611ed9578254825591600101919060010190611ebe565b50611ee5929150611f24565b5090565b828054828255906000526020600020908101928215611ed9579160200282015b82811115611ed9578235825591602001919060010190611f09565b61057591905b80821115611ee55760008155600101611f2a565b80356105bf81612d56565b60008083601f840112611f5a578182fd5b50813567ffffffffffffffff811115611f71578182fd5b6020830191508360208083028501011115611f8b57600080fd5b9250929050565b600082601f830112611fa2578081fd5b8135611fb5611fb082612cee565b612cc7565b818152915060208083019084810181840286018201871015611fd657600080fd5b60005b84811015611ff557813584529282019290820190600101611fd9565b505050505092915050565b600082601f830112612010578081fd5b813567ffffffffffffffff811115612026578182fd5b6120396020601f19601f84011601612cc7565b915080825283602082850101111561205057600080fd5b8060208401602084013760009082016020015292915050565b60006020828403121561207a578081fd5b813561065281612d56565b60008060008060006060868803121561209c578081fd5b85356120a781612d56565b9450602086013567ffffffffffffffff808211156120c3578283fd5b6120cf89838a01611f49565b909650945060408801359150808211156120e7578283fd5b506120f488828901611f49565b969995985093965092949392505050565b600080600080600080600060e0888a03121561211f578182fd5b6121298989611f3e565b9650602088013567ffffffffffffffff80821115612145578384fd5b6121518b838c01611f92565b975060408a0135915080821115612166578384fd5b6121728b838c01611f92565b965060608a0135915080821115612187578384fd5b6121938b838c01611f92565b955060808a01359150808211156121a8578384fd5b6121b48b838c01611f92565b945060a08a0135935060c08a01359150808211156121d0578283fd5b506121dd8a828b01612000565b91505092959891949750929550565b600080604083850312156121fe578182fd5b823561220981612d56565b9150602083013561221981612d6e565b809150509250929050565b60008060008060608587031215612239578384fd5b843561224481612d56565b9350602085013567ffffffffffffffff80821115612260578485fd5b81870160a0818a031215612272578586fd5b94506040870135915080821115612287578384fd5b81870188601f820112612298578485fd5b80359250818311156122a8578485fd5b8860208483010111156122b9578485fd5b959894975050602090940194505050565b600080604083850312156122dc578182fd5b82356122e781612d56565b915060208301356fffffffffffffffffffffffffffffffff81168114612219578182fd5b60008060006040848603121561231f578283fd5b833567ffffffffffffffff811115612335578384fd5b61234186828701611f49565b909790965060209590950135949350505050565b60006020808385031215612367578182fd5b825167ffffffffffffffff81111561237d578283fd5b80840185601f82011261238e578384fd5b8051915061239e611fb083612cee565b82815283810190828501858502840186018910156123ba578687fd5b8693505b848410156123dc5780518352600193909301929185019185016123be565b50979650505050505050565b6000602082840312156123f9578081fd5b813561065281612d6e565b600060208284031215612415578081fd5b815161065281612d6e565b600060208284031215612431578081fd5b5051919050565b600060208284031215612449578081fd5b5035919050565b60008284527f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff831115612481578081fd5b6020830280836020870137939093016020019283525090919050565b6000815180845260208085019450808401835b838110156124cc578151875295820195908201906001016124b0565b509495945050505050565b805160009060208084018383156124cc578151875295820195908201906001016124b0565b60006125088283612d0e565b60a0855261251a60a086018284612450565b6125276020860186612d0e565b93509150858103602087015261253e818484612450565b61254b6040870187612d0e565b945092508681036040880152612562818585612450565b9150506125726060860186612d0e565b935091508581036060870152612589818484612450565b608086013560808801528094505050505092915050565b60006125c76125c16125bb6125b5858c6124d7565b8a6124d7565b886124d7565b866124d7565b60609490941b7fffffffffffffffffffffffffffffffffffffffff00000000000000000000000016845250506014820152603401949350505050565b7f19457468657265756d205369676e6564204d6573736167653a0a3332000000008152601c810191909152603c0190565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b60006001600160a01b038089168352808816602084015250608060408301526126b3608083018688612450565b82810360608401526126c6818587612450565b9998505050505050505050565b60006001600160a01b03808816835280871660208401525060806040830152612700608083018587612450565b8281036060840152612712818561249d565b98975050505050505050565b6001600160a01b039290921682521515602082015260400190565b604080825284519082018190526000906020906060840190828801845b8281101561277b5781516001600160a01b031684529284019290840190600101612756565b50505083810382850152612790818688612450565b979650505050505050565b6000604082526127af604083018587612450565b9050826020830152949350505050565b600060a082526127d260a083018861249d565b82810360208401526127e4818861249d565b60408401969096525050606081019290925260809091015292915050565b901515815260200190565b93845260ff9290921660208401526040830152606082015260800190565b60208082526012908201527f4441495f49535f4e4f545f454e41424c45440000000000000000000000000000604082015260600190565b60208082526018908201527f44455354494e4154494f4e5f5a45524f5f414444524553530000000000000000604082015260600190565b60208082526015908201527f4e4f545f454e4f5547485f45544845525f53454e540000000000000000000000604082015260600190565b60208082526017908201527f5041594d454e545f5452414e534645525f4641494c4544000000000000000000604082015260600190565b60208082526013908201527f53414e445f49535f4e4f545f454e41424c454400000000000000000000000000604082015260600190565b60208082526014908201527f45544845525f49535f4e4f545f454e41424c4544000000000000000000000000604082015260600190565b60208082526013908201527f57414c4c45545f5a45524f5f4144445245535300000000000000000000000000604082015260600190565b60208082526010908201527f494e56414c49445f505552434841534500000000000000000000000000000000604082015260600190565b6020808252600d908201527f494e56414c49445f4e4f4e434500000000000000000000000000000000000000604082015260600190565b60208082526010908201527f53454e4445525f4e4f545f41444d494e00000000000000000000000000000000604082015260600190565b6020808252602e908201527f6f6e6c792061646d696e2063616e207365747570206d6574615472616e73616360408201527f74696f6e50726f636573736f7273000000000000000000000000000000000000606082015260800190565b6020808252600e908201527f494e56414c49445f53454e444552000000000000000000000000000000000000604082015260600190565b6020808252601b908201527f6f6e6c792061646d696e2063616e206368616e67652061646d696e0000000000604082015260600190565b60208082526008908201527f6f766572666c6f77000000000000000000000000000000000000000000000000604082015260600190565b6020808252600e908201527f4e4f545f415554484f52495a4544000000000000000000000000000000000000604082015260600190565b60208082526022908201527f44455354494e4154494f4e5f535441525445525041434b56315f434f4e54524160408201527f4354000000000000000000000000000000000000000000000000000000000000606082015260800190565b60208082526009908201527f64697662797a65726f0000000000000000000000000000000000000000000000604082015260600190565b600060808252612c3160808301876124fc565b6020830195909552506001600160a01b03929092166040830152606090910152919050565b6fffffffffffffffffffffffffffffffff91909116815260200190565b90815260200190565b6000808335601e19843603018112612c92578283fd5b8084018035925067ffffffffffffffff831115612cad578384fd5b6020810193505050602081023603821315611f8b57600080fd5b60405181810167ffffffffffffffff81118282101715612ce657600080fd5b604052919050565b600067ffffffffffffffff821115612d04578081fd5b5060209081020190565b6000808335601e19843603018112612d24578283fd5b830160208101925035905067ffffffffffffffff811115612d4457600080fd5b602081023603831315611f8b57600080fd5b6001600160a01b0381168114612d6b57600080fd5b50565b8015158114612d6b57600080fdfea26469706673582212200a7895316c434f4e35aecf13119547f69037d6dc656dacabe6bc83089ac2992164736f6c63430006050033
{"success": true, "error": null, "results": {"detectors": [{"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}]}
66
0x15a8153d292c4fb0571107aeda93ad26b7394d45
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); } contract sbEthFeePool { using SafeMath for uint256; bool public initDone; address public admin; address public pendingAdmin; address payable public superAdmin; address payable public pendingSuperAdmin; sbControllerInterface public sbController; sbStrongValuePoolInterface public sbStrongValuePool; IERC20 public strongToken; uint256 public superAdminFeeNumerator; uint256 public superAdminFeeDenominator; uint256 public logsSumFeeAmount; mapping(address => uint256[]) public logsContractFeeDays; mapping(address => uint256[]) public logsContractFeeAmounts; address public constant burnAddress = address( 0x000000000000000000000000000000000000dEaD ); function init( address sbControllerAddress, address sbStrongValuePoolAddress, address strongTokenAddress, address adminAddress, address payable superAdminAddress ) public { require(!initDone, "init done"); sbController = sbControllerInterface(sbControllerAddress); sbStrongValuePool = sbStrongValuePoolInterface( sbStrongValuePoolAddress ); strongToken = IERC20(strongTokenAddress); admin = adminAddress; superAdmin = superAdminAddress; initDone = true; } function updateSuperAdminFee(uint256 numerator, uint256 denominator) public { require(msg.sender == superAdmin); require(denominator != 0, "invalid value"); superAdminFeeNumerator = numerator; superAdminFeeDenominator = denominator; } function deposit() public payable { uint256 currentDay = _getCurrentDay(); uint256 len = logsContractFeeDays[msg.sender].length; if (len == 0) { logsContractFeeDays[msg.sender].push(currentDay); logsContractFeeAmounts[msg.sender].push(msg.value); } else { uint256 lastIndex = logsContractFeeDays[msg.sender].length.sub(1); uint256 lastDay = logsContractFeeDays[msg.sender][lastIndex]; if (lastDay == currentDay) { logsContractFeeAmounts[msg .sender][lastIndex] = logsContractFeeAmounts[msg .sender][lastIndex] .add(msg.value); } else { logsContractFeeDays[msg.sender].push(currentDay); logsContractFeeAmounts[msg.sender].push(msg.value); } } uint256 toSuperAdmin = msg.value.mul(superAdminFeeNumerator).div( superAdminFeeDenominator ); logsSumFeeAmount = logsSumFeeAmount.add(msg.value); superAdmin.transfer(toSuperAdmin); } 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 payable 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); } function getContractFeeData(address cntrct, uint256 dayNumber) public view returns (uint256, uint256) { uint256 day = dayNumber == 0 ? _getCurrentDay() : dayNumber; return _getContractFeeData(cntrct, day); } function _getContractFeeData(address cntrct, uint256 day) internal view returns (uint256, uint256) { uint256[] memory _Days = logsContractFeeDays[cntrct]; uint256[] memory _Amounts = logsContractFeeAmounts[cntrct]; return _get(_Days, _Amounts, day); } function _get( uint256[] memory _Days, uint256[] memory _Units, uint256 day ) internal pure returns (uint256, uint256) { uint256 len = _Days.length; if (len == 0) { return (day, 0); } if (day < _Days[0]) { return (day, 0); } uint256 lastIndex = len.sub(1); uint256 lastDay = _Days[lastIndex]; if (day == lastDay) { return (day, _Units[lastIndex]); } return _find(_Days, _Units, day); } function _find( uint256[] memory _Days, uint256[] memory _Units, uint256 day ) internal pure returns (uint256, uint256) { uint256 left = 0; uint256 right = _Days.length.sub(1); uint256 middle = right.add(left).div(2); while (_Days[middle] != day && left < right) { if (_Days[middle] > day) { right = middle.sub(1); } else if (_Days[middle] < day) { left = middle.add(1); } middle = right.add(left).div(2); } if (_Days[middle] != day) { return (day, 0); } else { return (day, _Units[middle]); } } function _getCurrentDay() internal view returns (uint256) { return block.timestamp.div(1 days).add(1); } } interface sbStrongValuePoolInterface { function mineFor(address miner, uint256 amount) external; function getMinerMineData(address miner, uint256 day) external view returns ( uint256, uint256, uint256 ); function getMineData(uint256 day) external view returns ( uint256, uint256, uint256 ); function serviceMinMined(address miner) external view returns (bool); function minerMinMined(address miner) external view returns (bool); }
0x6080604052600436106101355760003560e01c8063965d61b9116100ab578063d39ca7de1161006f578063d39ca7de1461036c578063e58eaf5b1461039f578063e7f9cefd146103d8578063f851a440146103ed578063fa371f8714610402578063fed0a20e1461043257610135565b8063965d61b9146102d3578063a4bd4840146102e8578063b30a7d84146102fd578063c92194011461034f578063d0e30db01461036457610135565b8063359ef75b116100fd578063359ef75b146101c157806348028d63146102165780634dd18bf51461022b57806363de7db31461025e5780636dfd8e1a146102a957806370d5ae05146102be57610135565b80630d65d00a1461013a5780630e18b6811461016b578063267822471461018257806329575f6a146101975780632fa41caf146101ac575b600080fd5b34801561014657600080fd5b5061014f61045b565b604080516001600160a01b039092168252519081900360200190f35b34801561017757600080fd5b5061018061046a565b005b34801561018e57600080fd5b5061014f6104f9565b3480156101a357600080fd5b5061014f610508565b3480156101b857600080fd5b5061014f610517565b3480156101cd57600080fd5b50610180600480360360a08110156101e457600080fd5b506001600160a01b03813581169160208101358216916040820135811691606081013582169160809091013516610526565b34801561022257600080fd5b5061014f6105e2565b34801561023757600080fd5b506101806004803603602081101561024e57600080fd5b50356001600160a01b03166105f1565b34801561026a57600080fd5b506102976004803603604081101561028157600080fd5b506001600160a01b038135169060200135610663565b60408051918252519081900360200190f35b3480156102b557600080fd5b50610297610691565b3480156102ca57600080fd5b5061014f610697565b3480156102df57600080fd5b5061014f61069d565b3480156102f457600080fd5b506102976106ac565b34801561030957600080fd5b506103366004803603604081101561032057600080fd5b506001600160a01b0381351690602001356106b2565b6040805192835260208301919091528051918290030190f35b34801561035b57600080fd5b506102976106e2565b6101806106e8565b34801561037857600080fd5b506101806004803603602081101561038f57600080fd5b50356001600160a01b03166108b9565b3480156103ab57600080fd5b50610297600480360360408110156103c257600080fd5b506001600160a01b03813516906020013561092b565b3480156103e457600080fd5b50610180610944565b3480156103f957600080fd5b5061014f6109cd565b34801561040e57600080fd5b506101806004803603604081101561042557600080fd5b50803590602001356109e1565b34801561043e57600080fd5b50610447610a45565b604080519115158252519081900360200190f35b6004546001600160a01b031681565b6001546001600160a01b03163314801561048357503315155b6104c7576040805162461bcd60e51b815260206004820152601060248201526f3737ba103832b73234b733a0b236b4b760811b604482015290519081900360640190fd5b6001805460008054610100600160a81b0319166101006001600160a01b038416021790556001600160a01b0319169055565b6001546001600160a01b031681565b6002546001600160a01b031681565b6005546001600160a01b031681565b60005460ff161561056a576040805162461bcd60e51b8152602060048201526009602482015268696e697420646f6e6560b81b604482015290519081900360640190fd5b600480546001600160a01b03199081166001600160a01b03978816179091556005805482169587169590951790945560068054851693861693909317909255600080546002805490951693861693909317909355610100600160a81b031990911661010091909316029190911760ff19166001179055565b6003546001600160a01b031681565b60005461010090046001600160a01b03163314610641576040805162461bcd60e51b81526020600482015260096024820152683737ba1030b236b4b760b91b604482015290519081900360640190fd5b600180546001600160a01b0319166001600160a01b0392909216919091179055565b600b602052816000526040600020818154811061067c57fe5b90600052602060002001600091509150505481565b60075481565b61dead81565b6006546001600160a01b031681565b60095481565b6000808083156106c257836106ca565b6106ca610a4e565b90506106d68582610a6d565b92509250509250929050565b60085481565b60006106f2610a4e565b336000908152600a60205260409020549091508061074c57336000818152600a6020908152604080832080546001818101835591855283852001879055938352600b82528220805493840181558252902034910155610843565b336000908152600a6020526040812054610767906001610b59565b336000908152600a60205260408120805492935090918390811061078757fe5b906000526020600020015490508381141561080257336000908152600b6020526040902080546107d6913491859081106107bd57fe5b9060005260206000200154610ba490919063ffffffff16565b336000908152600b602052604090208054849081106107f157fe5b600091825260209091200155610840565b336000818152600a6020908152604080832080546001818101835591855283852001899055938352600b825282208054938401815582529020349101555b50505b600061086660085461086060075434610bfe90919063ffffffff16565b90610c57565b6009549091506108769034610ba4565b6009556002546040516001600160a01b039091169082156108fc029083906000818181858888f193505050501580156108b3573d6000803e3d6000fd5b50505050565b6002546001600160a01b03163314610909576040805162461bcd60e51b815260206004820152600e60248201526d3737ba1039bab832b920b236b4b760911b604482015290519081900360640190fd5b600380546001600160a01b0319166001600160a01b0392909216919091179055565b600a602052816000526040600020818154811061067c57fe5b6003546001600160a01b03163314801561095d57503315155b6109a6576040805162461bcd60e51b81526020600482015260156024820152743737ba103832b73234b733a9bab832b920b236b4b760591b604482015290519081900360640190fd5b60038054600280546001600160a01b03199081166001600160a01b03841617909155169055565b60005461010090046001600160a01b031681565b6002546001600160a01b031633146109f857600080fd5b80610a3a576040805162461bcd60e51b815260206004820152600d60248201526c696e76616c69642076616c756560981b604482015290519081900360640190fd5b600791909155600855565b60005460ff1681565b6000610a686001610a624262015180610c57565b90610ba4565b905090565b6001600160a01b0382166000908152600a6020908152604080832080548251818502810185019093528083528493606093929190830182828015610ad057602002820191906000526020600020905b815481526020019060010190808311610abc575b5050506001600160a01b0388166000908152600b602090815260409182902080548351818402810184019094528084529596506060959294509250830182828015610b3a57602002820191906000526020600020905b815481526020019060010190808311610b26575b50505050509050610b4c828287610c99565b9350935050509250929050565b6000610b9b83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610d46565b90505b92915050565b600082820183811015610b9b576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b600082610c0d57506000610b9e565b82820282848281610c1a57fe5b0414610b9b5760405162461bcd60e51b8152600401808060200182810382526021815260200180610f3d6021913960400191505060405180910390fd5b6000610b9b83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250610ddd565b8251600090819080610cb2578360009250925050610d3e565b85600081518110610cbf57fe5b6020026020010151841015610cdb578360009250925050610d3e565b6000610ce8826001610b59565b90506000878281518110610cf857fe5b6020026020010151905080861415610d2b5785878381518110610d1757fe5b602002602001015194509450505050610d3e565b610d36888888610e42565b945094505050505b935093915050565b60008184841115610dd55760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610d9a578181015183820152602001610d82565b50505050905090810190601f168015610dc75780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b60008183610e2c5760405162461bcd60e51b8152602060048201818152835160248401528351909283926044909101919085019080838360008315610d9a578181015183820152602001610d82565b506000838581610e3857fe5b0495945050505050565b600080600080610e5d60018851610b5990919063ffffffff16565b90506000610e7060026108608486610ba4565b90505b85888281518110610e8057fe5b602002602001015114158015610e9557508183105b15610f065785888281518110610ea757fe5b60200260200101511115610ec757610ec0816001610b59565b9150610ef0565b85888281518110610ed457fe5b60200260200101511015610ef057610eed816001610ba4565b92505b610eff60026108608486610ba4565b9050610e73565b85888281518110610f1357fe5b602002602001015114610f2f5785600094509450505050610d3e565b85878281518110610d1757fefe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a2646970667358221220e0205e42631887c49669d4df5e8e6a3bb272d6c632b5dec773de6145db0d76ec64736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}]}
67
0x160710959a2ff50c4b8b981093aeecf66e4ca2f9
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } 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 sbTokens { event TokenAdded(address indexed token, address indexed oracle); event TokenPricesRecorded(uint256 indexed day); using SafeCast for int256; using SafeMath for uint256; bool internal initDone; uint16 internal constant PHASE_OFFSET = 64; address internal sbTimelock; address[] internal tokens; address[] internal oracles; mapping(address => uint16) internal oraclePhase; mapping(address => AggregatorV3Interface) internal priceFeeds; mapping(address => mapping(uint256 => uint256)) internal tokenDayPrice; mapping(address => uint64) internal tokenRoundLatest; mapping(address => uint256) internal tokenDayStart; uint256 internal dayLastRecordedPricesFor; function init( address sbTimelockAddress, address[] memory tokenAddresses, address[] memory oracleAddresses ) public { require(!initDone, 'init done'); // NOTE: ETH will be address(0) require(tokenAddresses.length == oracleAddresses.length, 'mismatch array lengths'); require(tokenAddresses.length > 0, 'zero'); sbTimelock = sbTimelockAddress; dayLastRecordedPricesFor = _getCurrentDay().sub(1); for (uint256 i = 0; i < tokenAddresses.length; i++) { _addToken(tokenAddresses[i], oracleAddresses[i]); } initDone = true; } function upToDate() external view returns (bool) { return dayLastRecordedPricesFor == _getCurrentDay().sub(1); } function addToken(address token, address oracle) external { require(msg.sender == sbTimelock, 'not sbTimelock'); require(token != address(0), 'token not zero address'); require(oracle != address(0), 'oracle not zero address'); require(oracle != token, 'token oracle not same'); require(!_tokenExists(token), 'token exists'); require(!_oracleExists(oracle), 'oracle exists'); _addToken(token, oracle); } function getTokens() external view returns (address[] memory) { return tokens; } function getTokenPrices(uint256 day) external view returns (uint256[] memory) { require(day <= dayLastRecordedPricesFor, 'invalid day'); uint256[] memory prices = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { address token = tokens[i]; prices[i] = tokenDayPrice[token][day]; } return prices; } function tokenAccepted(address token) external view returns (bool) { return _tokenExists(token); } function getTokenPrice(address token, uint256 day) external view returns (uint256) { require(_tokenExists(token), 'invalid token'); require(day >= tokenDayStart[token], '1: invalid day'); require(day <= dayLastRecordedPricesFor, '2: invalid day'); return tokenDayPrice[token][day]; } function getOracles() public view returns (address[] memory) { return oracles; } function getDayLastRecordedPricesFor() public view returns (uint256) { return dayLastRecordedPricesFor; } function getSbTimelockAddressUsed() public view returns (address) { return sbTimelock; } function getTokenRoundLatest(address token) public view returns (uint80) { require(_tokenExists(token), 'invalid token'); return _makeCombinedId(oraclePhase[token], tokenRoundLatest[token]); } function getTokenDayStart(address token) public view returns (uint256) { require(_tokenExists(token), 'invalid token'); return tokenDayStart[token]; } function getCurrentDay() public view returns (uint256) { return _getCurrentDay(); } function recordTokenPrices() public { require(_getCurrentDay() > dayLastRecordedPricesFor.add(1), 'already recorded'); dayLastRecordedPricesFor = dayLastRecordedPricesFor.add(1); for (uint256 i = 0; i < tokens.length; i++) { (uint80 roundId, , , , ) = priceFeeds[tokens[i]].latestRoundData(); (uint16 phase, ) = _getPhaseIdRoundId(roundId); if (oraclePhase[tokens[i]] != phase) { oraclePhase[tokens[i]] = phase; _cacheToken(tokens[i], _dayToTimestamp(dayLastRecordedPricesFor)); } tokenDayPrice[tokens[i]][dayLastRecordedPricesFor] = _getDayClosingPrice(tokens[i], dayLastRecordedPricesFor); } emit TokenPricesRecorded(dayLastRecordedPricesFor); } function _addToken(address token, address oracle) internal { tokens.push(token); oracles.push(oracle); priceFeeds[token] = AggregatorV3Interface(oracle); (uint80 roundId, , , , ) = priceFeeds[token].latestRoundData(); (uint16 phaseId, ) = _getPhaseIdRoundId(roundId); oraclePhase[token] = phaseId; uint256 currentDay = _getCurrentDay(); tokenDayStart[token] = currentDay; uint256 timestamp = _dayToTimestamp(currentDay.sub(1)); _cacheToken(token, timestamp); emit TokenAdded(token, oracle); } function _cacheToken(address token, uint256 timestamp) internal { tokenRoundLatest[token] = 1; uint64 roundId = _getRoundBeforeTimestamp(token, timestamp); tokenRoundLatest[token] = roundId; } function _getRoundBeforeTimestamp(address token, uint256 timestamp) internal view returns (uint64) { uint64 left = tokenRoundLatest[token]; (uint80 roundId, , , , ) = priceFeeds[token].latestRoundData(); (, uint64 right) = _getPhaseIdRoundId(roundId); uint64 middle = (right + left) / 2; while (left <= right) { roundId = _makeCombinedId(oraclePhase[token], middle); (, , , uint256 roundTimestamp, ) = priceFeeds[token].getRoundData(roundId); if (roundTimestamp == timestamp) { return middle - 1; } else if (roundTimestamp < timestamp) { left = middle + 1; } else { right = middle - 1; } middle = (right + left) / 2; } return middle; } function _getDayClosingPrice(address token, uint256 day) internal returns (uint256) { uint256 timestamp = _dayToTimestamp(day); uint64 roundId = _getRoundBeforeTimestamp(token, timestamp); tokenRoundLatest[token] = roundId; uint80 combinedId = _makeCombinedId(oraclePhase[token], roundId); (, int256 price, , , ) = priceFeeds[token].getRoundData(combinedId); uint256 priceUint256 = price.toUint256(); uint8 decimals = priceFeeds[token].decimals(); for (uint8 i = decimals; i < 18; i++) { priceUint256 = priceUint256.mul(10); } return priceUint256; } function _getCurrentDay() internal view returns (uint256) { return block.timestamp.div(1 days).add(1); } function _dayToTimestamp(uint256 day) internal pure returns (uint256) { return day.mul(1 days); } function _tokenExists(address token) internal view returns (bool) { for (uint256 i = 0; i < tokens.length; i++) { if (token == tokens[i]) { return true; } } return false; } function _oracleExists(address oracle) internal view returns (bool) { for (uint256 i = 0; i < oracles.length; i++) { if (oracle == oracles[i]) { return true; } } return false; } function _getPhaseIdRoundId(uint256 combinedId) internal pure returns (uint16, uint64) { return (uint16(combinedId >> PHASE_OFFSET), uint64(combinedId)); } function _makeCombinedId(uint80 phaseId, uint64 roundId) internal pure returns (uint80) { return (phaseId << PHASE_OFFSET) | roundId; } }
0x608060405234801561001057600080fd5b50600436106100ea5760003560e01c80636dba9b391161008c578063a761daec11610066578063a761daec146101c4578063aa6ca808146101d7578063aedf795e146101df578063c9f7153c146101f2576100ea565b80636dba9b391461017a578063782536041461019a578063a4bc4d7f146101af576100ea565b80633e6968b6116100c85780633e6968b61461014257806340884c521461014a57806346a305d01461015f5780635476bd7214610167576100ea565b80630bf52f9c146100ef57806329baa977146101045780633e5c0c861461012d575b600080fd5b6101026100fd366004611394565b610205565b005b610117610112366004611430565b610300565b604051610124919061151b565b60405180910390f35b6101356103e4565b60405161012491906118a0565b6101356103ea565b6101526103f9565b60405161012491906114ce565b61010261045b565b610102610175366004611360565b6106eb565b61018d610188366004611345565b6107f2565b60405161012491906118a9565b6101a261085c565b6040516101249190611553565b6101b7610874565b60405161012491906114ba565b6101356101d2366004611345565b610888565b6101526108cb565b6101a26101ed366004611345565b61092b565b610135610200366004611406565b610936565b60005460ff16156102315760405162461bcd60e51b81526004016102289061165a565b60405180910390fd5b80518251146102525760405162461bcd60e51b8152600401610228906116cf565b60008251116102735760405162461bcd60e51b8152600401610228906115d6565b60008054610100600160a81b0319166101006001600160a01b038616021790556102a660016102a06109e0565b906109fa565b60085560005b82518110156102ed576102e58382815181106102c457fe5b60200260200101518383815181106102d857fe5b6020026020010151610a43565b6001016102ac565b50506000805460ff191660011790555050565b60606008548211156103245760405162461bcd60e51b8152600401610228906115b1565b60015460609067ffffffffffffffff8111801561034057600080fd5b5060405190808252806020026020018201604052801561036a578160200160208202803683370190505b50905060005b6001548110156103db5760006001828154811061038957fe5b60009182526020808320909101546001600160a01b03168083526005825260408084208985529092529120548451919250908490849081106103c757fe5b602090810291909101015250600101610370565b5090505b919050565b60085490565b60006103f46109e0565b905090565b6060600280548060200260200160405190810160405280929190818152602001828054801561045157602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610433575b5050505050905090565b600854610469906001610c23565b6104716109e0565b1161048e5760405162461bcd60e51b81526004016102289061167d565b60085461049c906001610c23565b60085560005b6001548110156106bd57600060046000600184815481106104bf57fe5b60009182526020808320909101546001600160a01b0390811684529083019390935260409182019020548151633fabe5a360e21b8152915192169163feaf968c9160048082019260a092909190829003018186803b15801561052057600080fd5b505afa158015610534573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105589190611448565b5050505090506000610572826001600160501b0316610c48565b5090508061ffff16600360006001868154811061058b57fe5b60009182526020808320909101546001600160a01b0316835282019290925260400190205461ffff1614610640578060036000600186815481106105cb57fe5b6000918252602080832091909101546001600160a01b031683528201929092526040019020805461ffff191661ffff929092169190911790556001805461064091908590811061061757fe5b6000918252602090912001546008546001600160a01b039091169061063b90610c50565b610c5f565b6106706001848154811061065057fe5b6000918252602090912001546008546001600160a01b0390911690610cd1565b600560006001868154811061068157fe5b60009182526020808320909101546001600160a01b031683528281019390935260409182018120600854825290925290205550506001016104a2565b506008546040517e05cbf123ffbf07f1ecb68024e3171bdd0c2e627580fc2e43746c4e61fdee4b90600090a2565b60005461010090046001600160a01b0316331461071a5760405162461bcd60e51b815260040161022890611822565b6001600160a01b0382166107405760405162461bcd60e51b815260040161022890611870565b6001600160a01b0381166107665760405162461bcd60e51b8152600401610228906117eb565b816001600160a01b0316816001600160a01b031614156107985760405162461bcd60e51b81526004016102289061162b565b6107a182610ea1565b156107be5760405162461bcd60e51b81526004016102289061184a565b6107c781610ef6565b156107e45760405162461bcd60e51b8152600401610228906117c4565b6107ee8282610a43565b5050565b60006107fd82610ea1565b6108195760405162461bcd60e51b815260040161022890611775565b6001600160a01b0382166000908152600360209081526040808320546006909252909120546108569161ffff169067ffffffffffffffff16610f42565b92915050565b600061086b60016102a06109e0565b60085414905090565b60005461010090046001600160a01b031690565b600061089382610ea1565b6108af5760405162461bcd60e51b815260040161022890611775565b506001600160a01b031660009081526007602052604090205490565b60606001805480602002602001604051908101604052809291908181526020018280548015610451576020028201919060005260206000209081546001600160a01b03168152600190910190602001808311610433575050505050905090565b600061085682610ea1565b600061094183610ea1565b61095d5760405162461bcd60e51b815260040161022890611775565b6001600160a01b0383166000908152600760205260409020548210156109955760405162461bcd60e51b81526004016102289061179c565b6008548211156109b75760405162461bcd60e51b8152600401610228906116a7565b506001600160a01b03919091166000908152600560209081526040808320938352929052205490565b60006103f460016109f44262015180610f6a565b90610c23565b6000610a3c83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610fac565b9392505050565b6001805480820182557fb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf60180546001600160a01b03199081166001600160a01b038681169182179093556002805494850190557f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace9093018054821685841690811790915560009384526004602081905260408086208054909416909217928390558151633fabe5a360e21b81529151929093169263feaf968c928282019260a09290829003018186803b158015610b1957600080fd5b505afa158015610b2d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b519190611448565b5050505090506000610b6b826001600160501b0316610c48565b506001600160a01b0385166000908152600360205260408120805461ffff191661ffff8416179055909150610b9e6109e0565b6001600160a01b0386166000908152600760205260408120829055909150610bcf610bca8360016109fa565b610c50565b9050610bdb8682610c5f565b846001600160a01b0316866001600160a01b03167fdffbd9ded1c09446f09377de547142dcce7dc541c8b0b028142b1eba7026b9e760405160405180910390a3505050505050565b600082820183811015610a3c5760405162461bcd60e51b8152600401610228906115f4565b604081901c91565b60006108568262015180610fd8565b6001600160a01b0382166000908152600660205260408120805467ffffffffffffffff19166001179055610c938383611012565b6001600160a01b03939093166000908152600660205260409020805467ffffffffffffffff191667ffffffffffffffff909416939093179092555050565b600080610cdd83610c50565b90506000610ceb8583611012565b6001600160a01b0386166000908152600660209081526040808320805467ffffffffffffffff191667ffffffffffffffff8616179055600390915281205491925090610d3b9061ffff1683610f42565b6001600160a01b038088166000908152600460208190526040808320549051639a6fc8f560e01b815294955091939190921691639a6fc8f591610d80918691016118a9565b60a06040518083038186803b158015610d9857600080fd5b505afa158015610dac573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dd09190611448565b5050509150506000610de18261121f565b6001600160a01b03808a16600090815260046020818152604080842054815163313ce56760e01b815291519697509395939094169363313ce56793818401939091829003018186803b158015610e3657600080fd5b505afa158015610e4a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e6e9190611499565b9050805b60128160ff161015610e9357610e8983600a610fd8565b9250600101610e72565b509098975050505050505050565b6000805b600154811015610eed5760018181548110610ebc57fe5b6000918252602090912001546001600160a01b0384811691161415610ee55760019150506103df565b600101610ea5565b50600092915050565b6000805b600254811015610eed5760028181548110610f1157fe5b6000918252602090912001546001600160a01b0384811691161415610f3a5760019150506103df565b600101610efa565b67ffffffffffffffff1660409190911b71ffffffffffffffffffff0000000000000000161790565b6000610a3c83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250611245565b60008184841115610fd05760405162461bcd60e51b8152600401610228919061155e565b505050900390565b600082610fe757506000610856565b82820282848281610ff457fe5b0414610a3c5760405162461bcd60e51b815260040161022890611734565b6001600160a01b03808316600090815260066020908152604080832054600492839052818420548251633fabe5a360e21b81529251949567ffffffffffffffff909216948694919092169263feaf968c928183019260a092829003018186803b15801561107e57600080fd5b505afa158015611092573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110b69190611448565b50505050905060006110d0826001600160501b0316610c48565b9150506000600284830167ffffffffffffffff16816110eb57fe5b0490505b8167ffffffffffffffff168467ffffffffffffffff1611611215576001600160a01b0387166000908152600360205260409020546111319061ffff1682610f42565b6001600160a01b038089166000908152600460208190526040808320549051639a6fc8f560e01b815294975091939190921691639a6fc8f591611176918891016118a9565b60a06040518083038186803b15801561118e57600080fd5b505afa1580156111a2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111c69190611448565b509350505050868114156111e4575060001901935061085692505050565b868110156111f7578160010194506111fe565b6001820392505b5050600283820167ffffffffffffffff16046110ef565b9695505050505050565b6000808212156112415760405162461bcd60e51b8152600401610228906116ff565b5090565b600081836112665760405162461bcd60e51b8152600401610228919061155e565b50600083858161127257fe5b0495945050505050565b80356001600160a01b038116811461085657600080fd5b600082601f8301126112a3578081fd5b813567ffffffffffffffff808211156112ba578283fd5b6020808302604051828282010181811085821117156112d7578687fd5b6040528481529450818501925085820181870183018810156112f857600080fd5b600091505b848210156113235761130f888261127c565b8452928201926001919091019082016112fd565b505050505092915050565b80516001600160501b038116811461085657600080fd5b600060208284031215611356578081fd5b610a3c838361127c565b60008060408385031215611372578081fd5b61137c848461127c565b915061138b846020850161127c565b90509250929050565b6000806000606084860312156113a8578081fd5b6113b2858561127c565b9250602084013567ffffffffffffffff808211156113ce578283fd5b6113da87838801611293565b935060408601359150808211156113ef578283fd5b506113fc86828701611293565b9150509250925092565b60008060408385031215611418578182fd5b611422848461127c565b946020939093013593505050565b600060208284031215611441578081fd5b5035919050565b600080600080600060a0868803121561145f578081fd5b611469878761132e565b945060208601519350604086015192506060860151915061148d876080880161132e565b90509295509295909350565b6000602082840312156114aa578081fd5b815160ff81168114610a3c578182fd5b6001600160a01b0391909116815260200190565b6020808252825182820181905260009190848201906040850190845b8181101561150f5783516001600160a01b0316835292840192918401916001016114ea565b50909695505050505050565b6020808252825182820181905260009190848201906040850190845b8181101561150f57835183529284019291840191600101611537565b901515815260200190565b6000602080835283518082850152825b8181101561158a5785810183015185820160400152820161156e565b8181111561159b5783604083870101525b50601f01601f1916929092016040019392505050565b6020808252600b908201526a696e76616c69642064617960a81b604082015260600190565b6020808252600490820152637a65726f60e01b604082015260600190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b602080825260159082015274746f6b656e206f7261636c65206e6f742073616d6560581b604082015260600190565b602080825260099082015268696e697420646f6e6560b81b604082015260600190565b60208082526010908201526f185b1c9958591e481c9958dbdc99195960821b604082015260600190565b6020808252600e908201526d323a20696e76616c69642064617960901b604082015260600190565b6020808252601690820152756d69736d61746368206172726179206c656e6774687360501b604082015260600190565b6020808252818101527f53616665436173743a2076616c7565206d75737420626520706f736974697665604082015260600190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b6020808252600d908201526c34b73b30b634b2103a37b5b2b760991b604082015260600190565b6020808252600e908201526d313a20696e76616c69642064617960901b604082015260600190565b6020808252600d908201526c6f7261636c652065786973747360981b604082015260600190565b60208082526017908201527f6f7261636c65206e6f74207a65726f2061646472657373000000000000000000604082015260600190565b6020808252600e908201526d6e6f7420736254696d656c6f636b60901b604082015260600190565b6020808252600c908201526b746f6b656e2065786973747360a01b604082015260600190565b602080825260169082015275746f6b656e206e6f74207a65726f206164647265737360501b604082015260600190565b90815260200190565b6001600160501b039190911681526020019056fea2646970667358221220527bfca9b06caf99a26675a32320121c0c33175a4f9f851e4639c72097d41ca164736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}]}
68
0x163fd6af6ec3822aaf9c4127e9f75180d96715b7
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 HarvestStakingAdapter is ProtocolAdapter { string public constant override adapterType = "Asset"; string public constant override tokenType = "ERC20"; address internal constant FARM = 0xa0246c9032bC3A600820415aE600c6388619A14D; address internal constant UNI_FARM_USDC = 0x514906FC121c7878424a5C928cad1852CC545892; address internal constant F_WBTC = 0x5d9d25c7C457dD82fc8668FFC6B9746b674d4EcB; address internal constant F_WETH = 0xFE09e53A81Fe2808bc493ea64319109B5bAa573e; address internal constant F_DAI = 0xab7FA2B2985BCcfC13c6D86b1D5A17486ab1e04C; address internal constant F_USDC = 0xf0358e8c3CD5Fa238a29301d0bEa3D63A17bEdBE; address internal constant F_USDT = 0x053c80eA73Dc6941F518a68E2FC52Ac45BDE7c9C; address internal constant F_RENBTC = 0xC391d1b08c1403313B0c28D47202DFDA015633C4; address internal constant F_CRV_RENWBTC = 0x9aA8F427A17d6B0d91B6262989EdC7D45d6aEdf8; address internal constant F_UNI_WETH_USDT = 0x7DDc3ffF0612E75Ea5ddC0d6Bd4e268f70362Cff; address internal constant F_UNI_WETH_USDC = 0xA79a083FDD87F73c2f983c5551EC974685D6bb36; address internal constant F_UNI_WETH_DAI = 0x307E2752e8b8a9C29005001Be66B1c012CA9CDB7; address internal constant F_UNI_WETH_WBTC = 0x01112a60f427205dcA6E229425306923c3Cc2073; address internal constant F_TUSD = 0x7674622c63Bee7F46E86a4A5A18976693D54441b; address internal constant F_SUSHI_WBTC_TBTC = 0xF553E1f826f42716cDFe02bde5ee76b2a52fc7EB; address internal constant FARM_POOL = 0x8f5adC58b32D4e5Ca02EAC0E293D35855999436C; address internal constant UNI_FARM_USDC_POOL = 0x99b0d6641A63Ce173E6EB063b3d3AED9A35Cf9bf; address internal constant F_WBTC_POOL = 0x917d6480Ec60cBddd6CbD0C8EA317Bcc709EA77B; address internal constant F_WETH_POOL = 0x3DA9D911301f8144bdF5c3c67886e5373DCdff8e; address internal constant F_DAI_POOL = 0x15d3A64B2d5ab9E152F16593Cdebc4bB165B5B4A; address internal constant F_USDC_POOL = 0x4F7c28cCb0F1Dbd1388209C67eEc234273C878Bd; address internal constant F_USDT_POOL = 0x6ac4a7AB91E6fD098E13B7d347c6d4d1494994a2; address internal constant F_RENBTC_POOL = 0x7b8Ff8884590f44e10Ea8105730fe637Ce0cb4F6; address internal constant F_CRV_RENWBTC_POOL = 0xA3Cf8D1CEe996253FAD1F8e3d68BDCba7B3A3Db5; address internal constant F_UNI_WETH_USDT_POOL = 0x75071F2653fBC902EBaff908d4c68712a5d1C960; address internal constant F_UNI_WETH_USDC_POOL = 0x156733b89Ac5C704F3217FEe2949A9D4A73764b5; address internal constant F_UNI_WETH_DAI_POOL = 0x7aeb36e22e60397098C2a5C51f0A5fB06e7b859c; address internal constant F_UNI_WETH_WBTC_POOL = 0xF1181A71CC331958AE2cA2aAD0784Acfc436CB93; address internal constant F_TUSD_POOL = 0xeC56a21CF0D7FeB93C25587C12bFfe094aa0eCdA; address internal constant F_SUSHI_WBTC_TBTC_POOL = 0x9523FdC055F503F73FF40D7F66850F409D80EF34; /** * @return Amount of staked tokens / rewards earned after staking for a given account. * @dev Implementation of ProtocolAdapter interface function. */ function getBalance(address token, address account) external view override returns (uint256) { if (token == FARM) { uint256 totalRewards = 0; totalRewards += ERC20(FARM_POOL).balanceOf(account); totalRewards += StakingRewards(FARM_POOL).earned(account); totalRewards += StakingRewards(UNI_FARM_USDC_POOL).earned(account); totalRewards += StakingRewards(F_WBTC_POOL).earned(account); totalRewards += StakingRewards(F_WETH_POOL).earned(account); totalRewards += StakingRewards(F_DAI_POOL).earned(account); totalRewards += StakingRewards(F_USDC_POOL).earned(account); totalRewards += StakingRewards(F_USDT_POOL).earned(account); totalRewards += StakingRewards(F_RENBTC_POOL).earned(account); totalRewards += StakingRewards(F_CRV_RENWBTC_POOL).earned(account); totalRewards += StakingRewards(F_UNI_WETH_USDT_POOL).earned(account); totalRewards += StakingRewards(F_UNI_WETH_USDC_POOL).earned(account); totalRewards += StakingRewards(F_UNI_WETH_DAI_POOL).earned(account); totalRewards += StakingRewards(F_UNI_WETH_WBTC_POOL).earned(account); totalRewards += StakingRewards(F_TUSD_POOL).earned(account); totalRewards += StakingRewards(F_SUSHI_WBTC_TBTC_POOL).earned(account); return totalRewards; } else if (token == UNI_FARM_USDC) { return ERC20(UNI_FARM_USDC_POOL).balanceOf(account); } else if (token == F_WBTC) { return ERC20(F_WBTC_POOL).balanceOf(account); } else if (token == F_WETH) { return ERC20(F_WETH_POOL).balanceOf(account); } else if (token == F_DAI) { return ERC20(F_DAI_POOL).balanceOf(account); } else if (token == F_USDC) { return ERC20(F_USDC_POOL).balanceOf(account); } else if (token == F_USDT) { return ERC20(F_USDT_POOL).balanceOf(account); } else if (token == F_RENBTC) { return ERC20(F_RENBTC_POOL).balanceOf(account); } else if (token == F_CRV_RENWBTC) { return ERC20(F_CRV_RENWBTC_POOL).balanceOf(account); } else if (token == F_UNI_WETH_USDT) { return ERC20(F_UNI_WETH_USDT_POOL).balanceOf(account); } else if (token == F_UNI_WETH_USDC) { return ERC20(F_UNI_WETH_USDC_POOL).balanceOf(account); } else if (token == F_UNI_WETH_DAI) { return ERC20(F_UNI_WETH_DAI_POOL).balanceOf(account); } else if (token == F_UNI_WETH_WBTC) { return ERC20(F_UNI_WETH_WBTC_POOL).balanceOf(account); } else if (token == F_TUSD) { return ERC20(F_TUSD_POOL).balanceOf(account); } else if (token == F_SUSHI_WBTC_TBTC) { return ERC20(F_SUSHI_WBTC_TBTC_POOL).balanceOf(account); } else { return 0; } } }
0x608060405234801561001057600080fd5b50600436106100415760003560e01c806330fa738c14610046578063d4fac45d14610064578063f72c079114610084575b600080fd5b61004e61008c565b60405161005b919061135a565b60405180910390f35b6100776100723660046112ed565b6100c5565b60405161005b91906113cb565b61004e611290565b6040518060400160405280600581526020017f455243323000000000000000000000000000000000000000000000000000000081525081565b600073ffffffffffffffffffffffffffffffffffffffff831673a0246c9032bc3a600820415ae600c6388619a14d1415610b13576040517f70a08231000000000000000000000000000000000000000000000000000000008152600090738f5adc58b32d4e5ca02eac0e293d35855999436c906370a082319061014c908690600401611339565b60206040518083038186803b15801561016457600080fd5b505afa158015610178573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061019c9190611321565b6040517e8cc262000000000000000000000000000000000000000000000000000000008152910190738f5adc58b32d4e5ca02eac0e293d35855999436c90628cc262906101ed908690600401611339565b60206040518083038186803b15801561020557600080fd5b505afa158015610219573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061023d9190611321565b6040517e8cc2620000000000000000000000000000000000000000000000000000000081529101907399b0d6641a63ce173e6eb063b3d3aed9a35cf9bf90628cc2629061028e908690600401611339565b60206040518083038186803b1580156102a657600080fd5b505afa1580156102ba573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102de9190611321565b6040517e8cc26200000000000000000000000000000000000000000000000000000000815291019073917d6480ec60cbddd6cbd0c8ea317bcc709ea77b90628cc2629061032f908690600401611339565b60206040518083038186803b15801561034757600080fd5b505afa15801561035b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061037f9190611321565b6040517e8cc262000000000000000000000000000000000000000000000000000000008152910190733da9d911301f8144bdf5c3c67886e5373dcdff8e90628cc262906103d0908690600401611339565b60206040518083038186803b1580156103e857600080fd5b505afa1580156103fc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104209190611321565b6040517e8cc2620000000000000000000000000000000000000000000000000000000081529101907315d3a64b2d5ab9e152f16593cdebc4bb165b5b4a90628cc26290610471908690600401611339565b60206040518083038186803b15801561048957600080fd5b505afa15801561049d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104c19190611321565b6040517e8cc262000000000000000000000000000000000000000000000000000000008152910190734f7c28ccb0f1dbd1388209c67eec234273c878bd90628cc26290610512908690600401611339565b60206040518083038186803b15801561052a57600080fd5b505afa15801561053e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105629190611321565b6040517e8cc262000000000000000000000000000000000000000000000000000000008152910190736ac4a7ab91e6fd098e13b7d347c6d4d1494994a290628cc262906105b3908690600401611339565b60206040518083038186803b1580156105cb57600080fd5b505afa1580156105df573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106039190611321565b6040517e8cc262000000000000000000000000000000000000000000000000000000008152910190737b8ff8884590f44e10ea8105730fe637ce0cb4f690628cc26290610654908690600401611339565b60206040518083038186803b15801561066c57600080fd5b505afa158015610680573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106a49190611321565b6040517e8cc26200000000000000000000000000000000000000000000000000000000815291019073a3cf8d1cee996253fad1f8e3d68bdcba7b3a3db590628cc262906106f5908690600401611339565b60206040518083038186803b15801561070d57600080fd5b505afa158015610721573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107459190611321565b6040517e8cc2620000000000000000000000000000000000000000000000000000000081529101907375071f2653fbc902ebaff908d4c68712a5d1c96090628cc26290610796908690600401611339565b60206040518083038186803b1580156107ae57600080fd5b505afa1580156107c2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107e69190611321565b6040517e8cc26200000000000000000000000000000000000000000000000000000000815291019073156733b89ac5c704f3217fee2949a9d4a73764b590628cc26290610837908690600401611339565b60206040518083038186803b15801561084f57600080fd5b505afa158015610863573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108879190611321565b6040517e8cc262000000000000000000000000000000000000000000000000000000008152910190737aeb36e22e60397098c2a5c51f0a5fb06e7b859c90628cc262906108d8908690600401611339565b60206040518083038186803b1580156108f057600080fd5b505afa158015610904573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109289190611321565b6040517e8cc26200000000000000000000000000000000000000000000000000000000815291019073f1181a71cc331958ae2ca2aad0784acfc436cb9390628cc26290610979908690600401611339565b60206040518083038186803b15801561099157600080fd5b505afa1580156109a5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109c99190611321565b6040517e8cc26200000000000000000000000000000000000000000000000000000000815291019073ec56a21cf0d7feb93c25587c12bffe094aa0ecda90628cc26290610a1a908690600401611339565b60206040518083038186803b158015610a3257600080fd5b505afa158015610a46573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a6a9190611321565b6040517e8cc262000000000000000000000000000000000000000000000000000000008152910190739523fdc055f503f73ff40d7f66850f409d80ef3490628cc26290610abb908690600401611339565b60206040518083038186803b158015610ad357600080fd5b505afa158015610ae7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b0b9190611321565b01905061128a565b73ffffffffffffffffffffffffffffffffffffffff831673514906fc121c7878424a5c928cad1852cc5458921415610bec576040517f70a082310000000000000000000000000000000000000000000000000000000081527399b0d6641a63ce173e6eb063b3d3aed9a35cf9bf906370a0823190610b95908590600401611339565b60206040518083038186803b158015610bad57600080fd5b505afa158015610bc1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610be59190611321565b905061128a565b73ffffffffffffffffffffffffffffffffffffffff8316735d9d25c7c457dd82fc8668ffc6b9746b674d4ecb1415610c6e576040517f70a0823100000000000000000000000000000000000000000000000000000000815273917d6480ec60cbddd6cbd0c8ea317bcc709ea77b906370a0823190610b95908590600401611339565b73ffffffffffffffffffffffffffffffffffffffff831673fe09e53a81fe2808bc493ea64319109b5baa573e1415610cf0576040517f70a08231000000000000000000000000000000000000000000000000000000008152733da9d911301f8144bdf5c3c67886e5373dcdff8e906370a0823190610b95908590600401611339565b73ffffffffffffffffffffffffffffffffffffffff831673ab7fa2b2985bccfc13c6d86b1d5a17486ab1e04c1415610d72576040517f70a082310000000000000000000000000000000000000000000000000000000081527315d3a64b2d5ab9e152f16593cdebc4bb165b5b4a906370a0823190610b95908590600401611339565b73ffffffffffffffffffffffffffffffffffffffff831673f0358e8c3cd5fa238a29301d0bea3d63a17bedbe1415610df4576040517f70a08231000000000000000000000000000000000000000000000000000000008152734f7c28ccb0f1dbd1388209c67eec234273c878bd906370a0823190610b95908590600401611339565b73ffffffffffffffffffffffffffffffffffffffff831673053c80ea73dc6941f518a68e2fc52ac45bde7c9c1415610e76576040517f70a08231000000000000000000000000000000000000000000000000000000008152736ac4a7ab91e6fd098e13b7d347c6d4d1494994a2906370a0823190610b95908590600401611339565b73ffffffffffffffffffffffffffffffffffffffff831673c391d1b08c1403313b0c28d47202dfda015633c41415610ef8576040517f70a08231000000000000000000000000000000000000000000000000000000008152737b8ff8884590f44e10ea8105730fe637ce0cb4f6906370a0823190610b95908590600401611339565b73ffffffffffffffffffffffffffffffffffffffff8316739aa8f427a17d6b0d91b6262989edc7d45d6aedf81415610f7a576040517f70a0823100000000000000000000000000000000000000000000000000000000815273a3cf8d1cee996253fad1f8e3d68bdcba7b3a3db5906370a0823190610b95908590600401611339565b73ffffffffffffffffffffffffffffffffffffffff8316737ddc3fff0612e75ea5ddc0d6bd4e268f70362cff1415610ffc576040517f70a082310000000000000000000000000000000000000000000000000000000081527375071f2653fbc902ebaff908d4c68712a5d1c960906370a0823190610b95908590600401611339565b73ffffffffffffffffffffffffffffffffffffffff831673a79a083fdd87f73c2f983c5551ec974685d6bb36141561107e576040517f70a0823100000000000000000000000000000000000000000000000000000000815273156733b89ac5c704f3217fee2949a9d4a73764b5906370a0823190610b95908590600401611339565b73ffffffffffffffffffffffffffffffffffffffff831673307e2752e8b8a9c29005001be66b1c012ca9cdb71415611100576040517f70a08231000000000000000000000000000000000000000000000000000000008152737aeb36e22e60397098c2a5c51f0a5fb06e7b859c906370a0823190610b95908590600401611339565b73ffffffffffffffffffffffffffffffffffffffff83167301112a60f427205dca6e229425306923c3cc20731415611182576040517f70a0823100000000000000000000000000000000000000000000000000000000815273f1181a71cc331958ae2ca2aad0784acfc436cb93906370a0823190610b95908590600401611339565b73ffffffffffffffffffffffffffffffffffffffff8316737674622c63bee7f46e86a4a5a18976693d54441b1415611204576040517f70a0823100000000000000000000000000000000000000000000000000000000815273ec56a21cf0d7feb93c25587c12bffe094aa0ecda906370a0823190610b95908590600401611339565b73ffffffffffffffffffffffffffffffffffffffff831673f553e1f826f42716cdfe02bde5ee76b2a52fc7eb1415611286576040517f70a08231000000000000000000000000000000000000000000000000000000008152739523fdc055f503f73ff40d7f66850f409d80ef34906370a0823190610b95908590600401611339565b5060005b92915050565b6040518060400160405280600581526020017f417373657400000000000000000000000000000000000000000000000000000081525081565b803573ffffffffffffffffffffffffffffffffffffffff8116811461128a57600080fd5b600080604083850312156112ff578182fd5b61130984846112c9565b915061131884602085016112c9565b90509250929050565b600060208284031215611332578081fd5b5051919050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b6000602080835283518082850152825b818110156113865785810183015185820160400152820161136a565b818111156113975783604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b9081526020019056fea264697066735822122099ba073257228b5e0290072c64c4a9069b00c3d8e492291a36e81f35555781b464736f6c63430006050033
{"success": true, "error": null, "results": {}}
true
null
{}
69
0x165eec91620b7bb96d02890d8a3f8cb79a29195c
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; } } 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()); } } } 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 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)); } } contract DigitalaxAccessControls is AccessControl { /// @notice Role definitions bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE"); /// @notice Events for adding and removing various roles event AdminRoleGranted( address indexed beneficiary, address indexed caller ); event AdminRoleRemoved( address indexed beneficiary, address indexed caller ); event MinterRoleGranted( address indexed beneficiary, address indexed caller ); event MinterRoleRemoved( address indexed beneficiary, address indexed caller ); event SmartContractRoleGranted( address indexed beneficiary, address indexed caller ); event SmartContractRoleRemoved( address indexed beneficiary, address indexed caller ); /** * @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses */ constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the admin role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasAdminRole(address _address) external view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _address); } /** * @notice Used to check whether an address has the minter role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasMinterRole(address _address) external view returns (bool) { return hasRole(MINTER_ROLE, _address); } /** * @notice Used to check whether an address has the smart contract role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasSmartContractRole(address _address) external view returns (bool) { return hasRole(SMART_CONTRACT_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the admin role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addAdminRole(address _address) external { grantRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleGranted(_address, _msgSender()); } /** * @notice Removes the admin role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeAdminRole(address _address) external { revokeRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleRemoved(_address, _msgSender()); } /** * @notice Grants the minter role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addMinterRole(address _address) external { grantRole(MINTER_ROLE, _address); emit MinterRoleGranted(_address, _msgSender()); } /** * @notice Removes the minter role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeMinterRole(address _address) external { revokeRole(MINTER_ROLE, _address); emit MinterRoleRemoved(_address, _msgSender()); } /** * @notice Grants the smart contract role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addSmartContractRole(address _address) external { grantRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleGranted(_address, _msgSender()); } /** * @notice Removes the smart contract role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeSmartContractRole(address _address) external { revokeRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleRemoved(_address, _msgSender()); } }
0x608060405234801561001057600080fd5b50600436106101215760003560e01c80638a845fc0116100ad578063c395fcb311610071578063c395fcb314610348578063ca15c8731461036e578063d53913931461038b578063d547741f14610393578063dccfe310146103bf57610121565b80638a845fc0146102895780639010d07c146102af57806391d14854146102ee578063a217fddf1461031a578063adbf37761461032257610121565b806336568abe116100f457806336568abe146101e35780633f16431a1461020f57806354f1e126146102355780636595171c1461025b578063857d26081461028157610121565b8063099db01714610126578063113b0ab214610160578063248a9ca3146101865780632f2ff15d146101b5575b600080fd5b61014c6004803603602081101561013c57600080fd5b50356001600160a01b03166103e5565b604080519115158252519081900360200190f35b61014c6004803603602081101561017657600080fd5b50356001600160a01b0316610405565b6101a36004803603602081101561019c57600080fd5b503561041f565b60408051918252519081900360200190f35b6101e1600480360360408110156101cb57600080fd5b50803590602001356001600160a01b0316610434565b005b6101e1600480360360408110156101f957600080fd5b50803590602001356001600160a01b03166104a0565b6101e16004803603602081101561022557600080fd5b50356001600160a01b0316610501565b6101e16004803603602081101561024b57600080fd5b50356001600160a01b0316610563565b6101e16004803603602081101561027157600080fd5b50356001600160a01b03166105c5565b6101a361061a565b6101e16004803603602081101561029f57600080fd5b50356001600160a01b031661062c565b6102d2600480360360408110156102c557600080fd5b508035906020013561068e565b604080516001600160a01b039092168252519081900360200190f35b61014c6004803603604081101561030457600080fd5b50803590602001356001600160a01b03166106ad565b6101a36106c5565b6101e16004803603602081101561033857600080fd5b50356001600160a01b03166106ca565b61014c6004803603602081101561035e57600080fd5b50356001600160a01b031661072c565b6101a36004803603602081101561038457600080fd5b5035610738565b6101a361074f565b6101e1600480360360408110156103a957600080fd5b50803590602001356001600160a01b0316610761565b6101e1600480360360208110156103d557600080fd5b50356001600160a01b03166107ba565b60006103ff600080516020610b6d833981519152836106ad565b92915050565b60006103ff600080516020610b1d833981519152836106ad565b60009081526020819052604090206002015490565b60008281526020819052604090206002015461045790610452610824565b6106ad565b6104925760405162461bcd60e51b815260040180806020018281038252602f815260200180610aee602f913960400191505060405180910390fd5b61049c8282610828565b5050565b6104a8610824565b6001600160a01b0316816001600160a01b0316146104f75760405162461bcd60e51b815260040180806020018281038252602f815260200180610b8d602f913960400191505060405180910390fd5b61049c8282610891565b610519600080516020610b1d83398151915282610434565b610521610824565b6001600160a01b0316816001600160a01b03167f1d5f9ec24c6f91be922ea13ceaad919ad6554a41b5c26087f96289a9baf98ad260405160405180910390a350565b61057b600080516020610b6d83398151915282610761565b610583610824565b6001600160a01b0316816001600160a01b03167f56692a161ffec953ddf9def93b958ea8d1ec95e21b80870c66be91a4374dc4e360405160405180910390a350565b6105d0600082610434565b6105d8610824565b6001600160a01b0316816001600160a01b03167f2570ac42fd8b322dc453ada624dc2ed0e9bdd67f16f201a25bbd30468f2aa18760405160405180910390a350565b600080516020610b1d83398151915281565b610644600080516020610b1d83398151915282610761565b61064c610824565b6001600160a01b0316816001600160a01b03167fe5f1aa9e528307345194b88b24a32401c13926e0823060f1049d9b26c0bb62b260405160405180910390a350565b60008281526020819052604081206106a690836108fa565b9392505050565b60008281526020819052604081206106a69083610906565b600081565b6106e2600080516020610b6d83398151915282610434565b6106ea610824565b6001600160a01b0316816001600160a01b03167f0be6ab9784c7401fafb73f7bc47bc67cc4ef8c47a60ad3cb66d1de0353a0784c60405160405180910390a350565b60006103ff81836106ad565b60008181526020819052604081206103ff9061091b565b600080516020610b6d83398151915281565b60008281526020819052604090206002015461077f90610452610824565b6104f75760405162461bcd60e51b8152600401808060200182810382526030815260200180610b3d6030913960400191505060405180910390fd5b6107c5600082610761565b6107cd610824565b6001600160a01b0316816001600160a01b03167f21ba1239795d4e22874e3dc55f0a9d7b65bfb23069d32965d7c23be9524ccf9560405160405180910390a350565b60006106a6836001600160a01b038416610926565b3390565b6000828152602081905260409020610840908261080f565b1561049c5761084d610824565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60008281526020819052604090206108a99082610970565b1561049c576108b6610824565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b60006106a68383610985565b60006106a6836001600160a01b0384166109e9565b60006103ff82610a01565b600061093283836109e9565b610968575081546001818101845560008481526020808220909301849055845484825282860190935260409020919091556103ff565b5060006103ff565b60006106a6836001600160a01b038416610a05565b815460009082106109c75760405162461bcd60e51b8152600401808060200182810382526022815260200180610acc6022913960400191505060405180910390fd5b8260000182815481106109d657fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b5490565b60008181526001830160205260408120548015610ac15783546000198083019190810190600090879083908110610a3857fe5b9060005260206000200154905080876000018481548110610a5557fe5b600091825260208083209091019290925582815260018981019092526040902090840190558654879080610a8557fe5b600190038181906000526020600020016000905590558660010160008781526020019081526020016000206000905560019450505050506103ff565b60009150506103ff56fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e6473416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f206772616e749d49f397ae9ef1a834b569acb967799a367061e305932181a44f5773da873bfd416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f207265766f6b659f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a6416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636520726f6c657320666f722073656c66a2646970667358221220339fe81d4a13099776b4763d3ead4dcca9d74be0b246a4b6bcf6dc8781c8fd7a64736f6c634300060c0033
{"success": true, "error": null, "results": {}}
true
null
{}
70
0x16ca223aBe5E439942ba70620d90d3Ce8aeBFf7F
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract sbGovernor { // 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 pure returns (uint256) { return 400000e18; } // 400,000 = 4% of STRONG // The number of votes required in order for a voter to become a proposer function proposalThreshold() public pure returns (uint256) { return 100000e18; } // 100,000 = 1% of STRONG // The maximum number of actions that can be included in a proposal function proposalMaxOperations() public pure returns (uint256) { return 10; } // 10 actions // The delay before voting on a proposal may take place, once proposed function votingDelay() public pure returns (uint256) { return 1; } // 1 block // The duration of voting on a proposal, in blocks function votingPeriod() public pure returns (uint256) { return 17280; } // ~3 days in blocks (assuming 15s blocks) // The address of the StrongBlock Protocol Timelock sbTimelockInterface public sbTimelock; // The address of the sbVotes contract sbVotesInterface public sbVotes; // The address of the Governor Guardian address public guardian; // The total number of proposals uint256 public proposalCount; struct Proposal { // Unique id for looking up a proposal uint256 id; // Creator of the proposal address proposer; // The timestamp that the proposal will be available for execution, set once the vote succeeds uint256 eta; // the ordered list of target addresses for calls to be made address[] targets; // The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint256[] values; // The ordered list of function signatures to be called string[] signatures; // The ordered list of calldata to be passed to each call bytes[] calldatas; // The block at which voting begins: holders must delegate their votes prior to this block uint256 startBlock; // The block at which voting ends: votes must be cast prior to this block uint256 endBlock; // Current number of votes in favor of this proposal uint256 forVotes; // Current number of votes in opposition to this proposal uint256 againstVotes; // Flag marking whether the proposal has been canceled bool canceled; // Flag marking whether the proposal has been executed bool executed; // Receipts of ballots for the entire set of voters mapping(address => Receipt) receipts; } // Ballot receipt record for a voter struct Receipt { // Whether or not a vote has been cast bool hasVoted; // Whether or not the voter supports the proposal bool support; // The number of votes the voter had, which were cast uint96 votes; } // Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } // The official record of all proposals ever proposed mapping(uint256 => Proposal) public proposals; // The latest proposal for each proposer mapping(address => uint256) public latestProposalIds; // An event emitted when a new proposal is created event ProposalCreated( uint256 id, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); // An event emitted when a vote has been cast on a proposal event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes); // An event emitted when a proposal has been canceled event ProposalCanceled(uint256 id); // An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint256 id, uint256 eta); // An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint256 id); constructor( address sbTimelockAddress, address sbVotesAddress, address guardian_ ) public { sbTimelock = sbTimelockInterface(sbTimelockAddress); sbVotes = sbVotesInterface(sbVotesAddress); guardian = guardian_; } 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, sub256(block.number, 1)) > proposalThreshold(), 'sbGovernor::propose: proposer votes below proposal threshold' ); require( targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, 'sbGovernor::propose: proposal function information arity mismatch' ); require(targets.length != 0, 'sbGovernor::propose: must provide actions'); require(targets.length <= proposalMaxOperations(), 'sbGovernor::propose: too many actions'); uint256 latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require( proposersLatestProposalState != ProposalState.Active, 'sbGovernor::propose: one live proposal per proposer, found an already active proposal' ); require( proposersLatestProposalState != ProposalState.Pending, 'sbGovernor::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, 'sbGovernor::queue: proposal can only be queued if it is succeeded' ); Proposal storage proposal = proposals[proposalId]; uint256 eta = add256(block.timestamp, sbTimelock.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( !sbTimelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), 'sbGovernor::_queueOrRevert: proposal action already queued at eta' ); sbTimelock.queueTransaction(target, value, signature, data, eta); } function execute(uint256 proposalId) public payable { require( state(proposalId) == ProposalState.Queued, 'sbGovernor::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++) { sbTimelock.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, 'sbGovernor::cancel: cannot cancel executed proposal'); Proposal storage proposal = proposals[proposalId]; require( msg.sender == guardian || sbVotes.getPriorProposalVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), 'sbGovernor::cancel: proposer above threshold' ); proposal.canceled = true; for (uint256 i = 0; i < proposal.targets.length; i++) { sbTimelock.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, uint256[] 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, 'sbGovernor::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, sbTimelock.GRACE_PERIOD())) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function castVote(uint256 proposalId, bool support) public { return _castVote(msg.sender, proposalId, support); } function _castVote( address voter, uint256 proposalId, bool support ) internal { require(state(proposalId) == ProposalState.Active, 'sbGovernor::_castVote: voting is closed'); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, 'sbGovernor::_castVote: voter already voted'); uint96 votes = sbVotes.getPriorProposalVotes(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, 'sbGovernor::__acceptAdmin: sender must be gov guardian'); sbTimelock.acceptAdmin(); } function __abdicate() public { require(msg.sender == guardian, 'sbGovernor::__abdicate: sender must be gov guardian'); guardian = address(0); } function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public { require(msg.sender == guardian, 'sbGovernor::__queueSetTimelockPendingAdmin: sender must be gov guardian'); sbTimelock.queueTransaction(address(sbTimelock), 0, 'setPendingAdmin(address)', abi.encode(newPendingAdmin), eta); } function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public { require(msg.sender == guardian, 'sbGovernor::__executeSetTimelockPendingAdmin: sender must be gov guardian'); sbTimelock.executeTransaction(address(sbTimelock), 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; } } interface sbTimelockInterface { 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 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; }
0x6080604052600436106101405760003560e01c806372cacdd4116100b6578063d7f96d6d1161006f578063d7f96d6d14610359578063da35c6641461036e578063da95691a14610383578063ddf0b009146103a3578063e23a9a52146103c3578063fe0d94c1146103f057610140565b806372cacdd4146102d0578063760fbc13146102e55780637bdbe4d0146102fa578063915006711461030f578063b58131b01461032f578063b9a619611461034457610140565b806324bc1a641161010857806324bc1a6414610207578063328dd9821461021c5780633932abb11461024c5780633e4f49e61461026157806340e58ee51461028e578063452a9320146102ae57610140565b8063013cf08b1461014557806302a251a31461018357806315373e3d146101a557806317977c61146101c757806321f43e42146101e7575b600080fd5b34801561015157600080fd5b506101656101603660046120cb565b610403565b60405161017a99989796959493929190612c37565b60405180910390f35b34801561018f57600080fd5b5061019861045c565b60405161017a9190612480565b3480156101b157600080fd5b506101c56101c036600461210f565b610462565b005b3480156101d357600080fd5b506101986101e2366004611f13565b610471565b3480156101f357600080fd5b506101c5610202366004611f2e565b610483565b34801561021357600080fd5b5061019861056a565b34801561022857600080fd5b5061023c6102373660046120cb565b610578565b60405161017a9493929190612428565b34801561025857600080fd5b50610198610807565b34801561026d57600080fd5b5061028161027c3660046120cb565b61080c565b60405161017a9190612489565b34801561029a57600080fd5b506101c56102a93660046120cb565b610996565b3480156102ba57600080fd5b506102c3610bff565b60405161017a91906122d9565b3480156102dc57600080fd5b506102c3610c0e565b3480156102f157600080fd5b506101c5610c1d565b34801561030657600080fd5b50610198610c59565b34801561031b57600080fd5b506101c561032a366004611f2e565b610c5e565b34801561033b57600080fd5b50610198610d33565b34801561035057600080fd5b506101c5610d41565b34801561036557600080fd5b506102c3610dc6565b34801561037a57600080fd5b50610198610dd5565b34801561038f57600080fd5b5061019861039e366004611f58565b610ddb565b3480156103af57600080fd5b506101c56103be3660046120cb565b6111fb565b3480156103cf57600080fd5b506103e36103de3660046120e3565b611465565b60405161017a9190612b71565b6101c56103fe3660046120cb565b6114d4565b6004602052600090815260409020805460018201546002830154600784015460088501546009860154600a870154600b9097015495966001600160a01b0390951695939492939192909160ff8082169161010090041689565b61438090565b61046d338383611699565b5050565b60056020526000908152604090205481565b6002546001600160a01b031633146104b65760405162461bcd60e51b81526004016104ad90612a76565b60405180910390fd5b600080546040516001600160a01b0390911691630825f38f918391906104e09087906020016122d9565b604051602081830303815290604052856040518563ffffffff1660e01b815260040161050f9493929190612306565b600060405180830381600087803b15801561052957600080fd5b505af115801561053d573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526105659190810190612058565b505050565b6954b40b1f852bda00000090565b606080606080600060046000878152602001908152602001600020905080600301816004018260050183600601838054806020026020016040519081016040528092919081815260200182805480156105fa57602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116105dc575b505050505093508280548060200260200160405190810160405280929190818152602001828054801561064c57602002820191906000526020600020905b815481526020019060010190808311610638575b5050505050925081805480602002602001604051908101604052809291908181526020016000905b8282101561071f5760008481526020908190208301805460408051601f600260001961010060018716150201909416939093049283018590048502810185019091528181529283018282801561070b5780601f106106e05761010080835404028352916020019161070b565b820191906000526020600020905b8154815290600101906020018083116106ee57829003601f168201915b505050505081526020019060010190610674565b50505050915080805480602002602001604051908101604052809291908181526020016000905b828210156107f15760008481526020908190208301805460408051601f60026000196101006001871615020190941693909304928301859004850281018501909152818152928301828280156107dd5780601f106107b2576101008083540402835291602001916107dd565b820191906000526020600020905b8154815290600101906020018083116107c057829003601f168201915b505050505081526020019060010190610746565b5050505090509450945094509450509193509193565b600190565b600081600354101580156108205750600082115b61083c5760405162461bcd60e51b81526004016104ad906128e6565b6000828152600460205260409020600b81015460ff1615610861576002915050610991565b80600701544311610876576000915050610991565b8060080154431161088b576001915050610991565b80600a015481600901541115806108ac57506108a561056a565b8160090154105b156108bb576003915050610991565b60028101546108ce576004915050610991565b600b810154610100900460ff16156108ea576007915050610991565b61097b816002015460008054906101000a90046001600160a01b03166001600160a01b031663c1a287e26040518163ffffffff1660e01b815260040160206040518083038186803b15801561093e57600080fd5b505afa158015610952573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109769190612040565b611862565b421061098b576006915050610991565b60059150505b919050565b60006109a18261080c565b905060078160078111156109b157fe5b14156109cf5760405162461bcd60e51b81526004016104ad906125db565b60008281526004602052604090206002546001600160a01b0316331480610a9a57506109f9610d33565b60018054838201546001600160a01b039182169263916c435f9290911690610a2290439061188e565b6040518363ffffffff1660e01b8152600401610a3f9291906122ed565b60206040518083038186803b158015610a5757600080fd5b505afa158015610a6b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a8f919061213e565b6001600160601b0316105b610ab65760405162461bcd60e51b81526004016104ad906124f3565b600b8101805460ff1916600117905560005b6003820154811015610bc2576000546003830180546001600160a01b039092169163591fcdfe919084908110610afa57fe5b6000918252602090912001546004850180546001600160a01b039092169185908110610b2257fe5b9060005260206000200154856005018581548110610b3c57fe5b90600052602060002001866006018681548110610b5557fe5b9060005260206000200187600201546040518663ffffffff1660e01b8152600401610b849594939291906123ef565b600060405180830381600087803b158015610b9e57600080fd5b505af1158015610bb2573d6000803e3d6000fd5b505060019092019150610ac89050565b507f789cf55be980739dad1d0699b93b58e806b51c9d96619bfa8fe0a28abaa7b30c83604051610bf29190612480565b60405180910390a1505050565b6002546001600160a01b031681565b6001546001600160a01b031681565b6002546001600160a01b03163314610c475760405162461bcd60e51b81526004016104ad9061253f565b600280546001600160a01b0319169055565b600a90565b6002546001600160a01b03163314610c885760405162461bcd60e51b81526004016104ad90612879565b600080546040516001600160a01b0390911691633a66f90191839190610cb29087906020016122d9565b604051602081830303815290604052856040518563ffffffff1660e01b8152600401610ce19493929190612306565b602060405180830381600087803b158015610cfb57600080fd5b505af1158015610d0f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105659190612040565b69152d02c7e14af680000090565b6002546001600160a01b03163314610d6b5760405162461bcd60e51b81526004016104ad9061249d565b6000805460408051630e18b68160e01b815290516001600160a01b0390921692630e18b6819260048084019382900301818387803b158015610dac57600080fd5b505af1158015610dc0573d6000803e3d6000fd5b50505050565b6000546001600160a01b031681565b60035481565b6000610de5610d33565b600180546001600160a01b03169063916c435f903390610e0690439061188e565b6040518363ffffffff1660e01b8152600401610e239291906122ed565b60206040518083038186803b158015610e3b57600080fd5b505afa158015610e4f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e73919061213e565b6001600160601b031611610e995760405162461bcd60e51b81526004016104ad90612ae5565b84518651148015610eab575083518651145b8015610eb8575082518651145b610ed45760405162461bcd60e51b81526004016104ad906126f4565b8551610ef25760405162461bcd60e51b81526004016104ad90612592565b610efa610c59565b86511115610f1a5760405162461bcd60e51b81526004016104ad9061275b565b336000908152600560205260409020548015610f97576000610f3b8261080c565b90506001816007811115610f4b57fe5b1415610f695760405162461bcd60e51b81526004016104ad9061292c565b6000816007811115610f7757fe5b1415610f955760405162461bcd60e51b81526004016104ad90612678565b505b6000610fa543610976610807565b90506000610fb58261097661045c565b6003805460010190559050610fc8611a15565b604051806101a001604052806003548152602001336001600160a01b03168152602001600081526020018b81526020018a815260200189815260200188815260200184815260200183815260200160008152602001600081526020016000151581526020016000151581525090508060046000836000015181526020019081526020016000206000820151816000015560208201518160010160006101000a8154816001600160a01b0302191690836001600160a01b031602179055506040820151816002015560608201518160030190805190602001906110ab929190611a8a565b50608082015180516110c7916004840191602090910190611aef565b5060a082015180516110e3916005840191602090910190611b36565b5060c082015180516110ff916006840191602090910190611b8f565b5060e082015181600701556101008201518160080155610120820151816009015561014082015181600a015561016082015181600b0160006101000a81548160ff02191690831515021790555061018082015181600b0160016101000a81548160ff02191690831515021790555090505080600001516005600083602001516001600160a01b03166001600160a01b03168152602001908152602001600020819055507f7d84a6263ae0d98d3329bd7b46bb4e8d6f98cd35a7adb45c274c8b7fd5ebd5e08160000151338c8c8c8c89898e6040516111e599989796959493929190612b9f565b60405180910390a1519998505050505050505050565b60046112068261080c565b600781111561121157fe5b1461122e5760405162461bcd60e51b81526004016104ad90612812565b600081815260046020818152604080842084548251630d48571f60e31b815292519195946112839442946001600160a01b0390931693636a42b8f8938084019390829003018186803b15801561093e57600080fd5b905060005b600383015481101561142b576114238360030182815481106112a657fe5b6000918252602090912001546004850180546001600160a01b0390921691849081106112ce57fe5b90600052602060002001548560050184815481106112e857fe5b600091825260209182902001805460408051601f60026000196101006001871615020190941693909304928301859004850281018501909152818152928301828280156113765780601f1061134b57610100808354040283529160200191611376565b820191906000526020600020905b81548152906001019060200180831161135957829003601f168201915b505050505086600601858154811061138a57fe5b600091825260209182902001805460408051601f60026000196101006001871615020190941693909304928301859004850281018501909152818152928301828280156114185780601f106113ed57610100808354040283529160200191611418565b820191906000526020600020905b8154815290600101906020018083116113fb57829003601f168201915b5050505050866118b6565b600101611288565b50600282018190556040517f9a2e42fd6722813d69113e7d0079d3d940171428df7373df9c7f7617cfda289290610bf29085908490612c83565b61146d611be8565b5060008281526004602090815260408083206001600160a01b0385168452600c018252918290208251606081018452905460ff80821615158352610100820416151592820192909252620100009091046001600160601b0316918101919091525b92915050565b60056114df8261080c565b60078111156114ea57fe5b146115075760405162461bcd60e51b81526004016104ad906129a7565b6000818152600460205260408120600b8101805461ff001916610100179055905b600382015481101561165d576000546004830180546001600160a01b0390921691630825f38f91908490811061155a57fe5b906000526020600020015484600301848154811061157457fe5b6000918252602090912001546004860180546001600160a01b03909216918690811061159c57fe5b90600052602060002001548660050186815481106115b657fe5b906000526020600020018760060187815481106115cf57fe5b9060005260206000200188600201546040518763ffffffff1660e01b81526004016115fe9594939291906123ef565b6000604051808303818588803b15801561161757600080fd5b505af115801561162b573d6000803e3d6000fd5b50505050506040513d6000823e601f3d908101601f191682016040526116549190810190612058565b50600101611528565b507f712ae1383f79ac853f8d882153778e0260ef8f03b504e2866e0593e04d2b291f8260405161168d9190612480565b60405180910390a15050565b60016116a48361080c565b60078111156116af57fe5b146116cc5760405162461bcd60e51b81526004016104ad906127a0565b60008281526004602090815260408083206001600160a01b0387168452600c8101909252909120805460ff16156117155760405162461bcd60e51b81526004016104ad9061262e565b600154600783015460405163916c435f60e01b81526000926001600160a01b03169163916c435f9161174b918a916004016122ed565b60206040518083038186803b15801561176357600080fd5b505afa158015611777573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061179b919061213e565b905083156117c4576117ba8360090154826001600160601b0316611862565b60098401556117e1565b6117db83600a0154826001600160601b0316611862565b600a8401555b8154600160ff199091161761ff00191661010085151502176dffffffffffffffffffffffff00001916620100006001600160601b038316021782556040517f877856338e13f63d0c36822ff0ef736b80934cd90574a3a5bc9262c39d217c4690611852908890889088908690612372565b60405180910390a1505050505050565b6000828201838110156118875760405162461bcd60e51b81526004016104ad906127e7565b9392505050565b6000828211156118b05760405162461bcd60e51b81526004016104ad90612b42565b50900390565b6000546040516001600160a01b039091169063f2b06537906118e490889088908890889088906020016123a3565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016119169190612480565b60206040518083038186803b15801561192e57600080fd5b505afa158015611942573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119669190612024565b156119835760405162461bcd60e51b81526004016104ad90612a0f565b600054604051633a66f90160e01b81526001600160a01b0390911690633a66f901906119bb90889088908890889088906004016123a3565b602060405180830381600087803b1580156119d557600080fd5b505af11580156119e9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a0d9190612040565b505050505050565b604051806101a001604052806000815260200160006001600160a01b031681526020016000815260200160608152602001606081526020016060815260200160608152602001600081526020016000815260200160008152602001600081526020016000151581526020016000151581525090565b828054828255906000526020600020908101928215611adf579160200282015b82811115611adf57825182546001600160a01b0319166001600160a01b03909116178255602090920191600190910190611aaa565b50611aeb929150611c08565b5090565b828054828255906000526020600020908101928215611b2a579160200282015b82811115611b2a578251825591602001919060010190611b0f565b50611aeb929150611c27565b828054828255906000526020600020908101928215611b83579160200282015b82811115611b835782518051611b73918491602090910190611c3c565b5091602001919060010190611b56565b50611aeb929150611ca9565b828054828255906000526020600020908101928215611bdc579160200282015b82811115611bdc5782518051611bcc918491602090910190611c3c565b5091602001919060010190611baf565b50611aeb929150611cc6565b604080516060810182526000808252602082018190529181019190915290565b5b80821115611aeb5780546001600160a01b0319168155600101611c09565b5b80821115611aeb5760008155600101611c28565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10611c7d57805160ff1916838001178555611b2a565b82800160010185558215611b2a5791820182811115611b2a578251825591602001919060010190611b0f565b80821115611aeb576000611cbd8282611ce3565b50600101611ca9565b80821115611aeb576000611cda8282611ce3565b50600101611cc6565b50805460018160011615610100020316600290046000825580601f10611d095750611d27565b601f016020900490600052602060002090810190611d279190611c27565b50565b80356001600160a01b03811681146114ce57600080fd5b600082601f830112611d51578081fd5b8135611d64611d5f82612cb8565b612c91565b818152915060208083019084810181840286018201871015611d8557600080fd5b60005b84811015611dac57611d9a8883611d2a565b84529282019290820190600101611d88565b505050505092915050565b600082601f830112611dc7578081fd5b8135611dd5611d5f82612cb8565b818152915060208083019084810160005b84811015611dac57611dfd888484358a0101611ec5565b84529282019290820190600101611de6565b600082601f830112611e1f578081fd5b8135611e2d611d5f82612cb8565b818152915060208083019084810160005b84811015611dac57611e55888484358a0101611ec5565b84529282019290820190600101611e3e565b600082601f830112611e77578081fd5b8135611e85611d5f82612cb8565b818152915060208083019084810181840286018201871015611ea657600080fd5b60005b84811015611dac57813584529282019290820190600101611ea9565b600082601f830112611ed5578081fd5b8135611ee3611d5f82612cd8565b9150808252836020828501011115611efa57600080fd5b8060208401602084013760009082016020015292915050565b600060208284031215611f24578081fd5b6118878383611d2a565b60008060408385031215611f40578081fd5b611f4a8484611d2a565b946020939093013593505050565b600080600080600060a08688031215611f6f578081fd5b853567ffffffffffffffff80821115611f86578283fd5b611f9289838a01611d41565b96506020880135915080821115611fa7578283fd5b611fb389838a01611e67565b95506040880135915080821115611fc8578283fd5b611fd489838a01611e0f565b94506060880135915080821115611fe9578283fd5b611ff589838a01611db7565b9350608088013591508082111561200a578283fd5b5061201788828901611ec5565b9150509295509295909350565b600060208284031215612035578081fd5b815161188781612d34565b600060208284031215612051578081fd5b5051919050565b600060208284031215612069578081fd5b815167ffffffffffffffff81111561207f578182fd5b8201601f8101841361208f578182fd5b805161209d611d5f82612cd8565b8181528560208385010111156120b1578384fd5b6120c2826020830160208601612d08565b95945050505050565b6000602082840312156120dc578081fd5b5035919050565b600080604083850312156120f5578182fd5b823591506121068460208501611d2a565b90509250929050565b60008060408385031215612121578182fd5b82359150602083013561213381612d34565b809150509250929050565b60006020828403121561214f578081fd5b81516001600160601b0381168114611887578182fd5b6000815180845260208085019450808401835b8381101561219d5781516001600160a01b031687529582019590820190600101612178565b509495945050505050565b6000815180845260208085018081965082840281019150828601855b858110156121ee5782840389526121dc84835161222a565b988501989350908401906001016121c4565b5091979650505050505050565b6000815180845260208085019450808401835b8381101561219d5781518752958201959082019060010161220e565b60008151808452612242816020860160208601612d08565b601f01601f19169290920160200192915050565b600081546001808216600081146122745760018114612292576122d0565b60028304607f16865260ff19831660208701526040860193506122d0565b600283048087526122a286612cfc565b60005b828110156122c65781546020828b01015284820191506020810190506122a5565b8801602001955050505b50505092915050565b6001600160a01b0391909116815260200190565b6001600160a01b03929092168252602082015260400190565b600060018060a01b038616825284602083015260a06040830152601860a08301527f73657450656e64696e6741646d696e286164647265737329000000000000000060c083015260e0606083015261236160e083018561222a565b905082608083015295945050505050565b6001600160a01b039490941684526020840192909252151560408301526001600160601b0316606082015260800190565b600060018060a01b038716825285602083015260a060408301526123ca60a083018661222a565b82810360608401526123dc818661222a565b9150508260808301529695505050505050565b600060018060a01b038716825285602083015260a0604083015261241660a0830186612256565b82810360608401526123dc8186612256565b60006080825261243b6080830187612165565b828103602084015261244d81876121fb565b9050828103604084015261246181866121a8565b9050828103606084015261247581856121a8565b979650505050505050565b90815260200190565b602081016008831061249757fe5b91905290565b60208082526036908201527f7362476f7665726e6f723a3a5f5f61636365707441646d696e3a2073656e6465604082015275391036bab9ba1031329033b7bb1033bab0b93234b0b760511b606082015260800190565b6020808252602c908201527f7362476f7665726e6f723a3a63616e63656c3a2070726f706f7365722061626f60408201526b1d99481d1a1c995cda1bdb1960a21b606082015260800190565b60208082526033908201527f7362476f7665726e6f723a3a5f5f61626469636174653a2073656e646572206d6040820152723ab9ba1031329033b7bb1033bab0b93234b0b760691b606082015260800190565b60208082526029908201527f7362476f7665726e6f723a3a70726f706f73653a206d7573742070726f7669646040820152686520616374696f6e7360b81b606082015260800190565b60208082526033908201527f7362476f7665726e6f723a3a63616e63656c3a2063616e6e6f742063616e63656040820152721b08195e1958dd5d1959081c1c9bdc1bdcd85b606a1b606082015260800190565b6020808252602a908201527f7362476f7665726e6f723a3a5f63617374566f74653a20766f74657220616c726040820152691958591e481d9bdd195960b21b606082015260800190565b60208082526056908201527f7362476f7665726e6f723a3a70726f706f73653a206f6e65206c69766520707260408201527f6f706f73616c207065722070726f706f7365722c20666f756e6420616e20616c6060820152751c9958591e481c195b991a5b99c81c1c9bdc1bdcd85b60521b608082015260a00190565b60208082526041908201527f7362476f7665726e6f723a3a70726f706f73653a2070726f706f73616c20667560408201527f6e6374696f6e20696e666f726d6174696f6e206172697479206d69736d6174636060820152600d60fb1b608082015260a00190565b60208082526025908201527f7362476f7665726e6f723a3a70726f706f73653a20746f6f206d616e7920616360408201526474696f6e7360d81b606082015260800190565b60208082526027908201527f7362476f7665726e6f723a3a5f63617374566f74653a20766f74696e672069736040820152660818db1bdcd95960ca1b606082015260800190565b6020808252601190820152706164646974696f6e206f766572666c6f7760781b604082015260600190565b60208082526041908201527f7362476f7665726e6f723a3a71756575653a2070726f706f73616c2063616e2060408201527f6f6e6c79206265207175657565642069662069742069732073756363656564656060820152601960fa1b608082015260a00190565b60208082526047908201527f7362476f7665726e6f723a3a5f5f717565756553657454696d656c6f636b506560408201527f6e64696e6741646d696e3a2073656e646572206d75737420626520676f7620676060820152663ab0b93234b0b760c91b608082015260a00190565b60208082526026908201527f7362476f7665726e6f723a3a73746174653a20696e76616c69642070726f706f6040820152651cd85b081a5960d21b606082015260800190565b60208082526055908201527f7362476f7665726e6f723a3a70726f706f73653a206f6e65206c69766520707260408201527f6f706f73616c207065722070726f706f7365722c20666f756e6420616e20616c6060820152741c9958591e481858dd1a5d99481c1c9bdc1bdcd85b605a1b608082015260a00190565b60208082526042908201527f7362476f7665726e6f723a3a657865637574653a2070726f706f73616c20636160408201527f6e206f6e6c792062652065786563757465642069662069742069732071756575606082015261195960f21b608082015260a00190565b60208082526041908201527f7362476f7665726e6f723a3a5f71756575654f725265766572743a2070726f7060408201527f6f73616c20616374696f6e20616c7265616479207175657565642061742065746060820152606160f81b608082015260a00190565b60208082526049908201527f7362476f7665726e6f723a3a5f5f6578656375746553657454696d656c6f636b60408201527f50656e64696e6741646d696e3a2073656e646572206d75737420626520676f766060820152681033bab0b93234b0b760b91b608082015260a00190565b6020808252603c908201527f7362476f7665726e6f723a3a70726f706f73653a2070726f706f73657220766f60408201527f7465732062656c6f772070726f706f73616c207468726573686f6c6400000000606082015260800190565b6020808252601590820152747375627472616374696f6e20756e646572666c6f7760581b604082015260600190565b8151151581526020808301511515908201526040918201516001600160601b03169181019190915260600190565b8981526001600160a01b038916602082015261012060408201819052600090612bca8382018b612165565b90508281036060840152612bde818a6121fb565b90508281036080840152612bf281896121a8565b905082810360a0840152612c0681886121a8565b90508560c08401528460e0840152828103610100840152612c27818561222a565b9c9b505050505050505050505050565b9889526001600160a01b0397909716602089015260408801959095526060870193909352608086019190915260a085015260c0840152151560e083015215156101008201526101200190565b918252602082015260400190565b60405181810167ffffffffffffffff81118282101715612cb057600080fd5b604052919050565b600067ffffffffffffffff821115612cce578081fd5b5060209081020190565b600067ffffffffffffffff821115612cee578081fd5b50601f01601f191660200190565b60009081526020902090565b60005b83811015612d23578181015183820152602001612d0b565b83811115610dc05750506000910152565b8015158114611d2757600080fdfea2646970667358221220d476ab6b75366227d6d898fe18d4a798d46ca792e9e1a128f0d4d6790e317e9664736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}]}
71
0x17270c1497e06cEf5e15a106C06b808c6a636FD4
pragma solidity 0.7.4; enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, MODULO_BY_ZERO } 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); } } abstract contract AdminStorage { /** * @notice The address of the administrator account or contract. */ address public admin; } abstract contract BalanceSheetStorage { struct Vault { uint256 debt; uint256 freeCollateral; uint256 lockedCollateral; bool isOpen; } /** * @notice The unique Fintroller associated with this contract. */ FintrollerInterface public fintroller; /** * @dev One vault for each fyToken for each account. */ mapping(address => mapping(address => Vault)) internal vaults; /** * @notice Indicator that this is a BalanceSheet contract, for inspection. */ bool public constant isBalanceSheet = true; } abstract contract CarefulMath { /** * @notice Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @notice Add `a` and `b` and then subtract `c`. */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } /** * @notice Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @notice Returns the remainder of dividing two numbers. * @dev 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). */ function modUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.MODULO_BY_ZERO, 0); } return (MathError.NO_ERROR, a % b); } /** * @notice Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @notice Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } } abstract contract Erc20RecoverStorage { /** * @notice The tokens that can be recovered cannot be in this mapping. */ Erc20Interface[] public nonRecoverableTokens; /** * @notice A flag that signals whether the the non-recoverable tokens were set or not. */ bool public isInitialized; } abstract contract Erc20Storage { /** * @notice Returns the number of decimals used to get its user representation. */ uint8 public decimals; /** * @notice Returns the name of the token. */ string public name; /** * @notice Returns the symbol of the token, usually a shorter version of * the name. */ string public symbol; /** * @notice Returns the amount of tokens in existence. */ uint256 public totalSupply; mapping(address => mapping(address => uint256)) internal allowances; mapping(address => uint256) internal balances; } abstract contract ExponentialStorage { struct Exp { uint256 mantissa; } /** * @dev In Exponential denomination, 1e18 is 1. */ uint256 internal constant expScale = 1e18; uint256 internal constant halfExpScale = expScale / 2; uint256 internal constant mantissaOne = expScale; } abstract contract FyTokenStorage { /** * STRUCTS */ struct Vault { uint256 debt; uint256 freeCollateral; uint256 lockedCollateral; bool isOpen; } /** * STORAGE PROPERTIES */ /** * @notice The global debt registry. */ BalanceSheetInterface public balanceSheet; /** * @notice The Erc20 asset that backs the borows of this fyToken. */ Erc20Interface public collateral; /** * @notice The ratio between mantissa precision (1e18) and the collateral precision. */ uint256 public collateralPrecisionScalar; /** * @notice Unix timestamp in seconds for when this token expires. */ uint256 public expirationTime; /** * @notice The unique Fintroller associated with this contract. */ FintrollerInterface public fintroller; /** * @notice The unique Redemption Pool associated with this contract. */ RedemptionPoolInterface public redemptionPool; /** * @notice The Erc20 underlying, or target, asset for this fyToken. */ Erc20Interface public underlying; /** * @notice The ratio between mantissa precision (1e18) and the underlying precision. */ uint256 public underlyingPrecisionScalar; /** * @notice Indicator that this is a FyToken contract, for inspection. */ bool public constant isFyToken = true; } abstract contract RedemptionPoolStorage { /** * @notice The unique Fintroller associated with this contract. */ FintrollerInterface public fintroller; /** * @notice The amount of the underyling asset available to be redeemed after maturation. */ uint256 public totalUnderlyingSupply; /** * The unique fyToken associated with this Redemption Pool. */ FyTokenInterface public fyToken; /** * @notice Indicator that this is a Redemption Pool contract, for inspection. */ bool public constant isRedemptionPool = true; } abstract contract ReentrancyGuard { bool private notEntered; /* * 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. */ constructor() { notEntered = true; } /** * @notice Prevents a contract from calling itself, directly or indirectly. * @dev 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, "ERR_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 Address for address; /** * INTERNAL FUNCTIONS */ function safeTransfer( Erc20Interface token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( Erc20Interface token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * PRIVATE FUNCTIONS */ /** * @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 cannot 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(Erc20Interface 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 = functionCallWithValue(address(token), data, "ERR_SAFE_ERC20_LOW_LEVEL_CALL"); if (returndata.length > 0) { /* Return data is optional. */ require(abi.decode(returndata, (bool)), "ERR_SAFE_ERC20_ERC20_OPERATION"); } } function functionCallWithValue( address target, bytes memory data, string memory errorMessage ) private returns (bytes memory) { require(target.isContract(), "ERR_SAFE_ERC20_CALL_TO_NON_CONTRACT"); /* solhint-disable-next-line avoid-low-level-calls */ (bool success, bytes memory returndata) = target.call(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 UniswapAnchoredViewInterface { /** * @notice Get the official price for a symbol. * @param symbol The symbol to fetch the price of. * @return Price denominated in USD, with 6 decimals. */ function price(string memory symbol) external view returns (uint256); } abstract contract AdminInterface is AdminStorage { /** * NON-CONSTANT FUNCTIONS */ function _renounceAdmin() external virtual; function _transferAdmin(address newAdmin) external virtual; /** * EVENTS */ event TransferAdmin(address indexed oldAdmin, address indexed newAdmin); } abstract contract BalanceSheetInterface is BalanceSheetStorage { /** * CONSTANT FUNCTIONS */ function getClutchableCollateral(FyTokenInterface fyToken, uint256 repayAmount) external view virtual returns (uint256); function getCurrentCollateralizationRatio(FyTokenInterface fyToken, address account) public view virtual returns (uint256); function getHypotheticalCollateralizationRatio( FyTokenInterface fyToken, address account, uint256 lockedCollateral, uint256 debt ) public view virtual returns (uint256); function getVault(FyTokenInterface fyToken, address account) external view virtual returns ( uint256, uint256, uint256, bool ); function getVaultDebt(FyTokenInterface fyToken, address account) external view virtual returns (uint256); function getVaultLockedCollateral(FyTokenInterface fyToken, address account) external view virtual returns (uint256); function isAccountUnderwater(FyTokenInterface fyToken, address account) external view virtual returns (bool); function isVaultOpen(FyTokenInterface fyToken, address account) external view virtual returns (bool); /** * NON-CONSTANT FUNCTIONS */ function clutchCollateral( FyTokenInterface fyToken, address liquidator, address borrower, uint256 clutchedCollateralAmount ) external virtual returns (bool); function depositCollateral(FyTokenInterface fyToken, uint256 collateralAmount) external virtual returns (bool); function freeCollateral(FyTokenInterface fyToken, uint256 collateralAmount) external virtual returns (bool); function lockCollateral(FyTokenInterface fyToken, uint256 collateralAmount) external virtual returns (bool); function openVault(FyTokenInterface fyToken) external virtual returns (bool); function setVaultDebt( FyTokenInterface fyToken, address account, uint256 newVaultDebt ) external virtual returns (bool); function withdrawCollateral(FyTokenInterface fyToken, uint256 collateralAmount) external virtual returns (bool); /** * EVENTS */ event ClutchCollateral( FyTokenInterface indexed fyToken, address indexed liquidator, address indexed borrower, uint256 clutchedCollateralAmount ); event DepositCollateral(FyTokenInterface indexed fyToken, address indexed account, uint256 collateralAmount); event FreeCollateral(FyTokenInterface indexed fyToken, address indexed account, uint256 collateralAmount); event LockCollateral(FyTokenInterface indexed fyToken, address indexed account, uint256 collateralAmount); event OpenVault(FyTokenInterface indexed fyToken, address indexed account); event SetVaultDebt(FyTokenInterface indexed fyToken, address indexed account, uint256 oldDebt, uint256 newDebt); event WithdrawCollateral(FyTokenInterface indexed fyToken, address indexed account, uint256 collateralAmount); } abstract contract Erc20Interface is Erc20Storage { /** * CONSTANT FUNCTIONS */ function allowance(address owner, address spender) external view virtual returns (uint256); function balanceOf(address account) external view virtual returns (uint256); /** * NON-CONSTANT FUNCTIONS */ function approve(address spender, uint256 amount) external virtual returns (bool); function transfer(address recipient, uint256 amount) external virtual returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external virtual returns (bool); /** * EVENTS */ event Approval(address indexed owner, address indexed spender, uint256 value); event Burn(address indexed account, uint256 burnAmount); event Mint(address indexed account, uint256 mintAmount); event Transfer(address indexed from, address indexed to, uint256 value); } abstract contract Erc20RecoverInterface is Erc20RecoverStorage { /** * NON-CONSTANT FUNCTIONS */ function _recover(Erc20Interface token, uint256 recoverAmount) external virtual; function _setNonRecoverableTokens(Erc20Interface[] calldata tokens) external virtual; /** * EVENTS */ event Recover(address indexed admin, Erc20Interface token, uint256 recoverAmount); event SetNonRecoverableTokens(address indexed admin, Erc20Interface[] nonRecoverableTokens); } abstract contract Exponential is CarefulMath, /* no dependency */ ExponentialStorage /* no dependency */ { /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({ mantissa: result })); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b. * NOTE: Returns an error if (`num` * 10e18) > MAX_INT, or if `denom` is zero. */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(a.mantissa, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, b.mantissa); if (err1 != MathError.NO_ERROR) { return (err1, Exp({ mantissa: 0 })); } return (MathError.NO_ERROR, Exp({ mantissa: rational })); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 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, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({ mantissa: 0 })); } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); /* The only possible error `div` is MathError.DIVISION_BY_ZERO but we control `expScale` and it's not zero. */ assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({ mantissa: product })); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure 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 Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({ mantissa: result })); } } abstract contract FintrollerStorage is Exponential { struct Bond { Exp collateralizationRatio; uint256 debtCeiling; bool isBorrowAllowed; bool isDepositCollateralAllowed; bool isLiquidateBorrowAllowed; bool isListed; bool isRedeemFyTokenAllowed; bool isRepayBorrowAllowed; bool isSupplyUnderlyingAllowed; } /** * @dev Maps the fyToken address to the Bond structs. */ mapping(FyTokenInterface => Bond) internal bonds; /** * @notice The contract that provides price data for the collateral and the underlying asset. */ UniswapAnchoredViewInterface public oracle; /** * @notice Multiplier representing the discount on collateral that a liquidator receives. */ uint256 public liquidationIncentiveMantissa; /** * @notice The ratio between mantissa precision (1e18) and the oracle price precision (1e6). */ uint256 public constant oraclePricePrecisionScalar = 1.0e12; /** * @dev The threshold below which the collateralization ratio cannot be set, equivalent to 100%. */ uint256 internal constant collateralizationRatioLowerBoundMantissa = 1.0e18; /** * @dev The threshold above which the collateralization ratio cannot be set, equivalent to 10,000%. */ uint256 internal constant collateralizationRatioUpperBoundMantissa = 1.0e20; /** * @dev The dafault collateralization ratio set when a new bond is listed, equivalent to 150%. */ uint256 internal constant defaultCollateralizationRatioMantissa = 1.5e18; /** * @dev The threshold below which the liquidation incentive cannot be set, equivalent to 100%. */ uint256 internal constant liquidationIncentiveLowerBoundMantissa = 1.0e18; /** * @dev The threshold above which the liquidation incentive cannot be set, equivalent to 150%. */ uint256 internal constant liquidationIncentiveUpperBoundMantissa = 1.5e18; /** * @notice Indicator that this is a Fintroller contract, for inspection. */ bool public constant isFintroller = true; } abstract contract FyTokenInterface is FyTokenStorage { /** * NON-CONSTANT FUNCTIONS */ function borrow(uint256 borrowAmount) external virtual returns (bool); function burn(address holder, uint256 burnAmount) external virtual returns (bool); function liquidateBorrow(address borrower, uint256 repayAmount) external virtual returns (bool); function mint(address beneficiary, uint256 borrowAmount) external virtual returns (bool); function repayBorrow(uint256 repayAmount) external virtual returns (bool); function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (bool); function _setFintroller(FintrollerInterface newFintroller) external virtual returns (bool); /** * EVENTS */ event Borrow(address indexed account, uint256 repayAmount); event LiquidateBorrow( address indexed liquidator, address indexed borrower, uint256 repayAmount, uint256 clutchedCollateralAmount ); event RepayBorrow(address indexed payer, address indexed borrower, uint256 repayAmount, uint256 newDebt); event SetFintroller(address indexed admin, FintrollerInterface oldFintroller, FintrollerInterface newFintroller); } abstract contract RedemptionPoolInterface is RedemptionPoolStorage { /** * NON-CONSTANT FUNCTIONS */ function redeemFyTokens(uint256 underlyingAmount) external virtual returns (bool); function supplyUnderlying(uint256 underlyingAmount) external virtual returns (bool); /** * EVENTS */ event RedeemFyTokens(address indexed account, uint256 fyTokenAmount, uint256 underlyingAmount); event SupplyUnderlying(address indexed account, uint256 underlyingAmount, uint256 fyTokenAmount); } abstract contract Admin is AdminInterface { /** * @notice Throws if called by any account other than the admin. */ modifier onlyAdmin() { require(admin == msg.sender, "ERR_NOT_ADMIN"); _; } /** * @notice Initializes the contract setting the deployer as the initial admin. */ constructor() { address msgSender = msg.sender; admin = msgSender; emit TransferAdmin(address(0x00), msgSender); } /** * @notice Leaves the contract without admin, so it will not be possible to call * `onlyAdmin` functions anymore. * * Requirements: * * - The caller must be the administrator. * * WARNING: Doing this will leave the contract without an admin, * thereby removing any functionality that is only available to the admin. */ function _renounceAdmin() external virtual override onlyAdmin { emit TransferAdmin(admin, address(0x00)); admin = address(0x00); } /** * @notice Transfers the admin of the contract to a new account (`newAdmin`). * Can only be called by the current admin. * @param newAdmin The acount of the new admin. */ function _transferAdmin(address newAdmin) external virtual override onlyAdmin { require(newAdmin != address(0x00), "ERR_SET_ADMIN_ZERO_ADDRESS"); emit TransferAdmin(admin, newAdmin); admin = newAdmin; } } abstract contract Erc20Recover is Erc20RecoverInterface, /* one dependency */ Admin /* two dependencies */ { using SafeErc20 for Erc20Interface; /** * @notice Sets the tokens that this contract cannot recover. * * @dev Emits a {SetNonRecoverableTokens} event. * * Requirements: * * - The caller must be the administrator. * - The contract must be non-initialized. * - The array of given tokens cannot be empty. * * @param tokens The array of tokens to set as non-recoverable. */ function _setNonRecoverableTokens(Erc20Interface[] calldata tokens) external override onlyAdmin { /* Checks */ require(isInitialized == false, "ERR_INITALIZED"); /* Iterate over the token list, sanity check each and update the mapping. */ uint256 length = tokens.length; for (uint256 i = 0; i < length; i += 1) { tokens[i].symbol(); nonRecoverableTokens.push(tokens[i]); } /* Effects: prevent this function from ever being called again. */ isInitialized = true; emit SetNonRecoverableTokens(admin, tokens); } /** * @notice Recover Erc20 tokens sent to this contract (by accident or otherwise). * @dev Emits a {RecoverToken} event. * * Requirements: * * - The caller must be the administrator. * - The contract must be initialized. * - The amount to recover cannot be zero. * - The token to recover cannot be among the non-recoverable tokens. * * @param token The token to make the recover for. * @param recoverAmount The uint256 amount to recover, specified in the token's decimal system. */ function _recover(Erc20Interface token, uint256 recoverAmount) external override onlyAdmin { /* Checks */ require(isInitialized == true, "ERR_NOT_INITALIZED"); require(recoverAmount > 0, "ERR_RECOVER_ZERO"); bytes32 tokenSymbolHash = keccak256(bytes(token.symbol())); uint256 length = nonRecoverableTokens.length; /** * We iterate over the non-recoverable token array and check that: * * 1. The addresses of the tokens are not the same * 2. The symbols of the tokens are not the same * * It is true that the second check may lead to a false positive, but * there is no better way to fend off against proxied tokens. */ for (uint256 i = 0; i < length; i += 1) { require( address(token) != address(nonRecoverableTokens[i]) && tokenSymbolHash != keccak256(bytes(nonRecoverableTokens[i].symbol())), "ERR_RECOVER_NON_RECOVERABLE_TOKEN" ); } /* Interactions */ token.safeTransfer(admin, recoverAmount); emit Recover(admin, token, recoverAmount); } } abstract contract FintrollerInterface is FintrollerStorage { /** * CONSTANT FUNCTIONS */ function getBond(FyTokenInterface fyToken) external view virtual returns ( uint256 debtCeiling, uint256 collateralizationRatioMantissa, bool isBorrowAllowed, bool isDepositCollateralAllowed, bool isLiquidateBorrowAllowed, bool isListed, bool isRedeemFyTokenAllowed, bool isRepayBorrowAllowed, bool isSupplyUnderlyingAllowed ); function getBorrowAllowed(FyTokenInterface fyToken) external view virtual returns (bool); function getBondDebtCeiling(FyTokenInterface fyToken) external view virtual returns (uint256); function getBondCollateralizationRatio(FyTokenInterface fyToken) external view virtual returns (uint256); function getDepositCollateralAllowed(FyTokenInterface fyToken) external view virtual returns (bool); function getLiquidateBorrowAllowed(FyTokenInterface fyToken) external view virtual returns (bool); function getRedeemFyTokensAllowed(FyTokenInterface fyToken) external view virtual returns (bool); function getRepayBorrowAllowed(FyTokenInterface fyToken) external view virtual returns (bool); function getSupplyUnderlyingAllowed(FyTokenInterface fyToken) external view virtual returns (bool); /** * NON-CONSTANT FUNCTIONS */ function listBond(FyTokenInterface fyToken) external virtual returns (bool); function setBorrowAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); function setCollateralizationRatio(FyTokenInterface fyToken, uint256 newCollateralizationRatioMantissa) external virtual returns (bool); function setDebtCeiling(FyTokenInterface fyToken, uint256 newDebtCeiling) external virtual returns (bool); function setDepositCollateralAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); function setLiquidateBorrowAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); function setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external virtual returns (bool); function setOracle(UniswapAnchoredViewInterface newOracle) external virtual returns (bool); function setRedeemFyTokensAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); function setRepayBorrowAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); function setSupplyUnderlyingAllowed(FyTokenInterface fyToken, bool state) external virtual returns (bool); /** * EVENTS */ event ListBond(address indexed admin, FyTokenInterface indexed fyToken); event SetBorrowAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); event SetCollateralizationRatio( address indexed admin, FyTokenInterface indexed fyToken, uint256 oldCollateralizationRatio, uint256 newCollateralizationRatio ); event SetDebtCeiling( address indexed admin, FyTokenInterface indexed fyToken, uint256 oldDebtCeiling, uint256 newDebtCeiling ); event SetDepositCollateralAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); event SetLiquidateBorrowAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); event SetLiquidationIncentive( address indexed admin, uint256 oldLiquidationIncentive, uint256 newLiquidationIncentive ); event SetRedeemFyTokensAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); event SetRepayBorrowAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); event SetOracle(address indexed admin, address oldOracle, address newOracle); event SetSupplyUnderlyingAllowed(address indexed admin, FyTokenInterface indexed fyToken, bool state); } contract RedemptionPool is CarefulMath, /* no dependency */ ReentrancyGuard, /* no dependency */ RedemptionPoolInterface, /* one dependency */ Admin, /* two dependencies */ Erc20Recover /* five dependencies */ { using SafeErc20 for Erc20Interface; /** * @param fintroller_ The address of the Fintroller contract. * @param fyToken_ The address of the fyToken contract. */ constructor(FintrollerInterface fintroller_, FyTokenInterface fyToken_) Admin() { /* Set the Fintroller contract and sanity check it. */ fintroller = fintroller_; fintroller.isFintroller(); /** * Set the fyToken contract. It cannot be sanity-checked because the fyToken creates this * contract in its own constructor and contracts cannot be called while initializing. */ fyToken = fyToken_; } struct RedeemFyTokensLocalVars { MathError mathErr; uint256 newUnderlyingTotalSupply; uint256 underlyingPrecisionScalar; uint256 underlyingAmount; } /** * @notice Pays the token holder the face value at maturation time. * * @dev Emits a {RedeemFyTokens} event. * * Requirements: * * - Must be called post maturation. * - The amount to redeem cannot be zero. * - The Fintroller must allow this action to be performed. * - There must be enough liquidity in the Redemption Pool. * * @param fyTokenAmount The amount of fyTokens to redeem for the underlying asset. * @return true = success, otherwise it reverts. */ function redeemFyTokens(uint256 fyTokenAmount) external override nonReentrant returns (bool) { RedeemFyTokensLocalVars memory vars; /* Checks: maturation time. */ require(block.timestamp >= fyToken.expirationTime(), "ERR_BOND_NOT_MATURED"); /* Checks: the zero edge case. */ require(fyTokenAmount > 0, "ERR_REDEEM_FYTOKENS_ZERO"); /* Checks: the Fintroller allows this action to be performed. */ require(fintroller.getRedeemFyTokensAllowed(fyToken), "ERR_REDEEM_FYTOKENS_NOT_ALLOWED"); /* Checks: there is enough liquidity. */ require(fyTokenAmount <= totalUnderlyingSupply, "ERR_REDEEM_FYTOKENS_INSUFFICIENT_UNDERLYING"); /** * fyTokens always have 18 decimals so the underlying amount needs to be downscaled. * If the precision scalar is 1, it means that the underlying also has 18 decimals. */ vars.underlyingPrecisionScalar = fyToken.underlyingPrecisionScalar(); if (vars.underlyingPrecisionScalar != 1) { (vars.mathErr, vars.underlyingAmount) = divUInt(fyTokenAmount, vars.underlyingPrecisionScalar); require(vars.mathErr == MathError.NO_ERROR, "ERR_REDEEM_FYTOKENS_MATH_ERROR"); } else { vars.underlyingAmount = fyTokenAmount; } /* Effects: decrease the remaining supply of underlying. */ (vars.mathErr, vars.newUnderlyingTotalSupply) = subUInt(totalUnderlyingSupply, vars.underlyingAmount); assert(vars.mathErr == MathError.NO_ERROR); totalUnderlyingSupply = vars.newUnderlyingTotalSupply; /* Interactions: burn the fyTokens. */ require(fyToken.burn(msg.sender, fyTokenAmount), "ERR_SUPPLY_UNDERLYING_CALL_BURN"); /* Interactions: perform the Erc20 transfer. */ fyToken.underlying().safeTransfer(msg.sender, vars.underlyingAmount); emit RedeemFyTokens(msg.sender, fyTokenAmount, vars.underlyingAmount); return true; } struct SupplyUnderlyingLocalVars { MathError mathErr; uint256 newUnderlyingTotalSupply; uint256 underlyingPrecisionScalar; uint256 fyTokenAmount; } /** * @notice An alternative to the usual minting method that does not involve taking on debt. * * @dev Emits a {SupplyUnderlying} event. * * Requirements: * * - Must be called prior to maturation. * - The amount to supply cannot be zero. * - The Fintroller must allow this action to be performed. * - The caller must have allowed this contract to spend `underlyingAmount` tokens. * * @param underlyingAmount The amount of underlying to supply to the Redemption Pool. * @return true = success, otherwise it reverts. */ function supplyUnderlying(uint256 underlyingAmount) external override nonReentrant returns (bool) { SupplyUnderlyingLocalVars memory vars; /* Checks: maturation time. */ require(block.timestamp < fyToken.expirationTime(), "ERR_BOND_MATURED"); /* Checks: the zero edge case. */ require(underlyingAmount > 0, "ERR_SUPPLY_UNDERLYING_ZERO"); /* Checks: the Fintroller allows this action to be performed. */ require(fintroller.getSupplyUnderlyingAllowed(fyToken), "ERR_SUPPLY_UNDERLYING_NOT_ALLOWED"); /* Effects: update storage. */ (vars.mathErr, vars.newUnderlyingTotalSupply) = addUInt(totalUnderlyingSupply, underlyingAmount); require(vars.mathErr == MathError.NO_ERROR, "ERR_SUPPLY_UNDERLYING_MATH_ERROR"); totalUnderlyingSupply = vars.newUnderlyingTotalSupply; /** * fyTokens always have 18 decimals so the underlying amount needs to be upscaled. * If the precision scalar is 1, it means that the underlying also has 18 decimals. */ vars.underlyingPrecisionScalar = fyToken.underlyingPrecisionScalar(); if (vars.underlyingPrecisionScalar != 1) { (vars.mathErr, vars.fyTokenAmount) = mulUInt(underlyingAmount, vars.underlyingPrecisionScalar); require(vars.mathErr == MathError.NO_ERROR, "ERR_SUPPLY_UNDERLYING_MATH_ERROR"); } else { vars.fyTokenAmount = underlyingAmount; } /* Interactions: mint the fyTokens. */ require(fyToken.mint(msg.sender, vars.fyTokenAmount), "ERR_SUPPLY_UNDERLYING_CALL_MINT"); /* Interactions: perform the Erc20 transfer. */ fyToken.underlying().safeTransferFrom(msg.sender, address(this), underlyingAmount); emit SupplyUnderlying(msg.sender, underlyingAmount, vars.fyTokenAmount); return true; } }
0x608060405234801561001057600080fd5b50600436106100cf5760003560e01c8063dc3bfba91161008c578063e6abb5ae11610066578063e6abb5ae14610214578063ede4c0cc1461023a578063f1374d1814610242578063f851a4401461025f576100cf565b8063dc3bfba914610181578063dde4bec014610189578063e02dcb17146101f7576100cf565b8063143a08d4146100d45780631c2872aa146100ee578063392e53cd1461011c57806373805ae2146101385780639e6ae5a014610140578063bfa2530814610179575b600080fd5b6100dc610267565b60408051918252519081900360200190f35b61011a6004803603604081101561010457600080fd5b506001600160a01b03813516906020013561026d565b005b6101246106d0565b604080519115158252519081900360200190f35b6101246106d9565b61015d6004803603602081101561015657600080fd5b50356106de565b604080516001600160a01b039092168252519081900360200190f35b61011a610708565b61015d6107ac565b61011a6004803603602081101561019f57600080fd5b810190602081018135600160201b8111156101b957600080fd5b8201836020820111156101cb57600080fd5b803590602001918460208302840111600160201b831117156101ec57600080fd5b5090925090506107bb565b6101246004803603602081101561020d57600080fd5b5035610a82565b61011a6004803603602081101561022a57600080fd5b50356001600160a01b0316611040565b61015d611156565b6101246004803603602081101561025857600080fd5b503561116a565b61015d61170d565b60015481565b60045461010090046001600160a01b031633146102c1576040805162461bcd60e51b815260206004820152600d60248201526c22a9292fa727aa2fa0a226a4a760991b604482015290519081900360640190fd5b60045460ff161515600114610312576040805162461bcd60e51b815260206004820152601260248201527111549497d393d517d253925510531256915160721b604482015290519081900360640190fd5b6000811161035a576040805162461bcd60e51b815260206004820152601060248201526f4552525f5245434f5645525f5a45524f60801b604482015290519081900360640190fd5b6000826001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b15801561039557600080fd5b505afa1580156103a9573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156103d257600080fd5b8101908080516040519392919084600160201b8211156103f157600080fd5b90830190602082018581111561040657600080fd5b8251600160201b81118282018810171561041f57600080fd5b82525081516020918201929091019080838360005b8381101561044c578181015183820152602001610434565b50505050905090810190601f1680156104795780820380516001836020036101000a031916815260200191505b506040525050508051906020012090506000600380549050905060005b8181101561065a57600381815481106104ab57fe5b6000918252602090912001546001600160a01b038681169116148015906106175750600381815481106104da57fe5b6000918252602082200154604080516395d89b4160e01b815290516001600160a01b03909216926395d89b4192600480840193829003018186803b15801561052157600080fd5b505afa158015610535573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052602081101561055e57600080fd5b8101908080516040519392919084600160201b82111561057d57600080fd5b90830190602082018581111561059257600080fd5b8251600160201b8111828201881017156105ab57600080fd5b82525081516020918201929091019080838360005b838110156105d85781810151838201526020016105c0565b50505050905090810190601f1680156106055780820380516001836020036101000a031916815260200191505b50604052505050805190602001208314155b6106525760405162461bcd60e51b8152600401808060200182810382526021815260200180611b4a6021913960400191505060405180910390fd5b600101610496565b5060045461067a906001600160a01b038681169161010090041685611721565b600454604080516001600160a01b03878116825260208201879052825161010090940416927ff6891c84a6c6af32a6d052172a8acc4c631b1d5057ffa2bc1da268b6938ea2da929181900390910190a250505050565b60045460ff1681565b600181565b600381815481106106ee57600080fd5b6000918252602090912001546001600160a01b0316905081565b60045461010090046001600160a01b0316331461075c576040805162461bcd60e51b815260206004820152600d60248201526c22a9292fa727aa2fa0a226a4a760991b604482015290519081900360640190fd5b60045460405160009161010090046001600160a01b0316907fbdd36143ee09de60bdefca70680e0f71189b2ed7acee364b53917ad433fdaf80908390a360048054610100600160a81b0319169055565b6002546001600160a01b031681565b60045461010090046001600160a01b0316331461080f576040805162461bcd60e51b815260206004820152600d60248201526c22a9292fa727aa2fa0a226a4a760991b604482015290519081900360640190fd5b60045460ff1615610858576040805162461bcd60e51b815260206004820152600e60248201526d11549497d253925510531256915160921b604482015290519081900360640190fd5b8060005b818110156109f55783838281811061087057fe5b905060200201356001600160a01b03166001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b1580156108b857600080fd5b505afa1580156108cc573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156108f557600080fd5b8101908080516040519392919084600160201b82111561091457600080fd5b90830190602082018581111561092957600080fd5b8251600160201b81118282018810171561094257600080fd5b82525081516020918201929091019080838360005b8381101561096f578181015183820152602001610957565b50505050905090810190601f16801561099c5780820380516001836020036101000a031916815260200191505b506040525050505060038484838181106109b257fe5b835460018181018655600095865260209586902090910180546001600160a01b0319166001600160a01b039690930294909401359490941617909155500161085c565b5060048054600160ff1990911617908190556040805160208082528082018690526101009093046001600160a01b0316927fd877543bef27da9036243421e623413c8fdd78d7d183cc93d8f3cddbd657a2ed928792879290918291908201908590850280828437600083820152604051601f909101601f19169092018290039550909350505050a2505050565b6000805460ff16610acf576040805162461bcd60e51b815260206004820152601260248201527111549497d4915153951490539517d0d0531360721b604482015290519081900360640190fd5b6000805460ff19169055610ae1611b20565b600260009054906101000a90046001600160a01b03166001600160a01b031663da284dcc6040518163ffffffff1660e01b815260040160206040518083038186803b158015610b2f57600080fd5b505afa158015610b43573d6000803e3d6000fd5b505050506040513d6020811015610b5957600080fd5b5051421015610ba6576040805162461bcd60e51b815260206004820152601460248201527311549497d093d39117d393d517d350551554915160621b604482015290519081900360640190fd5b60008311610bfb576040805162461bcd60e51b815260206004820152601860248201527f4552525f52454445454d5f4659544f4b454e535f5a45524f0000000000000000604482015290519081900360640190fd5b6000546002546040805163162fdba360e01b81526001600160a01b03928316600482015290516101009093049091169163162fdba391602480820192602092909190829003018186803b158015610c5157600080fd5b505afa158015610c65573d6000803e3d6000fd5b505050506040513d6020811015610c7b57600080fd5b5051610cce576040805162461bcd60e51b815260206004820152601f60248201527f4552525f52454445454d5f4659544f4b454e535f4e4f545f414c4c4f57454400604482015290519081900360640190fd5b600154831115610d0f5760405162461bcd60e51b815260040180806020018281038252602b815260200180611b6b602b913960400191505060405180910390fd5b600260009054906101000a90046001600160a01b03166001600160a01b0316631a0de6fa6040518163ffffffff1660e01b815260040160206040518083038186803b158015610d5d57600080fd5b505afa158015610d71573d6000803e3d6000fd5b505050506040513d6020811015610d8757600080fd5b505160408201819052600114610e2f57610da5838260400151611778565b6060830181905282826004811115610db957fe5b6004811115610dc457fe5b9052506000905081516004811115610dd857fe5b14610e2a576040805162461bcd60e51b815260206004820152601e60248201527f4552525f52454445454d5f4659544f4b454e535f4d4154485f4552524f520000604482015290519081900360640190fd5b610e37565b606081018390525b610e4760015482606001516117a4565b6020830181905282826004811115610e5b57fe5b6004811115610e6657fe5b9052506000905081516004811115610e7a57fe5b14610e8157fe5b60208082015160015560025460408051632770a7eb60e21b81523360048201526024810187905290516001600160a01b0390921692639dc29fac926044808401938290030181600087803b158015610ed857600080fd5b505af1158015610eec573d6000803e3d6000fd5b505050506040513d6020811015610f0257600080fd5b5051610f55576040805162461bcd60e51b815260206004820152601f60248201527f4552525f535550504c595f554e4445524c59494e475f43414c4c5f4255524e00604482015290519081900360640190fd5b610fe8338260600151600260009054906101000a90046001600160a01b03166001600160a01b0316636f307dc36040518163ffffffff1660e01b815260040160206040518083038186803b158015610fac57600080fd5b505afa158015610fc0573d6000803e3d6000fd5b505050506040513d6020811015610fd657600080fd5b50516001600160a01b03169190611721565b6060810151604080518581526020810192909252805133927f885a0ef214a8c0b5d41cbf3cd2292d459773279061790ae6c1e654483828048792908290030190a260019150506000805460ff19166001179055919050565b60045461010090046001600160a01b03163314611094576040805162461bcd60e51b815260206004820152600d60248201526c22a9292fa727aa2fa0a226a4a760991b604482015290519081900360640190fd5b6001600160a01b0381166110ef576040805162461bcd60e51b815260206004820152601a60248201527f4552525f5345545f41444d494e5f5a45524f5f41444452455353000000000000604482015290519081900360640190fd5b6004546040516001600160a01b0380841692610100900416907fbdd36143ee09de60bdefca70680e0f71189b2ed7acee364b53917ad433fdaf8090600090a3600480546001600160a01b0390921661010002610100600160a81b0319909216919091179055565b60005461010090046001600160a01b031681565b6000805460ff166111b7576040805162461bcd60e51b815260206004820152601260248201527111549497d4915153951490539517d0d0531360721b604482015290519081900360640190fd5b6000805460ff191690556111c9611b20565b600260009054906101000a90046001600160a01b03166001600160a01b031663da284dcc6040518163ffffffff1660e01b815260040160206040518083038186803b15801561121757600080fd5b505afa15801561122b573d6000803e3d6000fd5b505050506040513d602081101561124157600080fd5b50514210611289576040805162461bcd60e51b815260206004820152601060248201526f11549497d093d39117d350551554915160821b604482015290519081900360640190fd5b600083116112de576040805162461bcd60e51b815260206004820152601a60248201527f4552525f535550504c595f554e4445524c59494e475f5a45524f000000000000604482015290519081900360640190fd5b6000546002546040805163e79628ab60e01b81526001600160a01b03928316600482015290516101009093049091169163e79628ab91602480820192602092909190829003018186803b15801561133457600080fd5b505afa158015611348573d6000803e3d6000fd5b505050506040513d602081101561135e57600080fd5b505161139b5760405162461bcd60e51b8152600401808060200182810382526021815260200180611b966021913960400191505060405180910390fd5b6113a7600154846117c7565b60208301819052828260048111156113bb57fe5b60048111156113c657fe5b90525060009050815160048111156113da57fe5b1461142c576040805162461bcd60e51b815260206004820181905260248201527f4552525f535550504c595f554e4445524c59494e475f4d4154485f4552524f52604482015290519081900360640190fd5b60208082015160015560025460408051630d06f37d60e11b815290516001600160a01b0390921692631a0de6fa92600480840193829003018186803b15801561147457600080fd5b505afa158015611488573d6000803e3d6000fd5b505050506040513d602081101561149e57600080fd5b505160408201819052600114611546576114bc8382604001516117ed565b60608301819052828260048111156114d057fe5b60048111156114db57fe5b90525060009050815160048111156114ef57fe5b14611541576040805162461bcd60e51b815260206004820181905260248201527f4552525f535550504c595f554e4445524c59494e475f4d4154485f4552524f52604482015290519081900360640190fd5b61154e565b606081018390525b6002546060820151604080516340c10f1960e01b81523360048201526024810192909252516001600160a01b03909216916340c10f19916044808201926020929091908290030181600087803b1580156115a757600080fd5b505af11580156115bb573d6000803e3d6000fd5b505050506040513d60208110156115d157600080fd5b5051611624576040805162461bcd60e51b815260206004820152601f60248201527f4552525f535550504c595f554e4445524c59494e475f43414c4c5f4d494e5400604482015290519081900360640190fd5b6116b5333085600260009054906101000a90046001600160a01b03166001600160a01b0316636f307dc36040518163ffffffff1660e01b815260040160206040518083038186803b15801561167857600080fd5b505afa15801561168c573d6000803e3d6000fd5b505050506040513d60208110156116a257600080fd5b50516001600160a01b031692919061182c565b6060810151604080518581526020810192909252805133927fc460d7cbd3e39052de48c19518b5af10728a5349bc2870e47b5a67ffc32d200d92908290030190a260019150506000805460ff19166001179055919050565b60045461010090046001600160a01b031681565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b17905261177390849061188c565b505050565b6000808261178c575060019050600061179d565b600083858161179757fe5b04915091505b9250929050565b6000808383116117bb57506000905081830361179d565b5060039050600061179d565b6000808383018481106117df5760009250905061179d565b60026000925092505061179d565b600080836118005750600090508061179d565b8383028385828161180d57fe5b04146118215760026000925092505061179d565b60009250905061179d565b604080516001600160a01b0380861660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b17905261188690859061188c565b50505050565b60606118ce83836040518060400160405280601d81526020017f4552525f534146455f45524332305f4c4f575f4c4556454c5f43414c4c000000815250611940565b805190915015611773578080602001905160208110156118ed57600080fd5b5051611773576040805162461bcd60e51b815260206004820152601e60248201527f4552525f534146455f45524332305f45524332305f4f5045524154494f4e0000604482015290519081900360640190fd5b6060611954846001600160a01b0316611ae4565b61198f5760405162461bcd60e51b8152600401808060200182810382526023815260200180611bb76023913960400191505060405180910390fd5b60006060856001600160a01b0316856040518082805190602001908083835b602083106119cd5780518252601f1990920191602091820191016119ae565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114611a2f576040519150601f19603f3d011682016040523d82523d6000602084013e611a34565b606091505b50915091508115611a48579150611add9050565b805115611a585780518082602001fd5b8360405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611aa2578181015183820152602001611a8a565b50505050905090810190601f168015611acf5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b9392505050565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590611b1857508115155b949350505050565b60408051608081019091528060008152602001600081526020016000815260200160008152509056fe4552525f5245434f5645525f4e4f4e5f5245434f56455241424c455f544f4b454e4552525f52454445454d5f4659544f4b454e535f494e53554646494349454e545f554e4445524c59494e474552525f535550504c595f554e4445524c59494e475f4e4f545f414c4c4f5745444552525f534146455f45524332305f43414c4c5f544f5f4e4f4e5f434f4e5452414354a26469706673582212209e2708db8a2f59561f1c7af1c63c57de85fdeed29c80c5ddfdefa5d93a7ac2b264736f6c63430007040033
{"success": true, "error": null, "results": {"detectors": [{"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}]}
72
0x1736c73e648304a7776ef4d424df49514d65531f
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 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; } } 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 TokenVesting is Ownable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; using SafeERC20 for IERC20; event TokensReleased(address token, uint256 amount); event TokenVestingRevoked(address token); // beneficiary of tokens after they are released address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _cliff; uint256 private _start; uint256 private _duration; bool private _revocable; mapping (address => uint256) private _released; mapping (address => bool) private _revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest * @param start the time (as Unix time) at which point vesting starts * @param duration duration in seconds of the period in which the tokens will vest * @param revocable whether the vesting is revocable or not */ constructor (address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, bool revocable) public { require(beneficiary != address(0), "TokenVesting: beneficiary is the zero address"); // solhint-disable-next-line max-line-length require(cliffDuration <= duration, "TokenVesting: cliff is longer than duration"); require(duration > 0, "TokenVesting: duration is 0"); // solhint-disable-next-line max-line-length require(start.add(duration) > block.timestamp, "TokenVesting: final time is before current time"); _beneficiary = beneficiary; _revocable = revocable; _duration = duration; _cliff = start.add(cliffDuration); _start = start; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the cliff time of the token vesting. */ function cliff() public view returns (uint256) { return _cliff; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return true if the vesting is revocable. */ function revocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released(address token) public view returns (uint256) { return _released[token]; } /** * @return true if the token is revoked. */ function revoked(address token) public view returns (bool) { return _revoked[token]; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20 token) public { uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "TokenVesting: no tokens are due"); _released[address(token)] = _released[address(token)].add(unreleased); token.safeTransfer(_beneficiary, unreleased); emit TokensReleased(address(token), unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20 token) public onlyOwner { require(_revocable, "TokenVesting: cannot revoke"); require(!_revoked[address(token)], "TokenVesting: token already revoked"); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = _releasableAmount(token); uint256 refund = balance.sub(unreleased); _revoked[address(token)] = true; token.safeTransfer(owner(), refund); emit TokenVestingRevoked(address(token)); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function _releasableAmount(IERC20 token) private view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(_released[address(token)]); if (block.timestamp < _cliff) { return 0; } else if (block.timestamp >= _start.add(_duration) || _revoked[address(token)]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(_start)).div(_duration); } } }
0x608060405234801561001057600080fd5b50600436106100cf5760003560e01c8063872a78101161008c5780639852595c116100665780639852595c1461019c578063be9a6555146101c2578063f2fde38b146101ca578063fa01dc06146101f0576100cf565b8063872a7810146101705780638da5cb5b1461018c5780638f32d59b14610194576100cf565b80630fb5a6b4146100d457806313d033c0146100ee57806319165587146100f657806338af3eed1461011e578063715018a61461014257806374a8f1031461014a575b600080fd5b6100dc610216565b60408051918252519081900360200190f35b6100dc61021c565b61011c6004803603602081101561010c57600080fd5b50356001600160a01b0316610222565b005b610126610327565b604080516001600160a01b039092168252519081900360200190f35b61011c610336565b61011c6004803603602081101561016057600080fd5b50356001600160a01b03166103d9565b610178610601565b604080519115158252519081900360200190f35b61012661060a565b610178610619565b6100dc600480360360208110156101b257600080fd5b50356001600160a01b031661063d565b6100dc61065c565b61011c600480360360208110156101e057600080fd5b50356001600160a01b0316610662565b6101786004803603602081101561020657600080fd5b50356001600160a01b03166106c7565b60045490565b60025490565b600061022d826106e5565b905060008111610284576040805162461bcd60e51b815260206004820152601f60248201527f546f6b656e56657374696e673a206e6f20746f6b656e73206172652064756500604482015290519081900360640190fd5b6001600160a01b0382166000908152600660205260409020546102ad908263ffffffff61071d16565b6001600160a01b038084166000818152600660205260409020929092556001546102df9291168363ffffffff61077e16565b604080516001600160a01b03841681526020810183905281517fc7798891864187665ac6dd119286e44ec13f014527aeeb2b8eb3fd413df93179929181900390910190a15050565b6001546001600160a01b031690565b61033e610619565b61038f576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6103e1610619565b610432576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b60055460ff16610489576040805162461bcd60e51b815260206004820152601b60248201527f546f6b656e56657374696e673a2063616e6e6f74207265766f6b650000000000604482015290519081900360640190fd5b6001600160a01b03811660009081526007602052604090205460ff16156104e15760405162461bcd60e51b8152600401808060200182810382526023815260200180610e036023913960400191505060405180910390fd5b604080516370a0823160e01b815230600482015290516000916001600160a01b038416916370a0823191602480820192602092909190829003018186803b15801561052b57600080fd5b505afa15801561053f573d6000803e3d6000fd5b505050506040513d602081101561055557600080fd5b505190506000610564836106e5565b90506000610578838363ffffffff6107d516565b6001600160a01b0385166000908152600760205260409020805460ff1916600117905590506105bf6105a861060a565b6001600160a01b038616908363ffffffff61077e16565b604080516001600160a01b038616815290517f39983c6d4d174a7aee564f449d4a5c3c7ac9649d72b7793c56901183996f8af69181900360200190a150505050565b60055460ff1690565b6000546001600160a01b031690565b600080546001600160a01b031661062e610817565b6001600160a01b031614905090565b6001600160a01b0381166000908152600660205260409020545b919050565b60035490565b61066a610619565b6106bb576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b6106c48161081b565b50565b6001600160a01b031660009081526007602052604090205460ff1690565b6001600160a01b0381166000908152600660205260408120546107179061070b846108bb565b9063ffffffff6107d516565b92915050565b600082820183811015610777576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b1790526107d0908490610a00565b505050565b600061077783836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610bbe565b3390565b6001600160a01b0381166108605760405162461bcd60e51b8152600401808060200182810382526026815260200180610d926026913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b604080516370a0823160e01b8152306004820152905160009182916001600160a01b038516916370a08231916024808301926020929190829003018186803b15801561090657600080fd5b505afa15801561091a573d6000803e3d6000fd5b505050506040513d602081101561093057600080fd5b50516001600160a01b0384166000908152600660205260408120549192509061096090839063ffffffff61071d16565b905060025442101561097757600092505050610657565b60045460035461098c9163ffffffff61071d16565b421015806109b257506001600160a01b03841660009081526007602052604090205460ff165b156109c05791506106579050565b6109f76004546109eb6109de600354426107d590919063ffffffff16565b849063ffffffff610c5516565b9063ffffffff610cae16565b92505050610657565b610a12826001600160a01b0316610cf0565b610a63576040805162461bcd60e51b815260206004820152601f60248201527f5361666545524332303a2063616c6c20746f206e6f6e2d636f6e747261637400604482015290519081900360640190fd5b60006060836001600160a01b0316836040518082805190602001908083835b60208310610aa15780518252601f199092019160209182019101610a82565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114610b03576040519150601f19603f3d011682016040523d82523d6000602084013e610b08565b606091505b509150915081610b5f576040805162461bcd60e51b815260206004820181905260248201527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564604482015290519081900360640190fd5b805115610bb857808060200190516020811015610b7b57600080fd5b5051610bb85760405162461bcd60e51b815260040180806020018281038252602a815260200180610dd9602a913960400191505060405180910390fd5b50505050565b60008184841115610c4d5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610c12578181015183820152602001610bfa565b50505050905090810190601f168015610c3f5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b600082610c6457506000610717565b82820282848281610c7157fe5b04146107775760405162461bcd60e51b8152600401808060200182810382526021815260200180610db86021913960400191505060405180910390fd5b600061077783836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250610d2c565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590610d2457508115155b949350505050565b60008183610d7b5760405162461bcd60e51b8152602060048201818152835160248401528351909283926044909101919085019080838360008315610c12578181015183820152602001610bfa565b506000838581610d8757fe5b049594505050505056fe4f776e61626c653a206e6577206f776e657220697320746865207a65726f2061646472657373536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f775361666545524332303a204552433230206f7065726174696f6e20646964206e6f742073756363656564546f6b656e56657374696e673a20746f6b656e20616c7265616479207265766f6b6564a265627a7a72315820ad6b0945a22f5668f96b3b011fd7bb1d162598643f2e4002498a82137c20d5aa64736f6c63430005110032
{"success": true, "error": null, "results": {}}
true
null
{}
73
0x17e7542824be3648fcd06b759de53fee3c3d3f78
pragma solidity 0.7.1; 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); } 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[] calldata tokenAmounts, bytes calldata data ) external 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[] calldata tokenAmounts, bytes calldata data ) external payable virtual returns (address[] memory); function getAbsoluteAmountDeposit( TokenAmount calldata 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 calldata 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 BPool { function getCurrentTokens() external view returns (address[] memory); function getBalance(address) external view returns (uint256); function getNormalizedWeight(address) external view returns (uint256); function joinswapExternAmountIn(address, uint256, uint256) external; function exitswapPoolAmountIn(address, uint256, uint256) external; } 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); } library SafeERC20 { function safeTransfer( ERC20 token, address to, uint256 value, string memory location ) internal { callOptionalReturn( token, abi.encodeWithSelector( token.transfer.selector, to, value ), "transfer", location ); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value, string memory location ) internal { callOptionalReturn( token, abi.encodeWithSelector( token.transferFrom.selector, from, to, value ), "transferFrom", location ); } function safeApprove( ERC20 token, address spender, uint256 value, string memory location ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: bad approve call" ); callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, value ), "approve", location ); } /** * @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). * @param location Location of the call (for debug). */ function callOptionalReturn( ERC20 token, bytes memory data, string memory functionName, string memory location ) 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 implement two-steps call as callee is a contract is a responsibility of a caller. // 1. The call itself is made, and success asserted // 2. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require( success, string( abi.encodePacked( "SafeERC20: ", functionName, " failed in ", location ) ) ); if (returndata.length > 0) { // Return data is optional require( abi.decode(returndata, (bool)), string( abi.encodePacked( "SafeERC20: ", functionName, " returned false in ", location ) ) ); } } } contract ERC20ProtocolAdapter is ProtocolAdapter { /** * @return Amount of tokens 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); } } contract BalancerInteractiveAdapter is InteractiveAdapter, ERC20ProtocolAdapter { using SafeERC20 for ERC20; /** * @notice Deposits tokens to the Balancer pool. * @param tokenAmounts Array with one element - TokenAmount struct with * token address, token amount to be deposited, and amount type. * @param data ABI-encoded additional parameters: * - poolAddress - pool address. * @return tokensToBeWithdrawn Array with one element - pool address. * @dev Implementation of InteractiveAdapter function. */ function deposit( TokenAmount[] calldata tokenAmounts, bytes calldata data ) external payable override returns (address[] memory tokensToBeWithdrawn) { require(tokenAmounts.length == 1, "BIA: should be 1 tokenAmount[1]"); address poolAddress = abi.decode(data, (address)); tokensToBeWithdrawn = new address[](1); tokensToBeWithdrawn[0] = poolAddress; address token = tokenAmounts[0].token; uint256 amount = getAbsoluteAmountDeposit(tokenAmounts[0]); ERC20(token).safeApprove(poolAddress, amount, "BIA"); try BPool(poolAddress).joinswapExternAmountIn( token, amount, 0 ) {} catch Error(string memory reason) { // solhint-disable-line no-empty-blocks revert(reason); } catch { revert("BIA: deposit fail"); } } /** * @notice Withdraws tokens from the Balancer pool. * @param tokenAmounts Array with one element - TokenAmount struct with * Balancer token address, Balancer token amount to be redeemed, and amount type. * @param data ABI-encoded additional parameters: * - toTokenAddress - destination token address. * @return tokensToBeWithdrawn Array with one element - destination token address. * @dev Implementation of InteractiveAdapter function. */ function withdraw( TokenAmount[] calldata tokenAmounts, bytes calldata data ) external payable override returns (address[] memory tokensToBeWithdrawn) { require(tokenAmounts.length == 1, "BIA: should be 1 tokenAmount[2]"); address toTokenAddress = abi.decode(data, (address)); tokensToBeWithdrawn = new address[](1); tokensToBeWithdrawn[0] = toTokenAddress; address token = tokenAmounts[0].token; uint256 amount = getAbsoluteAmountWithdraw(tokenAmounts[0]); try BPool(token).exitswapPoolAmountIn( toTokenAddress, amount, 0 ) {} catch Error(string memory reason) { // solhint-disable-line no-empty-blocks revert(reason); } catch { revert("BIA: withdraw fail"); } } }
0x6080604052600436106100345760003560e01c806328ffb83d14610039578063387b817414610062578063d4fac45d14610075575b600080fd5b61004c610047366004610c09565b6100a2565b6040516100599190610ed6565b60405180910390f35b61004c610070366004610c09565b610311565b34801561008157600080fd5b50610095610090366004610bd1565b6104d2565b6040516100599190611139565b6060600184146100e7576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100de90610fb8565b60405180910390fd5b60006100f583850185610bb5565b60408051600180825281830190925291925060208083019080368337019050509150808260008151811061012557fe5b602002602001019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff168152505060008686600081811061016e57fe5b6101849260206060909202019081019150610bb5565b905060006101a38888600081811061019857fe5b905060600201610580565b905061020783826040518060400160405280600381526020017f42494100000000000000000000000000000000000000000000000000000000008152508573ffffffffffffffffffffffffffffffffffffffff1661078c909392919063ffffffff16565b6040517f5db3427700000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff841690635db342779061025e9085908590600090600401610ea8565b600060405180830381600087803b15801561027857600080fd5b505af1925050508015610289575060015b61030657610295611174565b806102a057506102d4565b806040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100de9190610f30565b6040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100de9061105d565b505050949350505050565b60606001841461034d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100de90611094565b600061035b83850185610bb5565b60408051600180825281830190925291925060208083019080368337019050509150808260008151811061038b57fe5b602002602001019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff16815250506000868660008181106103d457fe5b6103ea9260206060909202019081019150610bb5565b90506000610409888860008181106103fe57fe5b90506060020161092e565b6040517f46ab38f100000000000000000000000000000000000000000000000000000000815290915073ffffffffffffffffffffffffffffffffffffffff8316906346ab38f1906104639086908590600090600401610ea8565b600060405180830381600087803b15801561047d57600080fd5b505af192505050801561048e575060015b6103065761049a611174565b806102a057506040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100de90611026565b6040517f70a0823100000000000000000000000000000000000000000000000000000000815260009073ffffffffffffffffffffffffffffffffffffffff8416906370a0823190610527908590600401610e3a565b60206040518083038186803b15801561053f57600080fd5b505afa158015610553573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105779190610d04565b90505b92915050565b6000806105906020840184610bb5565b9050602083013560006105a96060860160408701610ce5565b905060018160028111156105b957fe5b14806105d0575060028160028111156105ce57fe5b145b610606576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100de90610f81565b600181600281111561061457fe5b141561077d57670de0b6b3a764000082111561065c576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100de90610fef565b600073ffffffffffffffffffffffffffffffffffffffff841673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee141561069757504761073c565b6040517f70a0823100000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8516906370a08231906106e9903090600401610e3a565b60206040518083038186803b15801561070157600080fd5b505afa158015610715573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107399190610d04565b90505b670de0b6b3a764000083141561075757935061078792505050565b670de0b6b3a764000061076a8285610a16565b8161077157fe5b04945050505050610787565b5091506107879050565b919050565b81158061083a57506040517fdd62ed3e00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff85169063dd62ed3e906107e89030908790600401610e5b565b60206040518083038186803b15801561080057600080fd5b505afa158015610814573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108389190610d04565b155b610870576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100de90611102565b6109288463095ea7b360e01b858560405160240161088f929190610e82565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506040518060400160405280600781526020017f617070726f76650000000000000000000000000000000000000000000000000081525084610a6a565b50505050565b60008061093e6020840184610bb5565b9050602083013560006109576060860160408701610ce5565b9050600181600281111561096757fe5b148061097e5750600281600281111561097c57fe5b145b6109b4576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100de90610f81565b60018160028111156109c257fe5b141561077d57670de0b6b3a7640000821115610a0a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100de90610fef565b600061073984306104d2565b600082610a255750600061057a565b82820282848281610a3257fe5b0414610577576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100de906110cb565b600060608573ffffffffffffffffffffffffffffffffffffffff1685604051610a939190610d1c565b6000604051808303816000865af19150503d8060008114610ad0576040519150601f19603f3d011682016040523d82523d6000602084013e610ad5565b606091505b5091509150818484604051602001610aee929190610db9565b60405160208183030381529060405290610b35576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100de9190610f30565b50805115610bad5780806020019051810190610b519190610cc5565b8484604051602001610b64929190610d38565b60405160208183030381529060405290610bab576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100de9190610f30565b505b505050505050565b600060208284031215610bc6578081fd5b813561057781611256565b60008060408385031215610be3578081fd5b8235610bee81611256565b91506020830135610bfe81611256565b809150509250929050565b60008060008060408587031215610c1e578182fd5b843567ffffffffffffffff80821115610c35578384fd5b818701915087601f830112610c48578384fd5b813581811115610c56578485fd5b886020606083028501011115610c6a578485fd5b602092830196509450908601359080821115610c84578384fd5b818701915087601f830112610c97578384fd5b813581811115610ca5578485fd5b886020828501011115610cb6578485fd5b95989497505060200194505050565b600060208284031215610cd6578081fd5b81518015158114610577578182fd5b600060208284031215610cf6578081fd5b813560038110610577578182fd5b600060208284031215610d15578081fd5b5051919050565b60008251610d2e818460208701611142565b9190910192915050565b60007f5361666545524332303a2000000000000000000000000000000000000000000082528351610d7081600b850160208801611142565b7f2072657475726e65642066616c736520696e2000000000000000000000000000600b918401918201528351610dad81601e840160208801611142565b01601e01949350505050565b60007f5361666545524332303a2000000000000000000000000000000000000000000082528351610df181600b850160208801611142565b7f206661696c656420696e20000000000000000000000000000000000000000000600b918401918201528351610e2e816016840160208801611142565b01601601949350505050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b73ffffffffffffffffffffffffffffffffffffffff92831681529116602082015260400190565b73ffffffffffffffffffffffffffffffffffffffff929092168252602082015260400190565b73ffffffffffffffffffffffffffffffffffffffff9390931683526020830191909152604082015260600190565b6020808252825182820181905260009190848201906040850190845b81811015610f2457835173ffffffffffffffffffffffffffffffffffffffff1683529284019291840191600101610ef2565b50909695505050505050565b6000602082528251806020840152610f4f816040850160208701611142565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169190910160400192915050565b60208082526013908201527f49413a2062616420616d6f756e74207479706500000000000000000000000000604082015260600190565b6020808252601f908201527f4249413a2073686f756c64206265203120746f6b656e416d6f756e745b315d00604082015260600190565b6020808252600e908201527f49413a2062616420616d6f756e74000000000000000000000000000000000000604082015260600190565b60208082526012908201527f4249413a207769746864726177206661696c0000000000000000000000000000604082015260600190565b60208082526011908201527f4249413a206465706f736974206661696c000000000000000000000000000000604082015260600190565b6020808252601f908201527f4249413a2073686f756c64206265203120746f6b656e416d6f756e745b325d00604082015260600190565b60208082526010908201527f49413a206d756c206f766572666c6f7700000000000000000000000000000000604082015260600190565b6020808252601b908201527f5361666545524332303a2062616420617070726f76652063616c6c0000000000604082015260600190565b90815260200190565b60005b8381101561115d578181015183820152602001611145565b838111156109285750506000910152565b60e01c90565b600060443d101561118457611253565b600481823e6308c379a0611198825161116e565b146111a257611253565b6040517ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3d016004823e80513d67ffffffffffffffff81602484011181841117156111f05750505050611253565b8284019250825191508082111561120a5750505050611253565b503d8301602082840101111561122257505050611253565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01681016020016040529150505b90565b73ffffffffffffffffffffffffffffffffffffffff8116811461127857600080fd5b5056fea2646970667358221220c5f33319cf7a2fd6c1d6235b696e2cd080e9efddd9416876380aa13f63999cc464736f6c63430007010033
{"success": true, "error": null, "results": {"detectors": [{"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
74
0x1820a996cd0cee1d3316d1e0e6ebc7b22796af86
pragma solidity 0.7.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 on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } 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 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 transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } 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); } 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 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 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name, string memory symbol) { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } contract ERC721MintableByOwner is ERC721 { address private _owner; modifier onlyOwner() { require(_msgSender() == _owner); _; } constructor (string memory name, string memory symbol, string memory baseURI) ERC721(name, symbol) { _owner = _msgSender(); _setBaseURI(baseURI); } function mint(address to, string memory tokenURI) public onlyOwner returns (uint256) { uint256 tokenId = totalSupply() + 1; _safeMint(to, tokenId); _setTokenURI(tokenId, tokenURI); return tokenId; } }
0x608060405234801561001057600080fd5b50600436106101165760003560e01c80636352211e116100a2578063a22cb46511610071578063a22cb465146105fb578063b88d4fde1461064b578063c87b56dd14610750578063d0def521146107f7578063e985e9c5146108e657610116565b80636352211e146104455780636c0360eb1461049d57806370a082311461052057806395d89b411461057857610116565b806318160ddd116100e957806318160ddd146102a757806323b872dd146102c55780632f745c591461033357806342842e0e146103955780634f6ccce71461040357610116565b806301ffc9a71461011b57806306fdde031461017e578063081812fc14610201578063095ea7b314610259575b600080fd5b6101666004803603602081101561013157600080fd5b8101908080357bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19169060200190929190505050610960565b60405180821515815260200191505060405180910390f35b6101866109c7565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101c65780820151818401526020810190506101ab565b50505050905090810190601f1680156101f35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61022d6004803603602081101561021757600080fd5b8101908080359060200190929190505050610a69565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6102a56004803603604081101561026f57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610b04565b005b6102af610c48565b6040518082815260200191505060405180910390f35b610331600480360360608110156102db57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610c59565b005b61037f6004803603604081101561034957600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610ccf565b6040518082815260200191505060405180910390f35b610401600480360360608110156103ab57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610d2a565b005b61042f6004803603602081101561041957600080fd5b8101908080359060200190929190505050610d4a565b6040518082815260200191505060405180910390f35b6104716004803603602081101561045b57600080fd5b8101908080359060200190929190505050610d6d565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6104a5610da4565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156104e55780820151818401526020810190506104ca565b50505050905090810190601f1680156105125780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6105626004803603602081101561053657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610e46565b6040518082815260200191505060405180910390f35b610580610f1b565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156105c05780820151818401526020810190506105a5565b50505050905090810190601f1680156105ed5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6106496004803603604081101561061157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803515159060200190929190505050610fbd565b005b61074e6004803603608081101561066157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190803590602001906401000000008111156106c857600080fd5b8201836020820111156106da57600080fd5b803590602001918460018302840111640100000000831117156106fc57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f820116905080830192505050505050509192919290505050611173565b005b61077c6004803603602081101561076657600080fd5b81019080803590602001909291905050506111eb565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156107bc5780820151818401526020810190506107a1565b50505050905090810190601f1680156107e95780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6108d06004803603604081101561080d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019064010000000081111561084a57600080fd5b82018360208201111561085c57600080fd5b8035906020019184600183028401116401000000008311171561087e57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192905050506114d4565b6040518082815260200191505060405180910390f35b610948600480360360408110156108fc57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611564565b60405180821515815260200191505060405180910390f35b6000806000837bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916815260200190815260200160002060009054906101000a900460ff169050919050565b606060068054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610a5f5780601f10610a3457610100808354040283529160200191610a5f565b820191906000526020600020905b815481529060010190602001808311610a4257829003601f168201915b5050505050905090565b6000610a74826115f8565b610ac9576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c815260200180612b74602c913960400191505060405180910390fd5b6004600083815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff169050919050565b6000610b0f82610d6d565b90508073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610b96576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180612c246021913960400191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff16610bb5611615565b73ffffffffffffffffffffffffffffffffffffffff161480610be45750610be381610bde611615565b611564565b5b610c39576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526038815260200180612ac76038913960400191505060405180910390fd5b610c43838361161d565b505050565b6000610c5460026116d6565b905090565b610c6a610c64611615565b826116eb565b610cbf576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526031815260200180612c456031913960400191505060405180910390fd5b610cca8383836117df565b505050565b6000610d2282600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020611a2290919063ffffffff16565b905092915050565b610d4583838360405180602001604052806000815250611173565b505050565b600080610d61836002611a3c90919063ffffffff16565b50905080915050919050565b6000610d9d82604051806060016040528060298152602001612b29602991396002611a689092919063ffffffff16565b9050919050565b606060098054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610e3c5780601f10610e1157610100808354040283529160200191610e3c565b820191906000526020600020905b815481529060010190602001808311610e1f57829003601f168201915b5050505050905090565b60008073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610ecd576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602a815260200180612aff602a913960400191505060405180910390fd5b610f14600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020611a87565b9050919050565b606060078054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610fb35780601f10610f8857610100808354040283529160200191610fb3565b820191906000526020600020905b815481529060010190602001808311610f9657829003601f168201915b5050505050905090565b610fc5611615565b73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611066576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260198152602001807f4552433732313a20617070726f766520746f2063616c6c65720000000000000081525060200191505060405180910390fd5b8060056000611073611615565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055508173ffffffffffffffffffffffffffffffffffffffff16611120611615565b73ffffffffffffffffffffffffffffffffffffffff167f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c318360405180821515815260200191505060405180910390a35050565b61118461117e611615565b836116eb565b6111d9576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526031815260200180612c456031913960400191505060405180910390fd5b6111e584848484611a9c565b50505050565b60606111f6826115f8565b61124b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f815260200180612bf5602f913960400191505060405180910390fd5b6060600860008481526020019081526020016000208054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156112f45780601f106112c9576101008083540402835291602001916112f4565b820191906000526020600020905b8154815290600101906020018083116112d757829003601f168201915b5050505050905060006009805460018160011615610100020316600290049050141561132357809150506114cf565b6000815111156113fc57600981604051602001808380546001816001161561010002031660029004801561138e5780601f1061136c57610100808354040283529182019161138e565b820191906000526020600020905b81548152906001019060200180831161137a575b505082805190602001908083835b602083106113bf578051825260208201915060208101905060208303925061139c565b6001836020036101000a038019825116818451168082178552505050505050905001925050506040516020818303038152906040529150506114cf565b600961140784611b0e565b60405160200180838054600181600116156101000203166002900480156114655780601f10611443576101008083540402835291820191611465565b820191906000526020600020905b815481529060010190602001808311611451575b505082805190602001908083835b602083106114965780518252602082019150602081019050602083039250611473565b6001836020036101000a038019825116818451168082178552505050505050905001925050506040516020818303038152906040529150505b919050565b6000600a60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16611517611615565b73ffffffffffffffffffffffffffffffffffffffff161461153757600080fd5b60006001611543610c48565b0190506115508482611c55565b61155a8184611c73565b8091505092915050565b6000600560008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16905092915050565b600061160e826002611cfd90919063ffffffff16565b9050919050565b600033905090565b816004600083815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550808273ffffffffffffffffffffffffffffffffffffffff1661169083610d6d565b73ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560405160405180910390a45050565b60006116e482600001611d17565b9050919050565b60006116f6826115f8565b61174b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c815260200180612a9b602c913960400191505060405180910390fd5b600061175683610d6d565b90508073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff1614806117c557508373ffffffffffffffffffffffffffffffffffffffff166117ad84610a69565b73ffffffffffffffffffffffffffffffffffffffff16145b806117d657506117d58185611564565b5b91505092915050565b8273ffffffffffffffffffffffffffffffffffffffff166117ff82610d6d565b73ffffffffffffffffffffffffffffffffffffffff161461186b576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526029815260200180612bcc6029913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614156118f1576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526024815260200180612a516024913960400191505060405180910390fd5b6118fc838383611d28565b61190760008261161d565b61195881600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020611d2d90919063ffffffff16565b506119aa81600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020611d4790919063ffffffff16565b506119c181836002611d619092919063ffffffff16565b50808273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60405160405180910390a4505050565b6000611a318360000183611d96565b60001c905092915050565b600080600080611a4f8660000186611e19565b915091508160001c8160001c9350935050509250929050565b6000611a7b846000018460001b84611eb2565b60001c90509392505050565b6000611a9582600001611fa8565b9050919050565b611aa78484846117df565b611ab384848484611fb9565b611b08576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526032815260200180612a1f6032913960400191505060405180910390fd5b50505050565b60606000821415611b56576040518060400160405280600181526020017f30000000000000000000000000000000000000000000000000000000000000008152509050611c50565b600082905060005b60008214611b80578080600101915050600a8281611b7857fe5b049150611b5e565b60608167ffffffffffffffff81118015611b9957600080fd5b506040519080825280601f01601f191660200182016040528015611bcc5781602001600182028036833780820191505090505b50905060006001830390508593505b60008414611c4857600a8481611bed57fe5b0660300160f81b82828060019003935081518110611c0757fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600a8481611c4057fe5b049350611bdb565b819450505050505b919050565b611c6f8282604051806020016040528060008152506121d2565b5050565b611c7c826115f8565b611cd1576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c815260200180612ba0602c913960400191505060405180910390fd5b80600860008481526020019081526020016000209080519060200190611cf8929190612951565b505050565b6000611d0f836000018360001b612243565b905092915050565b600081600001805490509050919050565b505050565b6000611d3f836000018360001b612266565b905092915050565b6000611d59836000018360001b61234e565b905092915050565b6000611d8d846000018460001b8473ffffffffffffffffffffffffffffffffffffffff1660001b6123be565b90509392505050565b600081836000018054905011611df7576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806129fd6022913960400191505060405180910390fd5b826000018281548110611e0657fe5b9060005260206000200154905092915050565b60008082846000018054905011611e7b576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180612b526022913960400191505060405180910390fd5b6000846000018481548110611e8c57fe5b906000526020600020906002020190508060000154816001015492509250509250929050565b60008084600101600085815260200190815260200160002054905060008114158390611f79576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611f3e578082015181840152602081019050611f23565b50505050905090810190601f168015611f6b5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b50846000016001820381548110611f8c57fe5b9060005260206000209060020201600101549150509392505050565b600081600001805490509050919050565b6000611fda8473ffffffffffffffffffffffffffffffffffffffff1661249a565b611fe757600190506121ca565b606061215163150b7a0260e01b611ffc611615565b888787604051602401808573ffffffffffffffffffffffffffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff16815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b83811015612080578082015181840152602081019050612065565b50505050905090810190601f1680156120ad5780820380516001836020036101000a031916815260200191505b5095505050505050604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050604051806060016040528060328152602001612a1f603291398773ffffffffffffffffffffffffffffffffffffffff166124ad9092919063ffffffff16565b9050600081806020019051602081101561216a57600080fd5b8101908080519060200190929190505050905063150b7a0260e01b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916817bffffffffffffffffffffffffffffffffffffffffffffffffffffffff191614925050505b949350505050565b6121dc83836124c5565b6121e96000848484611fb9565b61223e576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526032815260200180612a1f6032913960400191505060405180910390fd5b505050565b600080836001016000848152602001908152602001600020541415905092915050565b6000808360010160008481526020019081526020016000205490506000811461234257600060018203905060006001866000018054905003905060008660000182815481106122b157fe5b90600052602060002001549050808760000184815481106122ce57fe5b906000526020600020018190555060018301876001016000838152602001908152602001600020819055508660000180548061230657fe5b60019003818190600052602060002001600090559055866001016000878152602001908152602001600020600090556001945050505050612348565b60009150505b92915050565b600061235a83836126b9565b6123b35782600001829080600181540180825580915050600190039060005260206000200160009091909190915055826000018054905083600101600084815260200190815260200160002081905550600190506123b8565b600090505b92915050565b600080846001016000858152602001908152602001600020549050600081141561246557846000016040518060400160405280868152602001858152509080600181540180825580915050600190039060005260206000209060020201600090919091909150600082015181600001556020820151816001015550508460000180549050856001016000868152602001908152602001600020819055506001915050612493565b8285600001600183038154811061247857fe5b90600052602060002090600202016001018190555060009150505b9392505050565b600080823b905060008111915050919050565b60606124bc84846000856126dc565b90509392505050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415612568576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4552433732313a206d696e7420746f20746865207a65726f206164647265737381525060200191505060405180910390fd5b612571816115f8565b156125e4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601c8152602001807f4552433732313a20746f6b656e20616c7265616479206d696e7465640000000081525060200191505060405180910390fd5b6125f060008383611d28565b61264181600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020611d4790919063ffffffff16565b5061265881836002611d619092919063ffffffff16565b50808273ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60405160405180910390a45050565b600080836001016000848152602001908152602001600020541415905092915050565b606082471015612737576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526026815260200180612a756026913960400191505060405180910390fd5b6127408561249a565b6127b2576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000081525060200191505060405180910390fd5b600060608673ffffffffffffffffffffffffffffffffffffffff1685876040518082805190602001908083835b6020831061280257805182526020820191506020810190506020830392506127df565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d8060008114612864576040519150601f19603f3d011682016040523d82523d6000602084013e612869565b606091505b5091509150612879828286612885565b92505050949350505050565b606083156128955782905061294a565b6000835111156128a85782518084602001fd5b816040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561290f5780820151818401526020810190506128f4565b50505050905090810190601f16801561293c5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b9392505050565b828054600181600116156101000203166002900490600052602060002090601f01602090048101928261298757600085556129ce565b82601f106129a057805160ff19168380011785556129ce565b828001600101855582156129ce579182015b828111156129cd5782518255916020019190600101906129b2565b5b5090506129db91906129df565b5090565b5b808211156129f85760008160009055506001016129e0565b509056fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e64734552433732313a207472616e7366657220746f206e6f6e20455243373231526563656976657220696d706c656d656e7465724552433732313a207472616e7366657220746f20746865207a65726f2061646472657373416464726573733a20696e73756666696369656e742062616c616e636520666f722063616c6c4552433732313a206f70657261746f7220717565727920666f72206e6f6e6578697374656e7420746f6b656e4552433732313a20617070726f76652063616c6c6572206973206e6f74206f776e6572206e6f7220617070726f76656420666f7220616c6c4552433732313a2062616c616e636520717565727920666f7220746865207a65726f20616464726573734552433732313a206f776e657220717565727920666f72206e6f6e6578697374656e7420746f6b656e456e756d657261626c654d61703a20696e646578206f7574206f6620626f756e64734552433732313a20617070726f76656420717565727920666f72206e6f6e6578697374656e7420746f6b656e4552433732314d657461646174613a2055524920736574206f66206e6f6e6578697374656e7420746f6b656e4552433732313a207472616e73666572206f6620746f6b656e2074686174206973206e6f74206f776e4552433732314d657461646174613a2055524920717565727920666f72206e6f6e6578697374656e7420746f6b656e4552433732313a20617070726f76616c20746f2063757272656e74206f776e65724552433732313a207472616e736665722063616c6c6572206973206e6f74206f776e6572206e6f7220617070726f766564a2646970667358221220463e1849938b05ff1967f2c0be995137161619766e43791c68093c8a4707dfc064736f6c63430007040033
{"success": true, "error": null, "results": {"detectors": [{"check": "unused-return", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}]}
75
0x18b3388f5cf24aa1a1b61c1f492f31db9b52f672
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 CurveRegistry { function getSwapAndTotalCoins(address) external view returns (address, uint256); function getName(address) external view returns (string memory); } interface stableswap { function coins(int128) external view returns (address); function coins(uint256) external view returns (address); function balances(int128) external view returns (uint256); function balances(uint256) external view returns (uint256); } contract CurveTokenAdapter is TokenAdapter { address internal constant REGISTRY = 0x86A1755BA805ecc8B0608d56c22716bd1d4B68A8; address internal constant CDAI = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address internal constant CUSDC = 0x39AA39c021dfbaE8faC545936693aC917d5E7563; address internal constant YDAIV2 = 0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01; address internal constant YUSDCV2 = 0xd6aD7a6750A7593E092a9B218d66C0A814a3436e; address internal constant YUSDTV2 = 0x83f798e925BcD4017Eb265844FDDAbb448f1707D; address internal constant YTUSDV2 = 0x73a052500105205d34Daf004eAb301916DA8190f; address internal constant YDAIV3 = 0xC2cB1040220768554cf699b0d863A3cd4324ce32; address internal constant YUSDCV3 = 0x26EA744E5B887E5205727f55dFBE8685e3b21951; address internal constant YUSDTV3 = 0xE6354ed5bC4b393a5Aad09f21c46E101e692d447; address internal constant YBUSDV3 = 0x04bC0Ab673d88aE9dbC9DA2380cB6B79C4BCa9aE; address internal constant YCDAI = 0x99d1Fa417f94dcD62BfE781a1213c092a47041Bc; address internal constant YCUSDC = 0x9777d7E2b60bB01759D0E2f8be2095df444cb07E; address internal constant YCUSDT = 0x1bE5d71F2dA660BFdee8012dDc58D024448A0A59; address internal constant THREE_CRV = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; address internal constant HBTC_CRV = 0xb19059ebb43466C323583928285a49f558E572Fd; /** * @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: 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) { (address swap, uint256 totalCoins) = CurveRegistry(REGISTRY).getSwapAndTotalCoins(token); Component[] memory underlyingComponents = new Component[](totalCoins); address underlyingToken; if (token == THREE_CRV || token == HBTC_CRV) { for (uint256 i = 0; i < totalCoins; i++) { underlyingToken = stableswap(swap).coins(i); underlyingComponents[i] = Component({ token: underlyingToken, tokenType: getTokenType(underlyingToken), rate: stableswap(swap).balances(i) * 1e18 / ERC20(token).totalSupply() }); } } else { for (uint256 i = 0; i < totalCoins; i++) { underlyingToken = stableswap(swap).coins(int128(i)); underlyingComponents[i] = Component({ token: underlyingToken, tokenType: getTokenType(underlyingToken), rate: stableswap(swap).balances(int128(i)) * 1e18 / ERC20(token).totalSupply() }); } } return underlyingComponents; } /** * @return Pool name. */ function getPoolName(address token) internal view returns (string memory) { return CurveRegistry(REGISTRY).getName(token); } function getTokenType(address token) internal pure returns (string memory) { if (token == CDAI || token == CUSDC) { return "CToken"; } else if ( token == YDAIV2 || token == YUSDCV2 || token == YUSDTV2 || token == YTUSDV2 || token == YDAIV3 || token == YUSDCV3 || token == YUSDTV3 || token == YBUSDV3 || token == YCDAI || token == YCUSDC || token == YCUSDT ) { return "YToken"; } else { return "ERC20"; } } }
0x608060405234801561001057600080fd5b50600436106100365760003560e01c80632a50c1461461003b57806379b1833414610064575b600080fd5b61004e610049366004610c6e565b610084565b60405161005b9190610ef7565b60405180910390f35b610077610072366004610c6e565b6101f1565b60405161005b9190610e37565b61008c610bf6565b60405180608001604052808373ffffffffffffffffffffffffffffffffffffffff1681526020016100bc846107db565b81526020018373ffffffffffffffffffffffffffffffffffffffff166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b15801561010757600080fd5b505afa15801561011b573d6000803e3d6000fd5b505050506040513d6000823e601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682016040526101619190810190610cda565b81526020018373ffffffffffffffffffffffffffffffffffffffff1663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156101ac57600080fd5b505afa1580156101c0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101e49190610dab565b60ff16905290505b919050565b6040517f0668d80700000000000000000000000000000000000000000000000000000000815260609060009081907386a1755ba805ecc8b0608d56c22716bd1d4b68a890630668d80790610249908790600401610e16565b604080518083038186803b15801561026057600080fd5b505afa158015610274573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102989190610cad565b9150915060608167ffffffffffffffff811180156102b557600080fd5b506040519080825280602002602001820160405280156102ef57816020015b6102dc610c37565b8152602001906001900390816102d45790505b509050600073ffffffffffffffffffffffffffffffffffffffff8616736c3f90f043a72fa612cbac8115ee7e52bde6e4901480610355575073ffffffffffffffffffffffffffffffffffffffff861673b19059ebb43466c323583928285a49f558e572fd145b156105985760005b83811015610592576040517fc661065700000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff86169063c6610657906103b7908490600401610f87565b60206040518083038186803b1580156103cf57600080fd5b505afa1580156103e3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104079190610c91565b915060405180606001604052808373ffffffffffffffffffffffffffffffffffffffff168152602001610439846108a6565b81526020018873ffffffffffffffffffffffffffffffffffffffff166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561048457600080fd5b505afa158015610498573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104bc9190610d93565b6040517f4903b0d100000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff891690634903b0d19061050e908790600401610f87565b60206040518083038186803b15801561052657600080fd5b505afa15801561053a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061055e9190610d93565b670de0b6b3a7640000028161056f57fe5b0481525083828151811061057f57fe5b602090810291909101015260010161035d565b506107d2565b60005b838110156107d0576040517f23746eb800000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8616906323746eb8906105f5908490600401610ee9565b60206040518083038186803b15801561060d57600080fd5b505afa158015610621573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106459190610c91565b915060405180606001604052808373ffffffffffffffffffffffffffffffffffffffff168152602001610677846108a6565b81526020018873ffffffffffffffffffffffffffffffffffffffff166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156106c257600080fd5b505afa1580156106d6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106fa9190610d93565b6040517f065a80d800000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff89169063065a80d89061074c908790600401610ee9565b60206040518083038186803b15801561076457600080fd5b505afa158015610778573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061079c9190610d93565b670de0b6b3a764000002816107ad57fe5b048152508382815181106107bd57fe5b602090810291909101015260010161059b565b505b50949350505050565b6040517f5fd4b08a0000000000000000000000000000000000000000000000000000000081526060907386a1755ba805ecc8b0608d56c22716bd1d4b68a890635fd4b08a9061082e908590600401610e16565b60006040518083038186803b15801561084657600080fd5b505afa15801561085a573d6000803e3d6000fd5b505050506040513d6000823e601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682016040526108a09190810190610cda565b92915050565b606073ffffffffffffffffffffffffffffffffffffffff8216735d3a536e4d6dbd6114cc1ead35777bab948e36431480610909575073ffffffffffffffffffffffffffffffffffffffff82167339aa39c021dfbae8fac545936693ac917d5e7563145b15610948575060408051808201909152600681527f43546f6b656e000000000000000000000000000000000000000000000000000060208201526101ec565b73ffffffffffffffffffffffffffffffffffffffff82167316de59092dae5ccf4a1e6439d611fd0653f0bd0114806109a9575073ffffffffffffffffffffffffffffffffffffffff821673d6ad7a6750a7593e092a9b218d66c0a814a3436e145b806109dd575073ffffffffffffffffffffffffffffffffffffffff82167383f798e925bcd4017eb265844fddabb448f1707d145b80610a11575073ffffffffffffffffffffffffffffffffffffffff82167373a052500105205d34daf004eab301916da8190f145b80610a45575073ffffffffffffffffffffffffffffffffffffffff821673c2cb1040220768554cf699b0d863a3cd4324ce32145b80610a79575073ffffffffffffffffffffffffffffffffffffffff82167326ea744e5b887e5205727f55dfbe8685e3b21951145b80610aad575073ffffffffffffffffffffffffffffffffffffffff821673e6354ed5bc4b393a5aad09f21c46e101e692d447145b80610ae1575073ffffffffffffffffffffffffffffffffffffffff82167304bc0ab673d88ae9dbc9da2380cb6b79c4bca9ae145b80610b15575073ffffffffffffffffffffffffffffffffffffffff82167399d1fa417f94dcd62bfe781a1213c092a47041bc145b80610b49575073ffffffffffffffffffffffffffffffffffffffff8216739777d7e2b60bb01759d0e2f8be2095df444cb07e145b80610b7d575073ffffffffffffffffffffffffffffffffffffffff8216731be5d71f2da660bfdee8012ddc58d024448a0a59145b15610bbc575060408051808201909152600681527f59546f6b656e000000000000000000000000000000000000000000000000000060208201526101ec565b5060408051808201909152600581527f455243323000000000000000000000000000000000000000000000000000000060208201526101ec565b6040518060800160405280600073ffffffffffffffffffffffffffffffffffffffff1681526020016060815260200160608152602001600060ff1681525090565b6040518060600160405280600073ffffffffffffffffffffffffffffffffffffffff16815260200160608152602001600081525090565b600060208284031215610c7f578081fd5b8135610c8a81610fc0565b9392505050565b600060208284031215610ca2578081fd5b8151610c8a81610fc0565b60008060408385031215610cbf578081fd5b8251610cca81610fc0565b6020939093015192949293505050565b600060208284031215610ceb578081fd5b815167ffffffffffffffff80821115610d02578283fd5b81840185601f820112610d13578384fd5b8051925081831115610d23578384fd5b60405160207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f8601168201018181108482111715610d61578586fd5b604052838152818401602001871015610d78578485fd5b610d89846020830160208501610f90565b9695505050505050565b600060208284031215610da4578081fd5b5051919050565b600060208284031215610dbc578081fd5b815160ff81168114610c8a578182fd5b60008151808452610de4816020860160208601610f90565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b60208082528251828201819052600091906040908185019080840286018301878501865b83811015610edb577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc08984030185528151606073ffffffffffffffffffffffffffffffffffffffff825116855288820151818a870152610ebd82870182610dcc565b92890151958901959095525094870194925090860190600101610e5b565b509098975050505050505050565b600f9190910b815260200190565b60006020825273ffffffffffffffffffffffffffffffffffffffff8351166020830152602083015160806040840152610f3360a0840182610dcc565b604085015191507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0848203016060850152610f6e8183610dcc565b60ff606087015116608086015280935050505092915050565b90815260200190565b60005b83811015610fab578181015183820152602001610f93565b83811115610fba576000848401525b50505050565b73ffffffffffffffffffffffffffffffffffffffff81168114610fe257600080fd5b5056fea264697066735822122074fffc47c8f1e82251e76ce9af8b44e2655b588ab7f22e2b4c2da80d4342ac5d64736f6c63430006050033
{"success": true, "error": null, "results": {}}
true
null
{}
76
0x18CfB667F10c004f9534eA3C928b864d14c8fc11
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IComptroller { function enterMarkets(address[] calldata _cTokens) external returns (uint[] memory); function exitMarket(address _cToken) external returns (uint); function getAssetsIn(address _account) external view returns (address[] memory); function getAccountLiquidity(address _account) external view returns (uint, uint, uint); function checkMembership(address account, ICToken cToken) external view returns (bool); } interface ICToken { function comptroller() external view returns (address); function underlying() external view returns (address); function symbol() external view returns (string memory); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function balanceOf(address _account) external view returns (uint256); function borrowBalanceCurrent(address _account) external returns (uint256); function borrowBalanceStored(address _account) external view returns (uint256); } 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 ICompoundRegistry { function addCToken(address _underlying, address _cToken) external; function removeCToken(address _underlying) external; function getCToken(address _underlying) external view returns (address); function listUnderlyings() external view returns (address[] memory); } 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 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 CompoundManager is BaseFeature{ bytes32 constant NAME = "CompoundManager"; // The Compound IComptroller contract IComptroller public comptroller; // The registry mapping underlying with cTokens ICompoundRegistry public compoundRegistry; event InvestmentAdded(address indexed _wallet, address _token, uint256 _invested, uint256 _period); event InvestmentRemoved(address indexed _wallet, address _token, uint256 _fraction); event LoanOpened( address indexed _wallet, bytes32 indexed _loanId, address _collateral, uint256 _collateralAmount, address _debtToken, uint256 _debtAmount); event LoanClosed(address indexed _wallet, bytes32 indexed _loanId); event CollateralAdded(address indexed _wallet, bytes32 indexed _loanId, address _collateral, uint256 _collateralAmount); event CollateralRemoved(address indexed _wallet, bytes32 indexed _loanId, address _collateral, uint256 _collateralAmount); event DebtAdded(address indexed _wallet, bytes32 indexed _loanId, address _debtToken, uint256 _debtAmount); event DebtRemoved(address indexed _wallet, bytes32 indexed _loanId, address _debtToken, uint256 _debtAmount); using SafeMath for uint256; constructor( ILockStorage _lockStorage, IComptroller _comptroller, ICompoundRegistry _compoundRegistry, IVersionManager _versionManager ) BaseFeature(_lockStorage, _versionManager, NAME) public { comptroller = _comptroller; compoundRegistry = _compoundRegistry; } /** * @inheritdoc IFeature */ function getRequiredSignatures(address, bytes calldata) external view override returns (uint256, OwnerSignature) { return (1, OwnerSignature.Required); } /* ********************************** Implementation of Loan ************************************* */ /** * @notice Opens a collateralized loan. * @param _wallet The target wallet. * @param _collateral The token used as a collateral. * @param _collateralAmount The amount of collateral token provided. * @param _debtToken The token borrowed. * @param _debtAmount The amount of tokens borrowed. * @return _loanId bytes32(0) as Compound does not allow the creation of multiple loans. */ function openLoan( address _wallet, address _collateral, uint256 _collateralAmount, address _debtToken, uint256 _debtAmount ) external onlyWalletOwnerOrFeature(_wallet) onlyWhenUnlocked(_wallet) returns (bytes32 _loanId) { address[] memory markets = new address[](2); markets[0] = compoundRegistry.getCToken(_collateral); markets[1] = compoundRegistry.getCToken(_debtToken); invokeWallet(_wallet, address(comptroller), 0, abi.encodeWithSignature("enterMarkets(address[])", markets)); mint(_wallet, markets[0], _collateral, _collateralAmount); borrow(_wallet, _debtToken, markets[1], _debtAmount); emit LoanOpened(_wallet, _loanId, _collateral, _collateralAmount, _debtToken, _debtAmount); } /** * @notice Closes the collateralized loan in all markets by repaying all debts (plus interest). Note that it does not redeem the collateral. * @param _wallet The target wallet. * @param _loanId bytes32(0) as Compound does not allow the creation of multiple loans. */ function closeLoan( address _wallet, bytes32 _loanId ) external onlyWalletOwnerOrFeature(_wallet) onlyWhenUnlocked(_wallet) { address[] memory markets = comptroller.getAssetsIn(_wallet); for (uint i = 0; i < markets.length; i++) { address cToken = markets[i]; uint debt = ICToken(cToken).borrowBalanceCurrent(_wallet); if (debt > 0) { repayBorrow(_wallet, cToken, debt); uint collateral = ICToken(cToken).balanceOf(_wallet); if (collateral == 0) { invokeWallet( _wallet, address(comptroller), 0, abi.encodeWithSignature("exitMarket(address)", address(cToken)) ); } } } emit LoanClosed(_wallet, _loanId); } /** * @notice Adds collateral to a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId bytes32(0) as Compound does not allow the creation of multiple loans. * @param _collateral The token used as a collateral. * @param _collateralAmount The amount of collateral to add. */ function addCollateral( address _wallet, bytes32 _loanId, address _collateral, uint256 _collateralAmount ) external onlyWalletOwnerOrFeature(_wallet) onlyWhenUnlocked(_wallet) { address cToken = compoundRegistry.getCToken(_collateral); enterMarketIfNeeded(_wallet, cToken, address(comptroller)); mint(_wallet, cToken, _collateral, _collateralAmount); emit CollateralAdded(_wallet, _loanId, _collateral, _collateralAmount); } /** * @notice Removes collateral from a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId bytes32(0) as Compound does not allow the creation of multiple loans. * @param _collateral The token used as a collateral. * @param _collateralAmount The amount of collateral to remove. */ function removeCollateral( address _wallet, bytes32 _loanId, address _collateral, uint256 _collateralAmount ) external onlyWalletOwnerOrFeature(_wallet) onlyWhenUnlocked(_wallet) { address cToken = compoundRegistry.getCToken(_collateral); redeemUnderlying(_wallet, cToken, _collateralAmount); exitMarketIfNeeded(_wallet, cToken, address(comptroller)); emit CollateralRemoved(_wallet, _loanId, _collateral, _collateralAmount); } /** * @notice Increases the debt by borrowing more token from a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId bytes32(0) as Compound does not allow the creation of multiple loans. * @param _debtToken The token borrowed. * @param _debtAmount The amount of token to borrow. */ function addDebt( address _wallet, bytes32 _loanId, address _debtToken, uint256 _debtAmount ) external onlyWalletOwnerOrFeature(_wallet) onlyWhenUnlocked(_wallet) { address dToken = compoundRegistry.getCToken(_debtToken); enterMarketIfNeeded(_wallet, dToken, address(comptroller)); borrow(_wallet, _debtToken, dToken, _debtAmount); emit DebtAdded(_wallet, _loanId, _debtToken, _debtAmount); } /** * @notice Decreases the debt by repaying some token from a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId bytes32(0) as Compound does not allow the creation of multiple loans. * @param _debtToken The token to repay. * @param _debtAmount The amount of token to repay. */ function removeDebt( address _wallet, bytes32 _loanId, address _debtToken, uint256 _debtAmount ) external onlyWalletOwnerOrFeature(_wallet) onlyWhenUnlocked(_wallet) { address dToken = compoundRegistry.getCToken(_debtToken); repayBorrow(_wallet, dToken, _debtAmount); exitMarketIfNeeded(_wallet, dToken, address(comptroller)); emit DebtRemoved(_wallet, _loanId, _debtToken, _debtAmount); } /** * @notice Gets information about the loan status on Compound. * @param _wallet The target wallet. * @return _status Status [0: no loan, 1: loan is safe, 2: loan is unsafe and can be liquidated] * @return _ethValue Value (in ETH) representing the value that could still be borrowed when status = 1; or the value of the collateral * that should be added to avoid liquidation when status = 2. */ function getLoan( address _wallet, bytes32 /* _loanId */ ) external view returns (uint8 _status, uint256 _ethValue) { (uint error, uint liquidity, uint shortfall) = comptroller.getAccountLiquidity(_wallet); require(error == 0, "CM: failed to get account liquidity"); if (liquidity > 0) { return (1, liquidity); } if (shortfall > 0) { return (2, shortfall); } return (0,0); } /* ********************************** Implementation of Invest ************************************* */ /** * @notice Invest tokens for a given period. * @param _wallet The target wallet. * @param _token The token address. * @param _amount The amount of tokens to invest. * @param _period The period over which the tokens may be locked in the investment (optional). * @return _invested The exact amount of tokens that have been invested. */ function addInvestment( address _wallet, address _token, uint256 _amount, uint256 _period ) external onlyWalletOwnerOrFeature(_wallet) onlyWhenUnlocked(_wallet) returns (uint256 _invested) { address cToken = compoundRegistry.getCToken(_token); mint(_wallet, cToken, _token, _amount); _invested = _amount; emit InvestmentAdded(_wallet, _token, _amount, _period); } /** * @notice Exit invested postions. * @param _wallet The target wallet. * @param _token The token address. * @param _fraction The fraction of invested tokens to exit in per 10000. */ function removeInvestment( address _wallet, address _token, uint256 _fraction ) external onlyWalletOwnerOrFeature(_wallet) onlyWhenUnlocked(_wallet) { require(_fraction <= 10000, "CM: invalid fraction value"); address cToken = compoundRegistry.getCToken(_token); uint shares = ICToken(cToken).balanceOf(_wallet); redeem(_wallet, cToken, shares.mul(_fraction).div(10000)); emit InvestmentRemoved(_wallet, _token, _fraction); } /** * @notice Get the amount of investment in a given token. * @param _wallet The target wallet. * @param _token The token address. * @return _tokenValue The value in tokens of the investment (including interests). * @return _periodEnd The time at which the investment can be removed. */ function getInvestment( address _wallet, address _token ) external view returns (uint256 _tokenValue, uint256 _periodEnd) { address cToken = compoundRegistry.getCToken(_token); uint amount = ICToken(cToken).balanceOf(_wallet); uint exchangeRateMantissa = ICToken(cToken).exchangeRateStored(); _tokenValue = amount.mul(exchangeRateMantissa).div(10 ** 18); _periodEnd = 0; } /* ****************************************** Compound wrappers ******************************************* */ /** * @notice Adds underlying tokens to a cToken contract. * @param _wallet The target wallet. * @param _cToken The cToken contract. * @param _token The underlying token. * @param _amount The amount of underlying token to add. */ function mint(address _wallet, address _cToken, address _token, uint256 _amount) internal { require(_cToken != address(0), "CM: No market for target token"); require(_amount > 0, "CM: amount cannot be 0"); uint256 initialCTokenAmount = ERC20(_cToken).balanceOf(_wallet); if (_token == ETH_TOKEN) { invokeWallet(_wallet, _cToken, _amount, abi.encodeWithSignature("mint()")); } else { invokeWallet(_wallet, _token, 0, abi.encodeWithSignature("approve(address,uint256)", _cToken, _amount)); invokeWallet(_wallet, _cToken, 0, abi.encodeWithSignature("mint(uint256)", _amount)); } require(ERC20(_cToken).balanceOf(_wallet) > initialCTokenAmount, "CM: mint failed"); } /** * @notice Redeems underlying tokens from a cToken contract. * @param _wallet The target wallet. * @param _cToken The cToken contract. * @param _amount The amount of cToken to redeem. */ function redeem(address _wallet, address _cToken, uint256 _amount) internal { // The following commented `require()` is not necessary as `ICToken(cToken).balanceOf(_wallet)` in `removeInvestment()` // would have reverted if `_cToken == address(0)` // It is however left as a comment as a reminder to include it if `removeInvestment()` is changed to use amounts instead of fractions. // require(_cToken != address(0), "CM: No market for target token"); require(_amount > 0, "CM: amount cannot be 0"); uint256 initialCTokenAmount = ERC20(_cToken).balanceOf(_wallet); invokeWallet(_wallet, _cToken, 0, abi.encodeWithSignature("redeem(uint256)", _amount)); require(ERC20(_cToken).balanceOf(_wallet) < initialCTokenAmount, "CM: redeem failed"); } /** * @notice Redeems underlying tokens from a cToken contract. * @param _wallet The target wallet. * @param _cToken The cToken contract. * @param _amount The amount of underlying token to redeem. */ function redeemUnderlying(address _wallet, address _cToken, uint256 _amount) internal { require(_cToken != address(0), "CM: No market for target token"); require(_amount > 0, "CM: amount cannot be 0"); uint256 initialCTokenAmount = ERC20(_cToken).balanceOf(_wallet); invokeWallet(_wallet, _cToken, 0, abi.encodeWithSignature("redeemUnderlying(uint256)", _amount)); require(ERC20(_cToken).balanceOf(_wallet) < initialCTokenAmount, "CM: redeemUnderlying failed"); } /** * @notice Borrows underlying tokens from a cToken contract. * @param _wallet The target wallet. * @param _token The token contract. * @param _cToken The cToken contract. * @param _amount The amount of underlying tokens to borrow. */ function borrow(address _wallet, address _token, address _cToken, uint256 _amount) internal { require(_cToken != address(0), "CM: No market for target token"); require(_amount > 0, "CM: amount cannot be 0"); uint256 initialTokenAmount = _token == ETH_TOKEN ? _wallet.balance : ERC20(_token).balanceOf(_wallet); invokeWallet(_wallet, _cToken, 0, abi.encodeWithSignature("borrow(uint256)", _amount)); uint256 finalTokenAmount = _token == ETH_TOKEN ? _wallet.balance : ERC20(_token).balanceOf(_wallet); require(finalTokenAmount > initialTokenAmount, "CM: borrow failed"); } /** * @notice Repays some borrowed underlying tokens to a cToken contract. * @param _wallet The target wallet. * @param _cToken The cToken contract. * @param _amount The amount of underlying to repay. */ function repayBorrow(address _wallet, address _cToken, uint256 _amount) internal { require(_cToken != address(0), "CM: No market for target token"); require(_amount > 0, "CM: amount cannot be 0"); string memory symbol = ICToken(_cToken).symbol(); uint256 initialTokenAmount; uint256 finalTokenAmount; if (keccak256(abi.encodePacked(symbol)) == keccak256(abi.encodePacked("cETH"))) { initialTokenAmount = _wallet.balance; invokeWallet(_wallet, _cToken, _amount, abi.encodeWithSignature("repayBorrow()")); finalTokenAmount = _wallet.balance; } else { address token = ICToken(_cToken).underlying(); initialTokenAmount = ERC20(token).balanceOf(_wallet); invokeWallet(_wallet, token, 0, abi.encodeWithSignature("approve(address,uint256)", _cToken, _amount)); invokeWallet(_wallet, _cToken, 0, abi.encodeWithSignature("repayBorrow(uint256)", _amount)); finalTokenAmount = ERC20(token).balanceOf(_wallet); } require(finalTokenAmount < initialTokenAmount, "CM: repayBorrow failed"); } /** * @notice Enters a cToken market if it was not entered before. * @param _wallet The target wallet. * @param _cToken The cToken contract. * @param _comptroller The comptroller contract. */ function enterMarketIfNeeded(address _wallet, address _cToken, address _comptroller) internal { bool isEntered = IComptroller(_comptroller).checkMembership(_wallet, ICToken(_cToken)); if (!isEntered) { address[] memory market = new address[](1); market[0] = _cToken; invokeWallet(_wallet, _comptroller, 0, abi.encodeWithSignature("enterMarkets(address[])", market)); } } /** * @notice Exits a cToken market if there is no more collateral and debt. * @param _wallet The target wallet. * @param _cToken The cToken contract. * @param _comptroller The comptroller contract. */ function exitMarketIfNeeded(address _wallet, address _cToken, address _comptroller) internal { uint collateral = ICToken(_cToken).balanceOf(_wallet); uint debt = ICToken(_cToken).borrowBalanceStored(_wallet); if (collateral == 0 && debt == 0) { invokeWallet(_wallet, _comptroller, 0, abi.encodeWithSignature("exitMarket(address)", _cToken)); } } }
0x608060405234801561001057600080fd5b506004361061011b5760003560e01c8063a287fdbd116100b2578063b352d4af11610081578063e8ca0ca311610066578063e8ca0ca31461047a578063ea2347e6146104b4578063ec9e13aa1461050c5761011b565b8063b352d4af146103f9578063cac7495c146104335761011b565b8063a287fdbd146102fb578063a90cf0af1461033d578063ac5f8d5114610369578063b02c808d146103a35761011b565b806381c44b5c116100ee57806381c44b5c1461021c57806385a13f381461026557806398d534281461029f5780639be65a60146102d55761011b565b806319ab453c146101205780633b73d67f1461014857806347eb8d43146101f05780635fe3b56714610214575b600080fd5b6101466004803603602081101561013657600080fd5b50356001600160a01b0316610548565b005b6101c86004803603604081101561015e57600080fd5b6001600160a01b03823516919081019060408101602082013564010000000081111561018957600080fd5b82018360208201111561019b57600080fd5b803590602001918460018302840111640100000000831117156101bd57600080fd5b50909250905061054b565b604051808381526020018260038111156101de57fe5b81526020019250505060405180910390f35b6101f8610556565b604080516001600160a01b039092168252519081900360200190f35b6101f8610565565b6102486004803603604081101561023257600080fd5b506001600160a01b038135169060200135610574565b6040805160ff909316835260208301919091528051918290030190f35b6101466004803603608081101561027b57600080fd5b506001600160a01b0381358116916020810135916040820135169060600135610695565b610146600480360360608110156102b557600080fd5b506001600160a01b03813581169160208101359091169060400135610859565b610146600480360360208110156102eb57600080fd5b50356001600160a01b0316610ae7565b6103296004803603604081101561031157600080fd5b506001600160a01b0381358116916020013516610c66565b604080519115158252519081900360200190f35b6101466004803603604081101561035357600080fd5b506001600160a01b038135169060200135610d0d565b6101466004803603608081101561037f57600080fd5b506001600160a01b03813581169160208101359160408201351690606001356110e8565b6103e7600480360360a08110156103b957600080fd5b506001600160a01b0381358116916020810135821691604082013591606081013590911690608001356112aa565b60408051918252519081900360200190f35b6101466004803603608081101561040f57600080fd5b506001600160a01b038135811691602081013591604082013516906060013561161a565b6104616004803603604081101561044957600080fd5b506001600160a01b03813581169160200135166117de565b6040805192835260208301919091528051918290030190f35b6101466004803603608081101561049057600080fd5b506001600160a01b038135811691602081013591604082013516906060013561198a565b6104bc611b4c565b60408051602080825283518183015283519192839290830191858101910280838360005b838110156104f85781810151838201526020016104e0565b505050509050019250505060405180910390f35b6103e76004803603608081101561052257600080fd5b506001600160a01b03813581169160208101359091169060408101359060600135611b51565b50565b600180935093915050565b6003546001600160a01b031681565b6002546001600160a01b031681565b6000806000806000600260009054906101000a90046001600160a01b03166001600160a01b0316635ec88c79886040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060606040518083038186803b1580156105de57600080fd5b505afa1580156105f2573d6000803e3d6000fd5b505050506040513d606081101561060857600080fd5b50805160208201516040909201519094509092509050821561065b5760405162461bcd60e51b81526004018080602001828103825260238152602001806133966023913960400191505060405180910390fd5b811561066f575060019350915061068e9050565b80156106835760029450925061068e915050565b600080945094505050505b9250929050565b836106a08133611d07565b60005460408051631293efbb60e21b81526001600160a01b038089166004830152915188939290921691634a4fbeec91602480820192602092909190829003018186803b1580156106f057600080fd5b505afa158015610704573d6000803e3d6000fd5b505050506040513d602081101561071a57600080fd5b505115610762576040805162461bcd60e51b815260206004820152601160248201527010918e881dd85b1b195d081b1bd8dad959607a1b604482015290519081900360640190fd5b60035460408051637e5a4eb960e01b81526001600160a01b03878116600483015291516000939290921691637e5a4eb991602480820192602092909190829003018186803b1580156107b357600080fd5b505afa1580156107c7573d6000803e3d6000fd5b505050506040513d60208110156107dd57600080fd5b50516002549091506107fb90889083906001600160a01b0316611d76565b61080787868387611eac565b604080516001600160a01b0387811682526020820187905282518993918b16927ff6669d5e7ff92997c22e9fe3b54f53ed18448cf5fdccb3eb1dc5004798fbb41492908290030190a350505050505050565b826108648133611d07565b60005460408051631293efbb60e21b81526001600160a01b038088166004830152915187939290921691634a4fbeec91602480820192602092909190829003018186803b1580156108b457600080fd5b505afa1580156108c8573d6000803e3d6000fd5b505050506040513d60208110156108de57600080fd5b505115610926576040805162461bcd60e51b815260206004820152601160248201527010918e881dd85b1b195d081b1bd8dad959607a1b604482015290519081900360640190fd5b61271083111561097d576040805162461bcd60e51b815260206004820152601a60248201527f434d3a20696e76616c6964206672616374696f6e2076616c7565000000000000604482015290519081900360640190fd5b60035460408051637e5a4eb960e01b81526001600160a01b03878116600483015291516000939290921691637e5a4eb991602480820192602092909190829003018186803b1580156109ce57600080fd5b505afa1580156109e2573d6000803e3d6000fd5b505050506040513d60208110156109f857600080fd5b5051604080516370a0823160e01b81526001600160a01b0389811660048301529151929350600092918416916370a0823191602480820192602092909190829003018186803b158015610a4a57600080fd5b505afa158015610a5e573d6000803e3d6000fd5b505050506040513d6020811015610a7457600080fd5b50519050610a988783610a93612710610a8d868b612170565b906121d0565b612212565b604080516001600160a01b038881168252602082018890528251908a16927f9aa275f858ea6286ee2cacd32cd2ae55f918a310ee6d0320caad244ee9d6109e928290030190a250505050505050565b6000816001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015610b3657600080fd5b505afa158015610b4a573d6000803e3d6000fd5b505050506040513d6020811015610b6057600080fd5b5051600154604080516001600160a01b039283166024820152604480820185905282518083039091018152606490910182526020810180516001600160e01b03167fa9059cbb00000000000000000000000000000000000000000000000000000000178152915181519495509286169390929182918083835b60208310610bf85780518252601f199092019160209182019101610bd9565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114610c5a576040519150601f19603f3d011682016040523d82523d6000602084013e610c5f565b606091505b5050505050565b600154604080517f5a51fd430000000000000000000000000000000000000000000000000000000081526001600160a01b038581166004830152848116602483015291516000939290921691635a51fd4391604480820192602092909190829003018186803b158015610cd857600080fd5b505afa158015610cec573d6000803e3d6000fd5b505050506040513d6020811015610d0257600080fd5b505190505b92915050565b81610d188133611d07565b60005460408051631293efbb60e21b81526001600160a01b038087166004830152915186939290921691634a4fbeec91602480820192602092909190829003018186803b158015610d6857600080fd5b505afa158015610d7c573d6000803e3d6000fd5b505050506040513d6020811015610d9257600080fd5b505115610dda576040805162461bcd60e51b815260206004820152601160248201527010918e881dd85b1b195d081b1bd8dad959607a1b604482015290519081900360640190fd5b600254604080517fabfceffc0000000000000000000000000000000000000000000000000000000081526001600160a01b0387811660048301529151606093929092169163abfceffc91602480820192600092909190829003018186803b158015610e4457600080fd5b505afa158015610e58573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526020811015610e8157600080fd5b8101908080516040519392919084640100000000821115610ea157600080fd5b908301906020820185811115610eb657600080fd5b8251866020820283011164010000000082111715610ed357600080fd5b82525081516020918201928201910280838360005b83811015610f00578181015183820152602001610ee8565b50505050905001604052505050905060005b81518110156110aa576000828281518110610f2957fe5b602002602001015190506000816001600160a01b03166317bfdfbc896040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b158015610f8457600080fd5b505af1158015610f98573d6000803e3d6000fd5b505050506040513d6020811015610fae57600080fd5b5051905080156110a057610fc388838361240c565b6000826001600160a01b03166370a082318a6040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b15801561101257600080fd5b505afa158015611026573d6000803e3d6000fd5b505050506040513d602081101561103c57600080fd5b505190508061109e57600254604080516001600160a01b038681166024808401919091528351808403909101815260449092019092526020810180516001600160e01b0316630ede4edd60e41b17905261109c928c92169060009061297b565b505b505b5050600101610f12565b5060405184906001600160a01b038716907f07e4a0c6f06275f83bcf78e5a10eb7f5515574d593bce993377961f4133b951c90600090a35050505050565b836110f38133611d07565b60005460408051631293efbb60e21b81526001600160a01b038089166004830152915188939290921691634a4fbeec91602480820192602092909190829003018186803b15801561114357600080fd5b505afa158015611157573d6000803e3d6000fd5b505050506040513d602081101561116d57600080fd5b5051156111b5576040805162461bcd60e51b815260206004820152601160248201527010918e881dd85b1b195d081b1bd8dad959607a1b604482015290519081900360640190fd5b60035460408051637e5a4eb960e01b81526001600160a01b03878116600483015291516000939290921691637e5a4eb991602480820192602092909190829003018186803b15801561120657600080fd5b505afa15801561121a573d6000803e3d6000fd5b505050506040513d602081101561123057600080fd5b5051905061123f878286612b5c565b60025461125890889083906001600160a01b0316612db1565b604080516001600160a01b0387811682526020820187905282518993918b16927ff1dec7a92ef063b16d2098bb05803ed604936a7ff30f0d245fe881baf96e8e6b92908290030190a350505050505050565b6000856112b78133611d07565b60005460408051631293efbb60e21b81526001600160a01b03808b16600483015291518a939290921691634a4fbeec91602480820192602092909190829003018186803b15801561130757600080fd5b505afa15801561131b573d6000803e3d6000fd5b505050506040513d602081101561133157600080fd5b505115611379576040805162461bcd60e51b815260206004820152601160248201527010918e881dd85b1b195d081b1bd8dad959607a1b604482015290519081900360640190fd5b6040805160028082526060808301845292602083019080368337505060035460408051637e5a4eb960e01b81526001600160a01b038d811660048301529151949550911692637e5a4eb992506024808301926020929190829003018186803b1580156113e457600080fd5b505afa1580156113f8573d6000803e3d6000fd5b505050506040513d602081101561140e57600080fd5b50518151829060009061141d57fe5b6001600160a01b0392831660209182029290920181019190915260035460408051637e5a4eb960e01b81528a8516600482015290519190931692637e5a4eb9926024808301939192829003018186803b15801561147957600080fd5b505afa15801561148d573d6000803e3d6000fd5b505050506040513d60208110156114a357600080fd5b50518151829060019081106114b457fe5b6001600160a01b0392831660209182029290920181019190915260025460405160248101838152855160448301528551611575958f9594169360009388939283926064909201918581019102808383895b8381101561151d578181015183820152602001611505565b50506040805193909501838103601f19018452909452506020810180517fc2998238000000000000000000000000000000000000000000000000000000006001600160e01b03909116179052945061297b9350505050565b50611596898260008151811061158757fe5b60200260200101518a8a612f27565b6115b68987836001815181106115a857fe5b602002602001015188611eac565b604080516001600160a01b038a81168252602082018a90528881168284015260608201889052915186928c16917ff9d7e11fb5d8d1e0a4be344a6a6adfb912161747edf926fb283150d07c39c108919081900360800190a350505095945050505050565b836116258133611d07565b60005460408051631293efbb60e21b81526001600160a01b038089166004830152915188939290921691634a4fbeec91602480820192602092909190829003018186803b15801561167557600080fd5b505afa158015611689573d6000803e3d6000fd5b505050506040513d602081101561169f57600080fd5b5051156116e7576040805162461bcd60e51b815260206004820152601160248201527010918e881dd85b1b195d081b1bd8dad959607a1b604482015290519081900360640190fd5b60035460408051637e5a4eb960e01b81526001600160a01b03878116600483015291516000939290921691637e5a4eb991602480820192602092909190829003018186803b15801561173857600080fd5b505afa15801561174c573d6000803e3d6000fd5b505050506040513d602081101561176257600080fd5b505160025490915061178090889083906001600160a01b0316611d76565b61178c87828787612f27565b604080516001600160a01b0387811682526020820187905282518993918b16927fdd016248708c391ccb5c72f9258127c75b9b291ac1479513fe4f331c3489013792908290030190a350505050505050565b60035460408051637e5a4eb960e01b81526001600160a01b038481166004830152915160009384938493911691637e5a4eb991602480820192602092909190829003018186803b15801561183157600080fd5b505afa158015611845573d6000803e3d6000fd5b505050506040513d602081101561185b57600080fd5b5051604080516370a0823160e01b81526001600160a01b0388811660048301529151929350600092918416916370a0823191602480820192602092909190829003018186803b1580156118ad57600080fd5b505afa1580156118c1573d6000803e3d6000fd5b505050506040513d60208110156118d757600080fd5b5051604080517f182df0f500000000000000000000000000000000000000000000000000000000815290519192506000916001600160a01b0385169163182df0f5916004808301926020929190829003018186803b15801561193857600080fd5b505afa15801561194c573d6000803e3d6000fd5b505050506040513d602081101561196257600080fd5b5051905061197c670de0b6b3a7640000610a8d8484612170565b976000975095505050505050565b836119958133611d07565b60005460408051631293efbb60e21b81526001600160a01b038089166004830152915188939290921691634a4fbeec91602480820192602092909190829003018186803b1580156119e557600080fd5b505afa1580156119f9573d6000803e3d6000fd5b505050506040513d6020811015611a0f57600080fd5b505115611a57576040805162461bcd60e51b815260206004820152601160248201527010918e881dd85b1b195d081b1bd8dad959607a1b604482015290519081900360640190fd5b60035460408051637e5a4eb960e01b81526001600160a01b03878116600483015291516000939290921691637e5a4eb991602480820192602092909190829003018186803b158015611aa857600080fd5b505afa158015611abc573d6000803e3d6000fd5b505050506040513d6020811015611ad257600080fd5b50519050611ae187828661240c565b600254611afa90889083906001600160a01b0316612db1565b604080516001600160a01b0387811682526020820187905282518993918b16927fbfa42ea7d37497e6a09441fadba47d64b610b6b1183d895dd0a42507973430bf92908290030190a350505050505050565b606090565b600084611b5e8133611d07565b60005460408051631293efbb60e21b81526001600160a01b03808a166004830152915189939290921691634a4fbeec91602480820192602092909190829003018186803b158015611bae57600080fd5b505afa158015611bc2573d6000803e3d6000fd5b505050506040513d6020811015611bd857600080fd5b505115611c20576040805162461bcd60e51b815260206004820152601160248201527010918e881dd85b1b195d081b1bd8dad959607a1b604482015290519081900360640190fd5b60035460408051637e5a4eb960e01b81526001600160a01b03898116600483015291516000939290921691637e5a4eb991602480820192602092909190829003018186803b158015611c7157600080fd5b505afa158015611c85573d6000803e3d6000fd5b505050506040513d6020811015611c9b57600080fd5b50519050611cab88828989612f27565b604080516001600160a01b038981168252602082018990528183018890529151889650918a16917ff8eece150ed2126815122a6def9737751aecd814379d4ce8c9edd07133a49cdb9181900360600190a2505050949350505050565b611d118282610c66565b80611d215750611d218282613250565b611d72576040805162461bcd60e51b815260206004820152601c60248201527f42463a206d757374206265206f776e6572206f72206665617475726500000000604482015290519081900360640190fd5b5050565b6000816001600160a01b031663929fe9a185856040518363ffffffff1660e01b815260040180836001600160a01b03168152602001826001600160a01b031681526020019250505060206040518083038186803b158015611dd657600080fd5b505afa158015611dea573d6000803e3d6000fd5b505050506040513d6020811015611e0057600080fd5b5051905080611ea657604080516001808252818301909252606091602080830190803683370190505090508381600081518110611e3957fe5b60200260200101906001600160a01b031690816001600160a01b031681525050611ea385846000846040516024018080602001828103825283818151815260200191508051906020019060200280838360008381101561151d578181015183820152602001611505565b50505b50505050565b6001600160a01b038216611f07576040805162461bcd60e51b815260206004820152601e60248201527f434d3a204e6f206d61726b657420666f722074617267657420746f6b656e0000604482015290519081900360640190fd5b60008111611f55576040805162461bcd60e51b81526020600482015260166024820152750434d3a20616d6f756e742063616e6e6f7420626520360541b604482015290519081900360640190fd5b60006001600160a01b03841673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14611ff957836001600160a01b03166370a08231866040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015611fc857600080fd5b505afa158015611fdc573d6000803e3d6000fd5b505050506040513d6020811015611ff257600080fd5b5051612005565b846001600160a01b0316315b6040805160248082018690528251808303909101815260449091019091526020810180516001600160e01b03167fc5ebeaec00000000000000000000000000000000000000000000000000000000179052909150612069908690859060009061297b565b5060006001600160a01b03851673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1461210e57846001600160a01b03166370a08231876040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b1580156120dd57600080fd5b505afa1580156120f1573d6000803e3d6000fd5b505050506040513d602081101561210757600080fd5b505161211a565b856001600160a01b0316315b9050818111611ea3576040805162461bcd60e51b815260206004820152601160248201527f434d3a20626f72726f77206661696c6564000000000000000000000000000000604482015290519081900360640190fd5b60008261217f57506000610d07565b8282028284828161218c57fe5b04146121c95760405162461bcd60e51b81526004018080602001828103825260218152602001806133756021913960400191505060405180910390fd5b9392505050565b60006121c983836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f0000000000008152506132d2565b60008111612260576040805162461bcd60e51b81526020600482015260166024820152750434d3a20616d6f756e742063616e6e6f7420626520360541b604482015290519081900360640190fd5b6000826001600160a01b03166370a08231856040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b1580156122af57600080fd5b505afa1580156122c3573d6000803e3d6000fd5b505050506040513d60208110156122d957600080fd5b50516040805160248082018690528251808303909101815260449091019091526020810180516001600160e01b03167fdb006a750000000000000000000000000000000000000000000000000000000017905290915061233f908590859060009061297b565b5080836001600160a01b03166370a08231866040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b15801561238e57600080fd5b505afa1580156123a2573d6000803e3d6000fd5b505050506040513d60208110156123b857600080fd5b505110611ea6576040805162461bcd60e51b815260206004820152601160248201527f434d3a2072656465656d206661696c6564000000000000000000000000000000604482015290519081900360640190fd5b6001600160a01b038216612467576040805162461bcd60e51b815260206004820152601e60248201527f434d3a204e6f206d61726b657420666f722074617267657420746f6b656e0000604482015290519081900360640190fd5b600081116124b5576040805162461bcd60e51b81526020600482015260166024820152750434d3a20616d6f756e742063616e6e6f7420626520360541b604482015290519081900360640190fd5b6060826001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b1580156124f057600080fd5b505afa158015612504573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052602081101561252d57600080fd5b810190808051604051939291908464010000000082111561254d57600080fd5b90830190602082018581111561256257600080fd5b825164010000000081118282018810171561257c57600080fd5b82525081516020918201929091019080838360005b838110156125a9578181015183820152602001612591565b50505050905090810190601f1680156125d65780820380516001836020036101000a031916815260200191505b50604052505050905060008060405160200180807f6345544800000000000000000000000000000000000000000000000000000000815250600401905060405160208183030381529060405280519060200120836040516020018082805190602001908083835b6020831061265c5780518252601f19909201916020918201910161263d565b6001836020036101000a03801982511681845116808217855250505050505090500191505060405160208183030381529060405280519060200120141561270d576040805160048152602481019091526020810180516001600160e01b03167f4e4d9fea000000000000000000000000000000000000000000000000000000001790526001600160a01b0387163192506126fb9087908790879061297b565b50506001600160a01b03851631612927565b6000856001600160a01b0316636f307dc36040518163ffffffff1660e01b815260040160206040518083038186803b15801561274857600080fd5b505afa15801561275c573d6000803e3d6000fd5b505050506040513d602081101561277257600080fd5b5051604080516370a0823160e01b81526001600160a01b038a811660048301529151929350908316916370a0823191602480820192602092909190829003018186803b1580156127c157600080fd5b505afa1580156127d5573d6000803e3d6000fd5b505050506040513d60208110156127eb57600080fd5b5051604080516001600160a01b038916602482015260448082018990528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b179052909350612847908890839060009061297b565b506040805160248082018890528251808303909101815260449091019091526020810180516001600160e01b03167f0e752702000000000000000000000000000000000000000000000000000000001790526128a9908890889060009061297b565b50806001600160a01b03166370a08231886040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b1580156128f757600080fd5b505afa15801561290b573d6000803e3d6000fd5b505050506040513d602081101561292157600080fd5b50519150505b818110611ea3576040805162461bcd60e51b815260206004820152601660248201527f434d3a207265706179426f72726f77206661696c656400000000000000000000604482015290519081900360640190fd5b6001546040517f915c77b90000000000000000000000000000000000000000000000000000000081526001600160a01b0386811660048301908152868216602484015260448301869052608060648401908152855160848501528551606095939093169363915c77b9938a938a938a938a9360a490910190602085019080838360005b83811015612a165781810151838201526020016129fe565b50505050905090810190601f168015612a435780820380516001836020036101000a031916815260200191505b5095505050505050600060405180830381600087803b158015612a6557600080fd5b505af1158015612a79573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526020811015612aa257600080fd5b8101908080516040519392919084640100000000821115612ac257600080fd5b908301906020820185811115612ad757600080fd5b8251640100000000811182820188101715612af157600080fd5b82525081516020918201929091019080838360005b83811015612b1e578181015183820152602001612b06565b50505050905090810190601f168015612b4b5780820380516001836020036101000a031916815260200191505b506040525050509050949350505050565b6001600160a01b038216612bb7576040805162461bcd60e51b815260206004820152601e60248201527f434d3a204e6f206d61726b657420666f722074617267657420746f6b656e0000604482015290519081900360640190fd5b60008111612c05576040805162461bcd60e51b81526020600482015260166024820152750434d3a20616d6f756e742063616e6e6f7420626520360541b604482015290519081900360640190fd5b6000826001600160a01b03166370a08231856040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015612c5457600080fd5b505afa158015612c68573d6000803e3d6000fd5b505050506040513d6020811015612c7e57600080fd5b50516040805160248082018690528251808303909101815260449091019091526020810180516001600160e01b03167f852a12e300000000000000000000000000000000000000000000000000000000179052909150612ce4908590859060009061297b565b5080836001600160a01b03166370a08231866040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015612d3357600080fd5b505afa158015612d47573d6000803e3d6000fd5b505050506040513d6020811015612d5d57600080fd5b505110611ea6576040805162461bcd60e51b815260206004820152601b60248201527f434d3a2072656465656d556e6465726c79696e67206661696c65640000000000604482015290519081900360640190fd5b6000826001600160a01b03166370a08231856040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015612e0057600080fd5b505afa158015612e14573d6000803e3d6000fd5b505050506040513d6020811015612e2a57600080fd5b5051604080517f95dd91930000000000000000000000000000000000000000000000000000000081526001600160a01b0387811660048301529151929350600092918616916395dd919391602480820192602092909190829003018186803b158015612e9557600080fd5b505afa158015612ea9573d6000803e3d6000fd5b505050506040513d6020811015612ebf57600080fd5b5051905081158015612ecf575080155b15610c5f57604080516001600160a01b0386166024808301919091528251808303909101815260449091019091526020810180516001600160e01b0316630ede4edd60e41b179052611ea3908690859060009061297b565b6001600160a01b038316612f82576040805162461bcd60e51b815260206004820152601e60248201527f434d3a204e6f206d61726b657420666f722074617267657420746f6b656e0000604482015290519081900360640190fd5b60008111612fd0576040805162461bcd60e51b81526020600482015260166024820152750434d3a20616d6f756e742063616e6e6f7420626520360541b604482015290519081900360640190fd5b6000836001600160a01b03166370a08231866040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b15801561301f57600080fd5b505afa158015613033573d6000803e3d6000fd5b505050506040513d602081101561304957600080fd5b505190506001600160a01b03831673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14156130c9576040805160048152602481019091526020810180516001600160e01b03167f1249c58b000000000000000000000000000000000000000000000000000000001790526130c39086908690859061297b565b50613184565b604080516001600160a01b038616602482015260448082018590528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b179052613120908690859060009061297b565b506040805160248082018590528251808303909101815260449091019091526020810180516001600160e01b03167fa0712d6800000000000000000000000000000000000000000000000000000000179052613182908690869060009061297b565b505b80846001600160a01b03166370a08231876040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b1580156131d257600080fd5b505afa1580156131e6573d6000803e3d6000fd5b505050506040513d60208110156131fc57600080fd5b505111610c5f576040805162461bcd60e51b815260206004820152600f60248201527f434d3a206d696e74206661696c65640000000000000000000000000000000000604482015290519081900360640190fd5b6000816001600160a01b0316836001600160a01b0316638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b15801561329557600080fd5b505afa1580156132a9573d6000803e3d6000fd5b505050506040513d60208110156132bf57600080fd5b50516001600160a01b0316149392505050565b6000818361335e5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561332357818101518382015260200161330b565b50505050905090810190601f1680156133505780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b50600083858161336a57fe5b049594505050505056fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77434d3a206661696c656420746f20676574206163636f756e74206c6971756964697479a2646970667358221220c1e55394c7046c4ba5ed000f812ce903bca5e46892190237dddfb31606e83b6e64736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "unchecked-lowlevel", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'unchecked-lowlevel', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}]}
77
0x199D3D6B41bced35c45A0156fc60C091Eed04F1A
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 DFSPrices 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); uint256 globalBorrowAmount = 0; { // avoid stack too deep // 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)); globalBorrowAmount = borrowAmount; } // payback on behalf of user if (borrowToken != ETH_ADDR) { ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } else { DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(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 = 0x7b856af5753a9f80968EA002641E69AdF1d795aB; 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 DFSExchangeCore, CompBalance { 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 COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; 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.dfsFeeDivider = 400; // 0.25% exchangeData.srcAmount = compBalance; (, depositAmount) = _sell(exchangeData); // if we have no deposit after, send back tokens to the user if (_cDepositAddr == address(0)) { if (exchangeData.destAddr != ETH_ADDRESS) { ERC20(exchangeData.destAddr).transfer(msg.sender, depositAmount); } else { msg.sender.transfer(address(this).balance); } } } // 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 deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } 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); } } }
0x608060405234801561001057600080fd5b50600436106100935760003560e01c806382dfc5f71161006657806382dfc5f7146100e65780638823151b146100ee578063d36b907d146100f6578063e074bb47146100fe578063ef9486df1461011157610093565b8063329b8f591461009857806339df1878146100ad5780633d391f70146100cb5780634d9fb18f146100de575b600080fd5b6100ab6100a6366004610a25565b610119565b005b6100b5610478565b6040516100c29190610b3e565b60405180910390f35b6100ab6100d9366004610a09565b610490565b6100b561067b565b6100b5610693565b6100b56106ab565b6100b56106c3565b6100ab61010c366004610a09565b6106db565b6100b56107b9565b731e0447b19bb6ecfdae1e4ae1694b0c3659614e4e600061014d73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26107d1565b9050600061015a846107d7565b60405163095ea7b360e01b815290915073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc29063095ea7b3906101aa90731e0447b19bb6ecfdae1e4ae1694b0c3659614e4e908590600401610c22565b602060405180830381600087803b1580156101c457600080fd5b505af11580156101d8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101fc9190610a65565b5060408051600380825260808201909252606091816020015b61021d610977565b8152602001906001900390816102155790505090506102518386737b856af5753a9f80968ea002641e69adf1d795ab6107ea565b8160008151811061025e57fe5b60200260200101819052506102ae8787873330604051602001610285959493929190610bf0565b604051602081830303815290604052737b856af5753a9f80968ea002641e69adf1d795ab610875565b816001815181106102bb57fe5b60200260200101819052506102d18383306108e7565b816002815181106102de57fe5b6020908102919091010152604080516001808252818301909252606091816020015b6103086109c9565b815260200190600190039081610300579050509050610325610922565b8160008151811061033257fe5b602002602001018190525061035a737b856af5753a9f80968ea002641e69adf1d795ab610490565b60405163a67a6a4560e01b81526001600160a01b0386169063a67a6a45906103889084908690600401610c3b565b600060405180830381600087803b1580156103a257600080fd5b505af11580156103b6573d6000803e3d6000fd5b505050506103d7737b856af5753a9f80968ea002641e69adf1d795ab6106db565b735c55b921f590a89c1ebe84df170e655a82b621266001600160a01b031663d061ce5030338b8b60405160200161040f929190610b52565b6040516020818303038152906040526040518463ffffffff1660e01b815260040161043c93929190610b6c565b600060405180830381600087803b15801561045657600080fd5b505af115801561046a573d6000803e3d6000fd5b505050505050505050505050565b735c55b921f590a89c1ebe84df170e655a82b6212681565b6000306001600160a01b031663bf7e214f6040518163ffffffff1660e01b815260040160206040518083038186803b1580156104cb57600080fd5b505afa1580156104df573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105039190610a85565b9050806001600160a01b0381166105f457735a15566417e6c1c9546523066500bddbc53f88c76001600160a01b03166365688cc96040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561056357600080fd5b505af1158015610577573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061059b9190610a85565b604051637a9e5e4b60e01b81529091503090637a9e5e4b906105c1908490600401610b3e565b600060405180830381600087803b1580156105db57600080fd5b505af11580156105ef573d6000803e3d6000fd5b505050505b6040516332fba9a360e21b81526001600160a01b0382169063cbeea68c9061064490869030907f1cff79cde515a86f6cc1adbebe8ae25888905561371faf11c8102211f56b487090600401610bc3565b600060405180830381600087803b15801561065e57600080fd5b505af1158015610672573d6000803e3d6000fd5b50505050505050565b737b856af5753a9f80968ea002641e69adf1d795ab81565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b735a15566417e6c1c9546523066500bddbc53f88c781565b731e0447b19bb6ecfdae1e4ae1694b0c3659614e4e81565b6000306001600160a01b031663bf7e214f6040518163ffffffff1660e01b815260040160206040518083038186803b15801561071657600080fd5b505afa15801561072a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061074e9190610a85565b90506001600160a01b03811661076457506107b6565b604051632bc3217d60e01b815281906001600160a01b03821690632bc3217d9061064490869030907f1cff79cde515a86f6cc1adbebe8ae25888905561371faf11c8102211f56b487090600401610bc3565b50565b734678f0a6958e4d2bc4f1baf7bc52e8f3564f3fe481565b50600090565b60006107e4826002610942565b92915050565b6107f2610977565b604080516101008101825260018152600060208083018290528351608081018552828152929384019291908201905b81526020016000815260200186815250815260200185815260200160008152602001836001600160a01b03168152602001600081526020016040518060200160405280600081525081525090509392505050565b61087d610977565b50604080516101008101825260088152600060208083018290528351608080820186528382529181018390528085018390526060808201849052948401529282018190529181018290526001600160a01b0390921660a083015260c082015260e081019190915290565b6108ef610977565b60408051610100810182526000808252602080830182905283516080810185526001815292938401929190820190610821565b61092a6109c9565b50604080518082019091523081526001602082015290565b6000828201838110156109705760405162461bcd60e51b815260040161096790610d57565b60405180910390fd5b9392505050565b6040805161010081018252600080825260208201529081016109976109e0565b8152602001600081526020016000815260200160006001600160a01b0316815260200160008152602001606081525090565b604080518082019091526000808252602082015290565b604080516080810190915260008082526020820190815260200160008152602001600081525090565b600060208284031215610a1a578081fd5b813561097081610da4565b600080600060608486031215610a39578182fd5b8335610a4481610da4565b92506020840135610a5481610da4565b929592945050506040919091013590565b600060208284031215610a76578081fd5b81518015158114610970578182fd5b600060208284031215610a96578081fd5b815161097081610da4565b6001600160a01b03169052565b60008151808452815b81811015610ad357602081850181015186830182015201610ab7565b81811115610ae45782602083870101525b50601f01601f19169290920160200192915050565b60098110610b0357fe5b9052565b8051151582526020810151610b1b81610d9a565b60208301526040810151610b2e81610d9a565b6040830152606090810151910152565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b03848116825283166020820152608060408201819052600a908201526910585d99525b5c1bdc9d60b21b60a082015260c060608201819052600090610bba90830184610aae565b95945050505050565b6001600160a01b0393841681529190921660208201526001600160e01b0319909116604082015260600190565b6001600160a01b0395861681529385166020850152604084019290925283166060830152909116608082015260a00190565b6001600160a01b03929092168252602082015260400190565b6040808252835182820181905260009190606090818501906020808901865b83811015610c87578151610c6e8151610d8e565b8652830151838601529386019390820190600101610c5a565b5050868303818801528751808452818401925080820284018201898301885b83811015610d4657601f198784030186528151610160610cc7858351610af9565b86820151878601528a820151610cdf8c870182610b07565b508982015160c081818801526080840151915060e0828189015260a08501519250610d0e610100890184610aa1565b908401516101208801529092015161014086018290529150610d3281860183610aae565b978701979450505090840190600101610ca6565b50909b9a5050505050505050505050565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b6001600160a01b031690565b600281106107b657fe5b6001600160a01b03811681146107b657600080fdfea264697066735822122081f734c2ed3fbbdd9b884a5974f43b98e05af5b46f9af19b1b5cab95da636c2f64736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "tx-origin", "impact": "Medium", "confidence": "Medium"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "name-reused", "impact": "High", "confidence": "High"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-lowlevel", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'tx-origin', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'name-reused', 'impact': 'High', 'confidence': 'High'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-lowlevel', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
78
0x1a3de69a70a7d4e6fb6a207a9aaf8ee3a7cb2709
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); } contract BzxAssetAdapter is ProtocolAdapter { string public constant override adapterType = "Asset"; string public constant override tokenType = "iToken"; /** * @return Amount of iTokens held by the given account. * @dev Implementation of ProtocolAdapter interface function. */ function getBalance(address token, address account) external view override returns (uint256) { return ERC20(token).balanceOf(account); } }
0x608060405234801561001057600080fd5b50600436106100415760003560e01c806330fa738c14610046578063d4fac45d14610064578063f72c079114610084575b600080fd5b61004e61008c565b60405161005b919061023d565b60405180910390f35b6100776100723660046101d0565b6100c5565b60405161005b91906102ae565b61004e610173565b6040518060400160405280600681526020017f69546f6b656e000000000000000000000000000000000000000000000000000081525081565b6040517f70a0823100000000000000000000000000000000000000000000000000000000815260009073ffffffffffffffffffffffffffffffffffffffff8416906370a082319061011a90859060040161021c565b60206040518083038186803b15801561013257600080fd5b505afa158015610146573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061016a9190610204565b90505b92915050565b6040518060400160405280600581526020017f417373657400000000000000000000000000000000000000000000000000000081525081565b803573ffffffffffffffffffffffffffffffffffffffff8116811461016d57600080fd5b600080604083850312156101e2578182fd5b6101ec84846101ac565b91506101fb84602085016101ac565b90509250929050565b600060208284031215610215578081fd5b5051919050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b6000602080835283518082850152825b818110156102695785810183015185820160400152820161024d565b8181111561027a5783604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b9081526020019056fea264697066735822122037ef848d1d3a1c7d4ae28978e1fce816feae216dba9a251503fa7ada4f9bc9be64736f6c63430006050033
{"success": true, "error": null, "results": {}}
true
null
{}
79
0x1BB6A03f25996122da8Ca2bb43E52b4bA59721dA
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 = 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 = 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); 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))); } } } 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] && _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; } 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; } } 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, 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 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 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; } 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) * (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]); } } function getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } } 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); 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 = 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 = 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 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(swapedTokens >= 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)); 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(DAI_JOIN_ADDRESS); 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 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(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); 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(); (,,,,,,,,,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); 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 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 = 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) { (, 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 = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB; /// @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])); } } }
0x6080604052600436106102465760003560e01c8063526d646111610139578063a8c90323116100b6578063d98bb5b11161007a578063d98bb5b1146105f5578063deca5f8814610615578063e3bbb4f114610635578063f05def811461064a578063f24ccbfe1461066a578063f851a4401461067f57610246565b8063a8c9032314610576578063b20b720914610596578063bfc36172146105ab578063bfe142a3146105cb578063c91d59fe146105e057610246565b80637f9ad5d6116100fd5780637f9ad5d614610504578063870e44d9146105175780638da5cb5b1461052c578063a56f971814610541578063a7304bf71461055657610246565b8063526d64611461049b578063696806c0146104b05780637753f47b146104c557806379521f02146104da5780637b925ab1146104ef57610246565b806336fc603f116101c7578063441697521161018b578063441697521461041157806349a3d737146104265780634d2ab9dc146104465780634d3f199e1461045b57806351c4a6311461047b57610246565b806336fc603f146103925780633816377e146103a757806339df1878146103c75780633a128322146103dc57806341c0e1b5146103fc57610246565b80631e48907b1161020e5780631e48907b146102f05780631ec18ec0146103105780632a56f602146103305780632b6e6581146103505780632b8f40071461037057610246565b806304c9805c1461024b57806305a363de1461027657806306d5e37e14610298578063087b0286146102c657806318bf60e1146102db575b600080fd5b34801561025757600080fd5b50610260610694565b60405161026d9190612722565b60405180910390f35b34801561028257600080fd5b5061028b61069a565b60405161026d9190612713565b3480156102a457600080fd5b506102b86102b3366004612144565b61069f565b60405161026d9291906125af565b6102d96102d43660046121ee565b61086d565b005b3480156102e757600080fd5b50610260610bbf565b3480156102fc57600080fd5b506102d961030b36600461204d565b610bc5565b34801561031c57600080fd5b5061026061032b366004612085565b610bfe565b34801561033c57600080fd5b5061026061034b3660046122e2565b610e41565b34801561035c57600080fd5b5061026061036b366004612085565b610e6b565b34801561037c57600080fd5b5061038561133e565b60405161026d9190612490565b34801561039e57600080fd5b5061026061134d565b3480156103b357600080fd5b506102d96103c23660046122e2565b611353565b3480156103d357600080fd5b50610385611380565b3480156103e857600080fd5b506102d96103f73660046120fd565b611398565b34801561040857600080fd5b506102d9611437565b34801561041d57600080fd5b5061038561145c565b34801561043257600080fd5b506102d9610441366004612085565b611474565b34801561045257600080fd5b5061026061152a565b34801561046757600080fd5b506102d96104763660046122e2565b611530565b34801561048757600080fd5b506102d96104963660046120bd565b61155b565b3480156104a757600080fd5b506103856115e5565b3480156104bc57600080fd5b506102606115fd565b3480156104d157600080fd5b50610385611603565b3480156104e657600080fd5b5061038561161b565b3480156104fb57600080fd5b5061038561162a565b6102d96105123660046121ee565b611642565b34801561052357600080fd5b5061026061194f565b34801561053857600080fd5b5061038561195b565b34801561054d57600080fd5b5061026061196a565b34801561056257600080fd5b506102d961057136600461204d565b611970565b34801561058257600080fd5b506102d96105913660046122e2565b6119a9565b3480156105a257600080fd5b506103856119d4565b3480156105b757600080fd5b506102b86105c6366004612144565b6119e3565b3480156105d757600080fd5b50610385611ae2565b3480156105ec57600080fd5b50610385611afa565b34801561060157600080fd5b5061026061061036600461204d565b611b0d565b34801561062157600080fd5b506102d961063036600461204d565b611c3d565b34801561064157600080fd5b50610260611c6a565b34801561065657600080fd5b506102d9610665366004612312565b611c70565b34801561067657600080fd5b50610385611c9d565b34801561068b57600080fd5b50610385611cac565b61014d81565b604081565b600854604051632e4aba1f60e21b8152600091829182916001600160a01b03169063b92ae87c906106d4908790600401612490565b60206040518083038186803b1580156106ec57600080fd5b505afa158015610700573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107249190612128565b905061072e611f8d565b60085460405163335d71f560e21b81526001600160a01b039091169063cd75c7d49061075e908890600401612490565b60c06040518083038186803b15801561077657600080fd5b505afa15801561078a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107ae9190612164565b9050816107c45750600092508291506108669050565b60008660018111156107d257fe5b1480156107e157508060a00151155b156107f55750600092508291506108669050565b600061080086611b0d565b9050600187600181111561081057fe5b1415610832576020909101516001600160801b03168110935091506108669050565b600087600181111561084057fe5b1415610862576040909101516001600160801b03168111935091506108669050565b5050505b9250929050565b6040516320eb73ed60e11b815273637726f8b08a7abe3ae3acab01a80e2d8ddef77b906341d6e7da906108a4903390600401612490565b60206040518083038186803b1580156108bc57600080fd5b505afa1580156108d0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108f49190612128565b6109195760405162461bcd60e51b815260040161091090612609565b60405180910390fd5b6003546040516370a0823160e01b815281906eb3f879cb30fe243b4dfee438691c04906370a0823190610950903090600401612490565b60206040518083038186803b15801561096857600080fd5b505afa15801561097c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109a091906122fa565b10610a2b5760405163d8ccd0f360e01b81526eb3f879cb30fe243b4dfee438691c049063d8ccd0f3906109d7908490600401612722565b602060405180830381600087803b1580156109f157600080fd5b505af1158015610a05573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a299190612128565b505b600080610a3960008561069f565b9150915081610a4757600080fd5b6000610a54600654610e41565b6007546009546040519293506001600160a01b0391821692638a0e833f9234928a92911690610a89908c908890602401612679565b60408051601f198184030181529181526020820180516001600160e01b03166378e810b160e11b1790525160e086901b6001600160e01b0319168152610ad4939291906004016124be565b6000604051808303818588803b158015610aed57600080fd5b505af1158015610b01573d6000803e3d6000fd5b5050505050600080610b146000886119e3565b9150915081610b2257600080fd5b610b2a611cbb565b600a546040516001600160a01b039091169063d061ce509030908a90610b56908990879060200161272b565b6040516020818303038152906040526040518463ffffffff1660e01b8152600401610b8393929190612540565b600060405180830381600087803b158015610b9d57600080fd5b505af1158015610bb1573d6000803e3d6000fd5b505050505050505050505050565b60065481565b6001546001600160a01b03163314610bdc57600080fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015610c4e57600080fd5b505afa158015610c62573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c869190612069565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b158015610cd757600080fd5b505afa158015610ceb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d0f9190612069565b90506000826001600160a01b031663bf92857c866040518263ffffffff1660e01b8152600401610d3f9190612490565b6101006040518083038186803b158015610d5857600080fd5b505afa158015610d6c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d9091906123df565b5050509450505050506000826001600160a01b031663b3596f07886040518263ffffffff1660e01b8152600401610dc79190612490565b60206040518083038186803b158015610ddf57600080fd5b505afa158015610df3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e1791906122fa565b9050610e34610e268383611cf1565b670de05bc096e9c000611d22565b9450505050505b92915050565b6000806004543a1115610e5657600454610e58565b3a5b9050610e648184611d4a565b9392505050565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316632f58b80d6040518163ffffffff1660e01b815260040160206040518083038186803b158015610ebb57600080fd5b505afa158015610ecf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ef39190612069565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b158015610f4457600080fd5b505afa158015610f58573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f7c9190612069565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b158015610fcd57600080fd5b505afa158015610fe1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110059190612069565b90506000806000856001600160a01b0316632c6d0e9b896040518263ffffffff1660e01b81526004016110389190612490565b6101006040518083038186803b15801561105157600080fd5b505afa158015611065573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110899190612376565b50505094505093509350506000856001600160a01b0316635fc526ff8b6040518263ffffffff1660e01b81526004016110c29190612490565b60806040518083038186803b1580156110da57600080fd5b505afa1580156110ee573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111129190612336565b50509150506000856001600160a01b031663b3596f078c6040518263ffffffff1660e01b81526004016111459190612490565b60206040518083038186803b15801561115d57600080fd5b505afa158015611171573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061119591906122fa565b90506000876001600160a01b03166318a4dbca8d8d6040518363ffffffff1660e01b81526004016111c79291906124a4565b60206040518083038186803b1580156111df57600080fd5b505afa1580156111f3573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061121791906122fa565b905060006112258284611d22565b90508561123d57509850610e3b975050505050505050565b600061126561125f61124f888b611d4a565b61125a8a6064611d4a565b611d6e565b87611d7e565b90508181116112745780611276565b815b905087811061129257879b505050505050505050505050610e3b565b60006112ab6112a1888b611d22565b61125a8886611d22565b905060006112dd6112ce836112c96112c38888611d6e565b8b611d22565b611d89565b6112d88c86611d6e565b611cf1565b90508781101561131c576113086113026112f7838d611d4a565b61125a8c6064611d4a565b82611d7e565b92508383116113175782611319565b835b92505b611329610e268488611cf1565b9d505050505050505050505050505092915050565b6009546001600160a01b031681565b60055481565b6000546001600160a01b0316331461136a57600080fd5b64746a528800811061137b57600080fd5b600455565b735c55b921f590a89c1ebe84df170e655a82b6212681565b6000546001600160a01b031633146113af57600080fd5b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6001600160a01b038316141561141357600080546040516001600160a01b039091169183156108fc02918491818181858888f1935050505015801561140d573d6000803e3d6000fd5b50611433565b600054611433906001600160a01b0384811691168363ffffffff611d9916565b5050565b6000546001600160a01b0316331461144e57600080fd5b6000546001600160a01b0316ff5b73322d58b9e75a6918f7e7849aee0ff09369977e0881565b6001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14156114a9576114a482824761155b565b611433565b6114338282846001600160a01b03166370a08231306040518263ffffffff1660e01b81526004016114da9190612490565b60206040518083038186803b1580156114f257600080fd5b505afa158015611506573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061049691906122fa565b61019081565b6000546001600160a01b0316331461154757600080fd5b622dc6c0811061155657600080fd5b600555565b80611565576115e0565b6001600160a01b03831673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14156115c6576040516001600160a01b0383169082156108fc029083906000818181858888f193505050501580156115c0573d6000803e3d6000fd5b506115e0565b6115e06001600160a01b038416838363ffffffff611d9916565b505050565b73637726f8b08a7abe3ae3acab01a80e2d8ddef77b81565b60035481565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b6008546001600160a01b031681565b731b14e8d511c9a4395425314f849bd737baf8208f81565b6040516320eb73ed60e11b815273637726f8b08a7abe3ae3acab01a80e2d8ddef77b906341d6e7da90611679903390600401612490565b60206040518083038186803b15801561169157600080fd5b505afa1580156116a5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116c99190612128565b6116e55760405162461bcd60e51b815260040161091090612609565b6002546040516370a0823160e01b815281906eb3f879cb30fe243b4dfee438691c04906370a082319061171c903090600401612490565b60206040518083038186803b15801561173457600080fd5b505afa158015611748573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061176c91906122fa565b106117f75760405163d8ccd0f360e01b81526eb3f879cb30fe243b4dfee438691c049063d8ccd0f3906117a3908490600401612722565b602060405180830381600087803b1580156117bd57600080fd5b505af11580156117d1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117f59190612128565b505b60008061180560018561069f565b915091508161181357600080fd5b6000611820600554610e41565b6007546009546040519293506001600160a01b0391821692638a0e833f9234928a92911690611855908c908890602401612679565b60408051601f198184030181529181526020820180516001600160e01b0316633a84827360e11b1790525160e086901b6001600160e01b03191681526118a0939291906004016124be565b6000604051808303818588803b1580156118b957600080fd5b505af11580156118cd573d6000803e3d6000fd5b50505050506000806118e06001886119e3565b91509150816118ee57600080fd5b6118f6611cbb565b600a546040516001600160a01b039091169063d061ce509030908a90611922908990879060200161272b565b6040516020818303038152906040526040518463ffffffff1660e01b8152600401610b83939291906124ea565b670de05bc096e9c00081565b6000546001600160a01b031681565b60025481565b6001546001600160a01b0316331461198757600080fd5b600180546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b031633146119c057600080fd5b622dc6c081106119cf57600080fd5b600655565b6007546001600160a01b031681565b6000806119ee611f8d565b60085460405163335d71f560e21b81526001600160a01b039091169063cd75c7d490611a1e908790600401612490565b60c06040518083038186803b158015611a3657600080fd5b505afa158015611a4a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a6e9190612164565b90506000611a7b85611b0d565b90506001866001811115611a8b57fe5b1415611aab576040909101516001600160801b0316811092509050610866565b6000866001811115611ab957fe5b1415611ad9576020909101516001600160801b0316811192509050610866565b50509250929050565b7324a42fd28c976a61df5d00d0599c34c4f90748c881565b6eb3f879cb30fe243b4dfee438691c0481565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015611b5d57600080fd5b505afa158015611b71573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b959190612069565b9050600080826001600160a01b031663bf92857c866040518263ffffffff1660e01b8152600401611bc69190612490565b6101006040518083038186803b158015611bdf57600080fd5b505afa158015611bf3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c1791906123df565b50505094505093505050611c34611c2e8383611d89565b83611cf1565b95945050505050565b6000546001600160a01b03163314611c5457600080fd5b6001546001600160a01b03161561198757600080fd5b60045481565b6000546001600160a01b03163314611c8757600080fd5b8015611c97576002829055611433565b50600355565b600a546001600160a01b031681565b6001546001600160a01b031681565b4715611cef5760405133904780156108fc02916000818181858888f19350505050158015611ced573d6000803e3d6000fd5b505b565b600081611d13611d0985670de0b6b3a7640000611d4a565b6002855b04611d89565b81611d1a57fe5b049392505050565b6000670de0b6b3a7640000611d13611d3a8585611d4a565b6002670de0b6b3a7640000611d0d565b6000811580611d6557505080820282828281611d6257fe5b04145b610e3b57600080fd5b80820382811115610e3b57600080fd5b6000818381611d1a57fe5b80820182811015610e3b57600080fd5b6115e08363a9059cbb60e01b8484604051602401611db8929190612596565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526060611e3f826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611e799092919063ffffffff16565b8051909150156115e05780806020019051810190611e5d9190612128565b6115e05760405162461bcd60e51b81526004016109109061262f565b6060611e888484600085611e90565b949350505050565b6060611e9b85611f54565b611eb75760405162461bcd60e51b8152600401610910906125d2565b60006060866001600160a01b03168587604051611ed49190612474565b60006040518083038185875af1925050503d8060008114611f11576040519150601f19603f3d011682016040523d82523d6000602084013e611f16565b606091505b50915091508115611f2a579150611e889050565b805115611f3a5780518082602001fd5b8360405162461bcd60e51b815260040161091091906125bf565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590611e88575050151592915050565b6040805160c081018252600080825260208201819052918101829052606081018290526080810182905260a081019190915290565b8035610e3b81612790565b600082601f830112611fdd578081fd5b813567ffffffffffffffff811115611ff3578182fd5b612006601f8201601f1916602001612739565b915080825283602082850101111561201d57600080fd5b8060208401602084013760009082016020015292915050565b80516001600160801b0381168114610e3b57600080fd5b60006020828403121561205e578081fd5b8135610e6481612790565b60006020828403121561207a578081fd5b8151610e6481612790565b60008060408385031215612097578081fd5b82356120a281612790565b915060208301356120b281612790565b809150509250929050565b6000806000606084860312156120d1578081fd5b83356120dc81612790565b925060208401356120ec81612790565b929592945050506040919091013590565b6000806040838503121561210f578182fd5b823561211a81612790565b946020939093013593505050565b600060208284031215612139578081fd5b8151610e64816127a5565b60008060408385031215612156578182fd5b8235600281106120a2578283fd5b600060c08284031215612175578081fd5b61217f60c0612739565b825161218a81612790565b81526121998460208501612036565b60208201526121ab8460408501612036565b60408201526121bd8460608501612036565b60608201526121cf8460808501612036565b608082015260a08301516121e2816127a5565b60a08201529392505050565b60008060408385031215612200578182fd5b823567ffffffffffffffff80821115612217578384fd5b61012091850180870383131561222b578485fd5b61223483612739565b61223e8883611fc2565b815261224d8860208401611fc2565b602082015260408201356040820152606082013560608201526080820135608082015261227d8860a08401611fc2565b60a082015261228f8860c08401611fc2565b60c082015260e08201359350828411156122a7578586fd5b6122b388858401611fcd565b60e082015261010093508382013584820152809550505050506122d98460208501611fc2565b90509250929050565b6000602082840312156122f3578081fd5b5035919050565b60006020828403121561230b578081fd5b5051919050565b60008060408385031215612324578182fd5b8235915060208301356120b2816127a5565b6000806000806080858703121561234b578182fd5b845193506020850151925060408501519150606085015161236b816127a5565b939692955090935050565b600080600080600080600080610100898b031215612392578586fd5b885197506020890151965060408901519550606089015194506080890151935060a0890151925060c0890151915060e08901516123ce816127a5565b809150509295985092959890939650565b600080600080600080600080610100898b0312156123fb578182fd5b505086516020880151604089015160608a015160808b015160a08c015160c08d015160e0909d0151959e949d50929b919a50985090965094509092509050565b6001600160a01b03169052565b60008151808452612460816020860160208601612760565b601f01601f19169290920160200192915050565b60008251612486818460208701612760565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b03848116825283166020820152606060408201819052600090611c3490830184612448565b6001600160a01b03848116825283166020820152608060408201819052601290820152714175746f6d6174696341617665526570617960701b60a082015260c060608201819052600090611c3490830184612448565b6001600160a01b0384811682528316602082015260806040820181905260129082015271105d5d1bdb585d1a58d0585d99509bdbdcdd60721b60a082015260c060608201819052600090611c3490830184612448565b6001600160a01b03929092168252602082015260400190565b9115158252602082015260400190565b600060208252610e646020830184612448565b6020808252601d908201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604082015260600190565b6020808252600c908201526b139bdd08185d5d1a08189bdd60a21b604082015260600190565b6020808252602a908201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6040820152691bdd081cdd58d8d9595960b21b606082015260800190565b60006040825261268d60408301855161243b565b602084015161269f606084018261243b565b5060408401516080830152606084015160a0830152608084015160c083015260a08401516126d060e084018261243b565b5060c08401516101006126e58185018361243b565b60e0860151610120858101529150612701610160850183612448565b95015161014084015250506020015290565b61ffff91909116815260200190565b90815260200190565b918252602082015260400190565b60405181810167ffffffffffffffff8111828210171561275857600080fd5b604052919050565b60005b8381101561277b578181015183820152602001612763565b8381111561278a576000848401525b50505050565b6001600160a01b0381168114611ced57600080fd5b8015158114611ced57600080fdfea26469706673582212205e7fe4ae34ca5936eeac0e798daabc3cba2854cb25ddd00c7eefa57f65d6160764736f6c63430006060033
{"success": true, "error": null, "results": {"detectors": [{"check": "tx-origin", "impact": "Medium", "confidence": "Medium"}, {"check": "name-reused", "impact": "High", "confidence": "High"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-lowlevel", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'tx-origin', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'name-reused', 'impact': 'High', 'confidence': 'High'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-lowlevel', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
80
0x1Bcc32Ac1C994CE7e9526FbaF95f37AbC0B2EC39
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; bool private _dated; bool private _migrated; uint256 _deployedAt; uint256 _totalStaked; mapping (address => uint256) private _staked; mapping (address => uint256) private _lastClaim; address private _developerFund; event StakeIncreased(address indexed staker, uint256 amount); event StakeDecreased(address indexed staker, uint256 amount); 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 migrate(address previous, address[] memory people, uint256[] memory lastClaims) external { require(!_migrated); require(people.length == lastClaims.length); for (uint i = 0; i < people.length; i++) { uint256 staked = VybeStake(previous).staked(people[i]); _staked[people[i]] = staked; _totalStaked = _totalStaked.add(staked); _lastClaim[people[i]] = lastClaims[i]; emit StakeIncreased(people[i], staked); } require(_VYBE.transferFrom(previous, address(this), _VYBE.balanceOf(previous))); _migrated = true; } function staked(address staker) external view returns (uint256) { return _staked[staker]; } function lastClaim(address staker) external view returns (uint256) { return _lastClaim[staker]; } function increaseStake(uint256 amount) external { require(!_dated); require(_VYBE.transferFrom(msg.sender, address(this), amount)); _totalStaked = _totalStaked.add(amount); _lastClaim[msg.sender] = block.timestamp; _staked[msg.sender] = _staked[msg.sender].add(amount); emit StakeIncreased(msg.sender, 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)); emit StakeDecreased(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 { require(!_dated); 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 { _dated = true; IOwnershipTransferrable(owned).transferOwnership(upgraded); } }
0x608060405234801561001057600080fd5b50600436106101005760003560e01c80638da5cb5b11610097578063eedad66b11610066578063eedad66b14610266578063f2397f3e14610283578063f2fde38b146102a9578063f3177079146102cf57610100565b80638da5cb5b146101ed57806398807d84146101f557806399a88ec41461021b578063e8b96de11461024957610100565b806364ab8675116100d357806364ab8675146101755780636b1dd7fd1461019b5780636de3ac3f146101bf578063817b1cd2146101e557610100565b80632da8913614610105578063372500ab1461012d5780634c885c02146101355780635c16e15e1461014f575b600080fd5b61012b6004803603602081101561011b57600080fd5b50356001600160a01b0316610406565b005b61012b610513565b61013d6106b9565b60408051918252519081900360200190f35b61013d6004803603602081101561016557600080fd5b50356001600160a01b0316610708565b61013d6004803603602081101561018b57600080fd5b50356001600160a01b0316610723565b6101a361073e565b604080516001600160a01b039092168252519081900360200190f35b61012b600480360360208110156101d557600080fd5b50356001600160a01b031661074d565b61013d6107ce565b6101a36107d4565b61013d6004803603602081101561020b57600080fd5b50356001600160a01b03166107e8565b61012b6004803603604081101561023157600080fd5b506001600160a01b0381358116916020013516610803565b61012b6004803603602081101561025f57600080fd5b50356108cf565b61012b6004803603602081101561027c57600080fd5b50356109cb565b61012b6004803603602081101561029957600080fd5b50356001600160a01b0316610af4565b61012b600480360360208110156102bf57600080fd5b50356001600160a01b0316610c00565b61012b600480360360608110156102e557600080fd5b6001600160a01b03823516919081019060408101602082013564010000000081111561031057600080fd5b82018360208201111561032257600080fd5b8035906020019184602083028401116401000000008311171561034457600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929594936020810193503591505064010000000081111561039457600080fd5b8201836020820111156103a657600080fd5b803590602001918460208302840111640100000000831117156103c857600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550610d0a945050505050565b60005461010090046001600160a01b03163314610458576040805162461bcd60e51b815260206004820181905260248201526000805160206111f1833981519152604482015290519081900360640190fd5b6001546040805163095ea7b360e01b81526001600160a01b038481166004830152600060248301819052925193169263095ea7b392604480840193602093929083900390910190829087803b1580156104b057600080fd5b505af11580156104c4573d6000803e3d6000fd5b505050506040513d60208110156104da57600080fd5b50506040516001600160a01b038216907f3161d766eb7d07d5e1ceea9abc5160636a3ec586a0f95a0c0cf367af6706d0b790600090a250565b60005460ff161561052357600080fd5b6000805460ff1916600190811790915554600160a01b900460ff161561054857600080fd5b600061055333610fee565b90506000610562826014611136565b90506000811161057157600080fd5b3360008181526005602052604090204290556001546001600160a01b0316906340c10f19906105a08585611158565b6040518363ffffffff1660e01b815260040180836001600160a01b0316815260200182815260200192505050600060405180830381600087803b1580156105e657600080fd5b505af11580156105fa573d6000803e3d6000fd5b5050600154600654604080516340c10f1960e01b81526001600160a01b0392831660048201526024810187905290519190921693506340c10f199250604480830192600092919082900301818387803b15801561065657600080fd5b505af115801561066a573d6000803e3d6000fd5b5050604080518581526020810185905281513394507f61953b03ced70bb23c53b5a7058e431e3db88cf84a72660faea0849b785c43bd93509081900390910190a250506000805460ff19169055565b6000806106f46106ec60056106e662278d006106e06002544261115890919063ffffffff16565b90611136565b9061116d565b60149061119b565b90506032811115610703575060325b905090565b6001600160a01b031660009081526005602052604090205490565b600061073860136106e660146106e086610fee565b92915050565b6001546001600160a01b031690565b60005461010090046001600160a01b0316331461079f576040805162461bcd60e51b815260206004820181905260248201526000805160206111f1833981519152604482015290519081900360640190fd5b6006805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0392909216919091179055565b60035490565b60005461010090046001600160a01b031690565b6001600160a01b031660009081526004602052604090205490565b60005461010090046001600160a01b03163314610855576040805162461bcd60e51b815260206004820181905260248201526000805160206111f1833981519152604482015290519081900360640190fd5b6001805460ff60a01b1916600160a01b1790556040805163f2fde38b60e01b81526001600160a01b03838116600483015291519184169163f2fde38b9160248082019260009290919082900301818387803b1580156108b357600080fd5b505af11580156108c7573d6000803e3d6000fd5b505050505050565b336000908152600460205260409020546108e99082611158565b336000908152600460205260409020556003546109069082611158565b6003556001546040805163a9059cbb60e01b81523360048201526024810184905290516001600160a01b039092169163a9059cbb916044808201926020929091908290030181600087803b15801561095d57600080fd5b505af1158015610971573d6000803e3d6000fd5b505050506040513d602081101561098757600080fd5b505161099257600080fd5b60408051828152905133917f700865370ffb2a65a2b0242e6a64b21ac907ed5ecd46c9cffc729c177b2b1c69919081900360200190a250565b600154600160a01b900460ff16156109e257600080fd5b600154604080516323b872dd60e01b81523360048201523060248201526044810184905290516001600160a01b03909216916323b872dd916064808201926020929091908290030181600087803b158015610a3c57600080fd5b505af1158015610a50573d6000803e3d6000fd5b505050506040513d6020811015610a6657600080fd5b5051610a7157600080fd5b600354610a7e908261119b565b6003553360009081526005602090815260408083204290556004909152902054610aa8908261119b565b33600081815260046020908152604091829020939093558051848152905191927f8b0ed825817a2e696c9a931715af4609fc60e1701f09c89ee7645130e937eb2d92918290030190a250565b60005461010090046001600160a01b03163314610b46576040805162461bcd60e51b815260206004820181905260248201526000805160206111f1833981519152604482015290519081900360640190fd5b6001546040805163095ea7b360e01b81526001600160a01b03848116600483015260001960248301529151919092169163095ea7b39160448083019260209291908290030181600087803b158015610b9d57600080fd5b505af1158015610bb1573d6000803e3d6000fd5b505050506040513d6020811015610bc757600080fd5b50506040516001600160a01b038216907fb87d41b5cab885fb2ce4b4c06efc62eea320378130b36c709de7d45facaa1bc890600090a250565b60005461010090046001600160a01b03163314610c52576040805162461bcd60e51b815260206004820181905260248201526000805160206111f1833981519152604482015290519081900360640190fd5b6001600160a01b038116610c975760405162461bcd60e51b81526004018080602001828103825260268152602001806111cb6026913960400191505060405180910390fd5b600080546040516001600160a01b038085169361010090930416917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b039092166101000274ffffffffffffffffffffffffffffffffffffffff0019909216919091179055565b600154600160a81b900460ff1615610d2157600080fd5b8051825114610d2f57600080fd5b60005b8251811015610ec5576000846001600160a01b03166398807d84858481518110610d5857fe5b60200260200101516040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015610d9d57600080fd5b505afa158015610db1573d6000803e3d6000fd5b505050506040513d6020811015610dc757600080fd5b505184519091508190600490600090879086908110610de257fe5b6020908102919091018101516001600160a01b0316825281019190915260400160002055600354610e13908261119b565b6003558251839083908110610e2457fe5b602002602001015160056000868581518110610e3c57fe5b60200260200101516001600160a01b03166001600160a01b0316815260200190815260200160002081905550838281518110610e7457fe5b60200260200101516001600160a01b03167f8b0ed825817a2e696c9a931715af4609fc60e1701f09c89ee7645130e937eb2d826040518082815260200191505060405180910390a250600101610d32565b50600154604080516370a0823160e01b81526001600160a01b038681166004830152915191909216916323b872dd918691309185916370a08231916024808301926020929190829003018186803b158015610f1f57600080fd5b505afa158015610f33573d6000803e3d6000fd5b505050506040513d6020811015610f4957600080fd5b5051604080516001600160e01b031960e087901b1681526001600160a01b0394851660048201529290931660248301526044820152905160648083019260209291908290030181600087803b158015610fa157600080fd5b505af1158015610fb5573d6000803e3d6000fd5b505050506040513d6020811015610fcb57600080fd5b5051610fd657600080fd5b50506001805460ff60a81b1916600160a81b17905550565b6001600160a01b03811660009081526004602052604081205460035482916110a49161101991611136565b6106e06110246106b9565b600160009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561107257600080fd5b505afa158015611086573d6000803e3d6000fd5b505050506040513d602081101561109c57600080fd5b505190611136565b6001600160a01b038416600090815260056020526040812054919250906110cc904290611158565b9050600062278d00821115611104576110f26110eb8362278d00611136565b849061116d565b90506111018262278d006111ad565b91505b811561112e5761112b61112461111d62278d0085611136565b8590611136565b829061119b565b90505b949350505050565b600080821161114457600080fd5b600082848161114f57fe5b04949350505050565b60008282111561116757600080fd5b50900390565b60008261117c57506000610738565b8282028284828161118957fe5b041461119457600080fd5b9392505050565b60008282018381101561119457600080fd5b6000816111b957600080fd5b8183816111c257fe5b06939250505056fe4f776e61626c653a206e6577206f776e657220697320746865207a65726f20616464726573734f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572a264697066735822122044ef247c3fb29e5517dc6ff6602d92a376db73014e8c43fc727bd4ee811649cf64736f6c63430007000033
{"success": true, "error": null, "results": {"detectors": [{"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}]}
81
0x1bf68a9d1eaee7826b3593c20a0ca93293cb489a
pragma solidity 0.5.0; 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); function decimals() external view returns (uint8); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract TIERC20 { function transfer(address to, uint value) public; function transferFrom(address from, address to, uint value) public; function balanceOf(address who) public view returns (uint); function allowance(address owner, address spender) public view returns (uint256); function decimals() external view returns (uint8); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract MultiSigWallet { uint constant public MAX_OWNER_COUNT = 50; event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { if (msg.sender != address(this)) revert("Unauthorized."); _; } modifier ownerDoesNotExist(address owner) { if (isOwner[owner]) revert("Unauthorized."); _; } modifier ownerExists(address owner) { if (!isOwner[owner]) revert("Unauthorized."); _; } modifier transactionExists(uint transactionId) { if (transactions[transactionId].destination == address(0)) revert("Existed transaction id."); _; } modifier confirmed(uint transactionId, address owner) { if (!confirmations[transactionId][owner]) revert("Not confirmed transaction."); _; } modifier notConfirmed(uint transactionId, address owner) { if (confirmations[transactionId][owner]) revert("Confirmed transaction."); _; } modifier notExecuted(uint transactionId) { if (transactions[transactionId].executed) revert("Executed transaction."); _; } modifier notNull(address _address) { if (_address == address(0)) revert("Address is null"); _; } modifier validRequirement(uint ownerCount, uint _required) { if ( ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0) revert("Invalid requirement"); _; } /// @dev Fallback function allows to deposit ether. function() external payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. constructor(address[] memory _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i=0; i<_owners.length; i++) { if (isOwner[_owners[i]] || _owners[i] == address(0)) revert("Invalid owner"); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param owner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes memory data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; (bool result, ) = txn.destination.call.value(txn.value)(txn.data); if (result) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); txn.executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public view returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes memory data) public notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public view returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public view returns (uint count) { for (uint i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public view returns (address[] memory) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public view returns (address[] memory _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public view returns (uint[] memory _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } } contract SafeMath { function safeMul(uint a, uint b) internal pure returns(uint) { uint c = a * b; assertion(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal pure returns(uint) { assertion(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns(uint) { uint c = a + b; assertion(c >= a && c >= b); return c; } function safeDiv(uint a, uint b) internal pure returns(uint) { require(b != 0, 'Divide by zero'); return a / b; } function safeCeil(uint a, uint b) internal pure returns (uint) { require(b > 0); uint v = a / b; if(v * b == a) return v; return v + 1; // b cannot be 1, so v <= a / 2 } function assertion(bool flag) internal pure { if (!flag) revert('Assertion fail.'); } } contract EthVault is MultiSigWallet{ string public constant chain = "ETH"; bool public isActivated = true; address payable public implementation; address public tetherAddress; uint public depositCount = 0; mapping(bytes32 => bool) public isUsedWithdrawal; mapping(bytes32 => address) public tokenAddr; mapping(address => bytes32) public tokenSummaries; mapping(bytes32 => bool) public isValidChain; constructor(address[] memory _owners, uint _required, address payable _implementation, address _tetherAddress) MultiSigWallet(_owners, _required) public { implementation = _implementation; tetherAddress = _tetherAddress; // klaytn valid chain default setting isValidChain[sha256(abi.encodePacked(address(this), "KLAYTN"))] = true; } function _setImplementation(address payable _newImp) public onlyWallet { require(implementation != _newImp); implementation = _newImp; } 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) } } } } contract EthVaultImpl is EthVault, SafeMath{ event Deposit(string fromChain, string toChain, address fromAddr, bytes toAddr, address token, uint8 decimal, uint amount, uint depositId, uint block); event Withdraw(address hubContract, string fromChain, string toChain, bytes fromAddr, bytes toAddr, bytes token, bytes32[] bytes32s, uint[] uints); modifier onlyActivated { require(isActivated); _; } constructor(address[] memory _owner) public EthVault(_owner, _owner.length, address(0), address(0)) { } function getVersion() public pure returns(string memory){ return "1028"; } function changeActivate(bool activate) public onlyWallet { isActivated = activate; } function setTetherAddress(address tether) public onlyWallet { tetherAddress = tether; } function getChainId(string memory _chain) public view returns(bytes32){ return sha256(abi.encodePacked(address(this), _chain)); } function setValidChain(string memory _chain, bool valid) public onlyWallet { isValidChain[getChainId(_chain)] = valid; } function deposit(string memory toChain, bytes memory toAddr) payable public onlyActivated { require(isValidChain[getChainId(toChain)]); require(msg.value > 0); depositCount = depositCount + 1; emit Deposit(chain, toChain, msg.sender, toAddr, address(0), 18, msg.value, depositCount, block.number); } function depositToken(address token, string memory toChain, bytes memory toAddr, uint amount) public onlyActivated{ require(isValidChain[getChainId(toChain)]); require(token != address(0)); require(amount > 0); uint8 decimal = 0; if(token == tetherAddress){ TIERC20(token).transferFrom(msg.sender, address(this), amount); decimal = TIERC20(token).decimals(); }else{ if(!IERC20(token).transferFrom(msg.sender, address(this), amount)) revert(); decimal = IERC20(token).decimals(); } require(decimal > 0); depositCount = depositCount + 1; emit Deposit(chain, toChain, msg.sender, toAddr, token, decimal, amount, depositCount, block.number); } // Fix Data Info ///@param bytes32s [0]:govId, [1]:txHash ///@param uints [0]:amount, [1]:decimals function withdraw( address hubContract, string memory fromChain, bytes memory fromAddr, bytes memory toAddr, bytes memory token, bytes32[] memory bytes32s, uint[] memory uints, uint8[] memory v, bytes32[] memory r, bytes32[] memory s ) public onlyActivated { require(bytes32s.length >= 1); require(bytes32s[0] == sha256(abi.encodePacked(hubContract, chain, address(this)))); require(uints.length >= 2); require(isValidChain[getChainId(fromChain)]); bytes32 whash = sha256(abi.encodePacked(hubContract, fromChain, chain, fromAddr, toAddr, token, bytes32s, uints)); require(!isUsedWithdrawal[whash]); isUsedWithdrawal[whash] = true; uint validatorCount = _validate(whash, v, r, s); require(validatorCount >= required); address payable _toAddr = bytesToAddress(toAddr); address tokenAddress = bytesToAddress(token); if(tokenAddress == address(0)){ if(!_toAddr.send(uints[0])) revert(); }else{ if(tokenAddress == tetherAddress){ TIERC20(tokenAddress).transfer(_toAddr, uints[0]); } else{ if(!IERC20(tokenAddress).transfer(_toAddr, uints[0])) revert(); } } emit Withdraw(hubContract, fromChain, chain, fromAddr, toAddr, token, bytes32s, uints); } function _validate(bytes32 whash, uint8[] memory v, bytes32[] memory r, bytes32[] memory s) private view returns(uint){ uint validatorCount = 0; address[] memory vaList = new address[](owners.length); uint i=0; uint j=0; for(i; i<v.length; i++){ address va = ecrecover(whash,v[i],r[i],s[i]); if(isOwner[va]){ for(j=0; j<validatorCount; j++){ require(vaList[j] != va); } vaList[validatorCount] = va; validatorCount += 1; } } return validatorCount; } function bytesToAddress(bytes memory bys) private pure returns (address payable addr) { assembly { addr := mload(add(bys,20)) } } function () payable external{ } }
0x6080604052600436106101955763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663025e7c2781146101d7578063173825d91461021d57806320ea8d86146102525780632dfdf0b51461027c5780632f54bf6e146102a35780633411c81c146102ea5780633a8105ec146103235780634a8c1fb414610338578063547415251461034d5780635c60da1b146103815780635ed7a8fc146103965780637065cb48146103c0578063784547a7146103f35780638b51d13f1461041d5780639ace38c2146104475780639d188c1614610514578063a0e67e2b1461053e578063a8abe69a146105a3578063b5dc40c3146105e3578063b77bf6001461060d578063ba51a6df14610622578063bb913f411461064c578063c01a8c841461067f578063c6427474146106a9578063c763e5a114610771578063d74f8edd146107fb578063dc8452cd14610810578063e1d703a114610825578063e20056e614610858578063ec096f8d14610893578063ee22610b1461095b578063f01b246714610985575b6006546101009004600160a060020a03168015156101b257600080fd5b60405136600082376000803683855af43d806000843e8180156101d3578184f35b8184fd5b3480156101e357600080fd5b50610201600480360360208110156101fa57600080fd5b50356109af565b60408051600160a060020a039092168252519081900360200190f35b34801561022957600080fd5b506102506004803603602081101561024057600080fd5b5035600160a060020a03166109d7565b005b34801561025e57600080fd5b506102506004803603602081101561027557600080fd5b5035610bb9565b34801561028857600080fd5b50610291610d42565b60408051918252519081900360200190f35b3480156102af57600080fd5b506102d6600480360360208110156102c657600080fd5b5035600160a060020a0316610d48565b604080519115158252519081900360200190f35b3480156102f657600080fd5b506102d66004803603604081101561030d57600080fd5b5080359060200135600160a060020a0316610d5d565b34801561032f57600080fd5b50610201610d7d565b34801561034457600080fd5b506102d6610d8c565b34801561035957600080fd5b506102916004803603604081101561037057600080fd5b508035151590602001351515610d95565b34801561038d57600080fd5b50610201610e01565b3480156103a257600080fd5b50610201600480360360208110156103b957600080fd5b5035610e15565b3480156103cc57600080fd5b50610250600480360360208110156103e357600080fd5b5035600160a060020a0316610e30565b3480156103ff57600080fd5b506102d66004803603602081101561041657600080fd5b5035611055565b34801561042957600080fd5b506102916004803603602081101561044057600080fd5b50356110dc565b34801561045357600080fd5b506104716004803603602081101561046a57600080fd5b503561114b565b6040518085600160a060020a0316600160a060020a031681526020018481526020018060200183151515158152602001828103825284818151815260200191508051906020019080838360005b838110156104d65781810151838201526020016104be565b50505050905090810190601f1680156105035780820380516001836020036101000a031916815260200191505b509550505050505060405180910390f35b34801561052057600080fd5b506102d66004803603602081101561053757600080fd5b5035611209565b34801561054a57600080fd5b5061055361121e565b60408051602080825283518183015283519192839290830191858101910280838360005b8381101561058f578181015183820152602001610577565b505050509050019250505060405180910390f35b3480156105af57600080fd5b50610553600480360360808110156105c657600080fd5b508035906020810135906040810135151590606001351515611281565b3480156105ef57600080fd5b506105536004803603602081101561060657600080fd5b50356113b2565b34801561061957600080fd5b50610291611523565b34801561062e57600080fd5b506102506004803603602081101561064557600080fd5b5035611529565b34801561065857600080fd5b506102506004803603602081101561066f57600080fd5b5035600160a060020a0316611624565b34801561068b57600080fd5b50610250600480360360208110156106a257600080fd5b50356116be565b3480156106b557600080fd5b50610291600480360360608110156106cc57600080fd5b600160a060020a03823516916020810135918101906060810160408201356401000000008111156106fc57600080fd5b82018360208201111561070e57600080fd5b8035906020019184600183028401116401000000008311171561073057600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550611858945050505050565b34801561077d57600080fd5b50610786611877565b6040805160208082528351818301528351919283929083019185019080838360005b838110156107c05781810151838201526020016107a8565b50505050905090810190601f1680156107ed5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561080757600080fd5b506102916118ae565b34801561081c57600080fd5b506102916118b3565b34801561083157600080fd5b506102916004803603602081101561084857600080fd5b5035600160a060020a03166118b9565b34801561086457600080fd5b506102506004803603604081101561087b57600080fd5b50600160a060020a03813581169160200135166118cb565b34801561089f57600080fd5b50610291600480360360608110156108b657600080fd5b600160a060020a03823516916020810135918101906060810160408201356401000000008111156108e657600080fd5b8201836020820111156108f857600080fd5b8035906020019184600183028401116401000000008311171561091a57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550611af9945050505050565b34801561096757600080fd5b506102506004803603602081101561097e57600080fd5b5035611c34565b34801561099157600080fd5b506102d6600480360360208110156109a857600080fd5b5035611e08565b60038054829081106109bd57fe5b600091825260209091200154600160a060020a0316905081565b333014610a1c576040805160e560020a62461bcd02815260206004820152600d6024820152600080516020611edf833981519152604482015290519081900360640190fd5b600160a060020a038116600090815260026020526040902054819060ff161515610a7e576040805160e560020a62461bcd02815260206004820152600d6024820152600080516020611edf833981519152604482015290519081900360640190fd5b600160a060020a0382166000908152600260205260408120805460ff191690555b60035460001901811015610b545782600160a060020a0316600382815481101515610ac657fe5b600091825260209091200154600160a060020a03161415610b4c57600380546000198101908110610af357fe5b60009182526020909120015460038054600160a060020a039092169183908110610b1957fe5b9060005260206000200160006101000a815481600160a060020a030219169083600160a060020a03160217905550610b54565b600101610a9f565b50600380546000190190610b689082611e1d565b506003546004541115610b8157600354610b8190611529565b604051600160a060020a038316907f8001553a916ef2f495d26a907cc54d96ed840d7bda71e73194bf5a9df7a76b9090600090a25050565b3360008181526002602052604090205460ff161515610c10576040805160e560020a62461bcd02815260206004820152600d6024820152600080516020611edf833981519152604482015290519081900360640190fd5b60008281526001602090815260408083203380855292529091205483919060ff161515610c87576040805160e560020a62461bcd02815260206004820152601a60248201527f4e6f7420636f6e6669726d6564207472616e73616374696f6e2e000000000000604482015290519081900360640190fd5b600084815260208190526040902060030154849060ff1615610cf3576040805160e560020a62461bcd02815260206004820152601560248201527f4578656375746564207472616e73616374696f6e2e0000000000000000000000604482015290519081900360640190fd5b6000858152600160209081526040808320338085529252808320805460ff191690555187927ff6a317157440607f36269043eb55f1287a5a19ba2216afeab88cd46cbcfb88e991a35050505050565b60085481565b60026020526000908152604090205460ff1681565b600160209081526000928352604080842090915290825290205460ff1681565b600754600160a060020a031681565b60065460ff1681565b6000805b600554811015610dfa57838015610dc2575060008181526020819052604090206003015460ff16155b80610de65750828015610de6575060008181526020819052604090206003015460ff165b15610df2576001820191505b600101610d99565b5092915050565b6006546101009004600160a060020a031681565b600a60205260009081526040902054600160a060020a031681565b333014610e75576040805160e560020a62461bcd02815260206004820152600d6024820152600080516020611edf833981519152604482015290519081900360640190fd5b600160a060020a038116600090815260026020526040902054819060ff1615610ed6576040805160e560020a62461bcd02815260206004820152600d6024820152600080516020611edf833981519152604482015290519081900360640190fd5b81600160a060020a0381161515610f37576040805160e560020a62461bcd02815260206004820152600f60248201527f41646472657373206973206e756c6c0000000000000000000000000000000000604482015290519081900360640190fd5b6003805490506001016004546032821180610f5157508181115b80610f5a575080155b80610f63575081155b15610fb8576040805160e560020a62461bcd02815260206004820152601360248201527f496e76616c696420726571756972656d656e7400000000000000000000000000604482015290519081900360640190fd5b600160a060020a038516600081815260026020526040808220805460ff1916600190811790915560038054918201815583527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b01805473ffffffffffffffffffffffffffffffffffffffff191684179055517ff39e6e1eb0edcf53c221607b54b00cd28f3196fed0a24994dc308b8f611b682d9190a25050505050565b600080805b6003548110156110d4576000848152600160205260408120600380549192918490811061108357fe5b6000918252602080832090910154600160a060020a0316835282019290925260400190205460ff16156110b7576001820191505b6004548214156110cc576001925050506110d7565b60010161105a565b50505b919050565b6000805b600354811015611145576000838152600160205260408120600380549192918490811061110957fe5b6000918252602080832090910154600160a060020a0316835282019290925260400190205460ff161561113d576001820191505b6001016110e0565b50919050565b6000602081815291815260409081902080546001808301546002808501805487516101009582161595909502600019011691909104601f8101889004880284018801909652858352600160a060020a03909316959094919291908301828280156111f65780601f106111cb576101008083540402835291602001916111f6565b820191906000526020600020905b8154815290600101906020018083116111d957829003601f168201915b5050506003909301549192505060ff1684565b60096020526000908152604090205460ff1681565b6060600380548060200260200160405190810160405280929190818152602001828054801561127657602002820191906000526020600020905b8154600160a060020a03168152600190910190602001808311611258575b505050505090505b90565b6060806005546040519080825280602002602001820160405280156112b0578160200160208202803883390190505b5090506000805b600554811015611332578580156112e0575060008181526020819052604090206003015460ff16155b806113045750848015611304575060008181526020819052604090206003015460ff165b1561132a5780838381518110151561131857fe5b60209081029091010152600191909101905b6001016112b7565b87870360405190808252806020026020018201604052801561135e578160200160208202803883390190505b5093508790505b868110156113a757828181518110151561137b57fe5b906020019060200201518489830381518110151561139557fe5b60209081029091010152600101611365565b505050949350505050565b6060806003805490506040519080825280602002602001820160405280156113e4578160200160208202803883390190505b5090506000805b60035481101561149c576000858152600160205260408120600380549192918490811061141457fe5b6000918252602080832090910154600160a060020a0316835282019290925260400190205460ff161561149457600380548290811061144f57fe5b6000918252602090912001548351600160a060020a039091169084908490811061147557fe5b600160a060020a03909216602092830290910190910152600191909101905b6001016113eb565b816040519080825280602002602001820160405280156114c6578160200160208202803883390190505b509350600090505b8181101561151b5782818151811015156114e457fe5b9060200190602002015184828151811015156114fc57fe5b600160a060020a039092166020928302909101909101526001016114ce565b505050919050565b60055481565b33301461156e576040805160e560020a62461bcd02815260206004820152600d6024820152600080516020611edf833981519152604482015290519081900360640190fd5b60035481603282118061158057508181115b80611589575080155b80611592575081155b156115e7576040805160e560020a62461bcd02815260206004820152601360248201527f496e76616c696420726571756972656d656e7400000000000000000000000000604482015290519081900360640190fd5b60048390556040805184815290517fa3f1ee9126a074d9326c682f561767f710e927faa811f7a99829d49dc421797a9181900360200190a1505050565b333014611669576040805160e560020a62461bcd02815260206004820152600d6024820152600080516020611edf833981519152604482015290519081900360640190fd5b600654600160a060020a0382811661010090920416141561168957600080fd5b60068054600160a060020a039092166101000274ffffffffffffffffffffffffffffffffffffffff0019909216919091179055565b3360008181526002602052604090205460ff161515611715576040805160e560020a62461bcd02815260206004820152600d6024820152600080516020611edf833981519152604482015290519081900360640190fd5b6000828152602081905260409020548290600160a060020a03161515611785576040805160e560020a62461bcd02815260206004820152601760248201527f45786973746564207472616e73616374696f6e2069642e000000000000000000604482015290519081900360640190fd5b60008381526001602090815260408083203380855292529091205484919060ff16156117fb576040805160e560020a62461bcd02815260206004820152601660248201527f436f6e6669726d6564207472616e73616374696f6e2e00000000000000000000604482015290519081900360640190fd5b6000858152600160208181526040808420338086529252808420805460ff1916909317909255905187927f4a504a94899432a9846e1aa406dceb1bcfd538bb839071d49d1e5e23f5be30ef91a361185185611c34565b5050505050565b6000611865848484611af9565b9050611870816116be565b9392505050565b60408051808201909152600381527f4554480000000000000000000000000000000000000000000000000000000000602082015281565b603281565b60045481565b600b6020526000908152604090205481565b333014611910576040805160e560020a62461bcd02815260206004820152600d6024820152600080516020611edf833981519152604482015290519081900360640190fd5b600160a060020a038216600090815260026020526040902054829060ff161515611972576040805160e560020a62461bcd02815260206004820152600d6024820152600080516020611edf833981519152604482015290519081900360640190fd5b600160a060020a038216600090815260026020526040902054829060ff16156119d3576040805160e560020a62461bcd02815260206004820152600d6024820152600080516020611edf833981519152604482015290519081900360640190fd5b60005b600354811015611a5f5784600160a060020a03166003828154811015156119f957fe5b600091825260209091200154600160a060020a03161415611a575783600382815481101515611a2457fe5b9060005260206000200160006101000a815481600160a060020a030219169083600160a060020a03160217905550611a5f565b6001016119d6565b50600160a060020a03808516600081815260026020526040808220805460ff1990811690915593871682528082208054909416600117909355915190917f8001553a916ef2f495d26a907cc54d96ed840d7bda71e73194bf5a9df7a76b9091a2604051600160a060020a038416907ff39e6e1eb0edcf53c221607b54b00cd28f3196fed0a24994dc308b8f611b682d90600090a250505050565b600083600160a060020a0381161515611b5c576040805160e560020a62461bcd02815260206004820152600f60248201527f41646472657373206973206e756c6c0000000000000000000000000000000000604482015290519081900360640190fd5b60055460408051608081018252600160a060020a0388811682526020808301898152838501898152600060608601819052878152808452959095208451815473ffffffffffffffffffffffffffffffffffffffff191694169390931783555160018301559251805194965091939092611bdc926002850192910190611e46565b50606091909101516003909101805460ff191691151591909117905560058054600101905560405182907fc0ba8fe4b176c1714197d43b9cc6bcf797a4a7461c5fe8d0ef6e184ae7601e5190600090a2509392505050565b600081815260208190526040902060030154819060ff1615611ca0576040805160e560020a62461bcd02815260206004820152601560248201527f4578656375746564207472616e73616374696f6e2e0000000000000000000000604482015290519081900360640190fd5b611ca982611055565b15611e045760008281526020819052604080822060038101805460ff19166001908117909155815481830154935160028085018054959796600160a060020a03909416959394909383928592600019908316156101000201909116048015611d485780601f10611d26576101008083540402835291820191611d48565b820191906000526020600020905b815481529060010190602001808311611d34575b505091505060006040518083038185875af1925050503d8060008114611d8a576040519150601f19603f3d011682016040523d82523d6000602084013e611d8f565b606091505b505090508015611dc95760405184907f33e13ecb54c3076d8e8bb8c2881800a4d972b792045ffae98fdf46df365fed7590600090a2611e01565b60405184907f526441bb6c1aba3c9a4a6ca1d6545da9c2333c8c48343ef398eb858d72b7923690600090a260038201805460ff191690555b50505b5050565b600c6020526000908152604090205460ff1681565b815481835581811115611e4157600083815260209020611e41918101908301611ec4565b505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10611e8757805160ff1916838001178555611eb4565b82800160010185558215611eb4579182015b82811115611eb4578251825591602001919060010190611e99565b50611ec0929150611ec4565b5090565b61127e91905b80821115611ec05760008155600101611eca56fe556e617574686f72697a65642e00000000000000000000000000000000000000a165627a7a72305820620a304d1f4c0cf3ced6c4561eded58216eafb3de08d3b63fc721313a44776de0029
{"success": true, "error": null, "results": {"detectors": [{"check": "reentrancy-eth", "impact": "High", "confidence": "Medium"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'reentrancy-eth', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}]}
82
0x1c2a85a392929e182407845c156b1af99fdf1ac3
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 YCT 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 YCT( 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]; } }
0x6060604052600436106100af576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100b4578063095ea7b31461014257806318160ddd1461019c57806323b872dd146101c557806327e235e31461023e578063313ce5671461028b5780635c658165146102ba57806370a082311461032657806395d89b4114610373578063a9059cbb14610401578063dd62ed3e1461045b575b600080fd5b34156100bf57600080fd5b6100c76104c7565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101075780820151818401526020810190506100ec565b50505050905090810190601f1680156101345780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561014d57600080fd5b610182600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610565565b604051808215151515815260200191505060405180910390f35b34156101a757600080fd5b6101af610657565b6040518082815260200191505060405180910390f35b34156101d057600080fd5b610224600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061065d565b604051808215151515815260200191505060405180910390f35b341561024957600080fd5b610275600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108f7565b6040518082815260200191505060405180910390f35b341561029657600080fd5b61029e61090f565b604051808260ff1660ff16815260200191505060405180910390f35b34156102c557600080fd5b610310600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610922565b6040518082815260200191505060405180910390f35b341561033157600080fd5b61035d600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610947565b6040518082815260200191505060405180910390f35b341561037e57600080fd5b610386610990565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156103c65780820151818401526020810190506103ab565b50505050905090810190601f1680156103f35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561040c57600080fd5b610441600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610a2e565b604051808215151515815260200191505060405180910390f35b341561046657600080fd5b6104b1600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610b87565b6040518082815260200191505060405180910390f35b60038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561055d5780601f106105325761010080835404028352916020019161055d565b820191906000526020600020905b81548152906001019060200180831161054057829003601f168201915b505050505081565b600081600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b60005481565b600080600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015801561072e5750828110155b151561073957600080fd5b82600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8110156108865782600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055505b8373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a360019150509392505050565b60016020528060005260406000206000915090505481565b600460009054906101000a900460ff1681565b6002602052816000526040600020602052806000526040600020600091509150505481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60058054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610a265780601f106109fb57610100808354040283529160200191610a26565b820191906000526020600020905b815481529060010190602001808311610a0957829003601f168201915b505050505081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410151515610a7e57600080fd5b81600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050929150505600a165627a7a723058203e312108c0bd8dd3ab385db21f6744155cdf37bf2191d71b63e98b95e26a95920029
{"success": true, "error": null, "results": {}}
true
null
{}
83
0x1c839fd542563182BFD0C337c8AaD1Be412F0fd2
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
{"success": true, "error": null, "results": {"detectors": [{"check": "reentrancy-eth", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-send", "impact": "Medium", "confidence": "Medium"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'reentrancy-eth', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-send', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}]}
84
0x1c8740e4e6d6f375287176f17c2e58bd2a2eca24
pragma solidity 0.6.12; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c;} function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow");} function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c;} function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) {return 0;} uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c;} function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero");} function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c;} function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero");} function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b;} } 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); function mint(address account, uint256 amount) external; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface Uniswap{ function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function addLiquidityETH(address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline) external payable returns (uint amountToken, uint amountETH, uint liquidity); function getPair(address tokenA, address tokenB) external view returns (address pair); function WETH() external pure returns (address); } interface Pool{ function primary() external view returns (address); } contract Poolable{ address payable internal constant _POOLADDRESS = 0xFD91f75C65D135134E5984F24Cb58136c34E06B0; function primary() private view returns (address) { return Pool(_POOLADDRESS).primary(); } modifier onlyPrimary() { require(msg.sender == primary(), "Caller is not primary"); _; } } contract Staker is Poolable{ using SafeMath for uint256; uint constant internal DECIMAL = 10**18; uint constant public INF = 33136721748; uint private _rewardValue = 10**18; mapping (address => uint256) public timePooled; mapping (address => uint256) private internalTime; mapping (address => uint256) private LPTokenBalance; mapping (address => uint256) private rewards; mapping (address => uint256) private referralEarned; address public YIELDAddress; address constant public UNIROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address constant public FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address public WETHAddress = Uniswap(UNIROUTER).WETH(); bool private _unchangeable = false; bool private _tokenAddressGiven = false; receive() external payable { if(msg.sender != UNIROUTER){ stake(msg.sender, address(0)); } } function sendValue(address payable recipient, uint256 amount) internal { (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } //If true, no changes can be made function unchangeable() public view returns (bool){ return _unchangeable; } function rewardValue() public view returns (uint){ return _rewardValue; } //THE ONLY ADMIN FUNCTIONS vvvv //After this is called, no changes can be made function makeUnchangeable() public{ _unchangeable = true; } //Can only be called once to set token address function setTokenAddress(address input) public{ require(!_tokenAddressGiven, "Function was already called"); _tokenAddressGiven = true; YIELDAddress = input; } //Set reward value that has high APY, can't be called if makeUnchangeable() was called function updateRewardValue(uint input) public { require(!unchangeable(), "makeUnchangeable() function was already called"); _rewardValue = input; } //THE ONLY ADMIN FUNCTIONS ^^^^ function stake(address staker, address payable ref) public payable{ staker = msg.sender; if(ref != address(0)){ referralEarned[ref] = referralEarned[ref] + ((address(this).balance/10)*DECIMAL)/price(); } sendValue(_POOLADDRESS, address(this).balance/2); address poolAddress = Uniswap(FACTORY).getPair(YIELDAddress, WETHAddress); uint ethAmount = IERC20(WETHAddress).balanceOf(poolAddress); //Eth in uniswap uint tokenAmount = IERC20(YIELDAddress).balanceOf(poolAddress); //token in uniswap uint toMint = (address(this).balance.mul(tokenAmount)).div(ethAmount); IERC20(YIELDAddress).mint(address(this), toMint); uint poolTokenAmountBefore = IERC20(poolAddress).balanceOf(address(this)); uint amountTokenDesired = IERC20(YIELDAddress).balanceOf(address(this)); IERC20(YIELDAddress).approve(UNIROUTER, amountTokenDesired ); //allow pool to get tokens Uniswap(UNIROUTER).addLiquidityETH{ value: address(this).balance }(YIELDAddress, amountTokenDesired, 1, 1, address(this), INF); uint poolTokenAmountAfter = IERC20(poolAddress).balanceOf(address(this)); uint poolTokenGot = poolTokenAmountAfter.sub(poolTokenAmountBefore); rewards[staker] = rewards[staker].add(viewRecentRewardTokenAmount(staker)); timePooled[staker] = now; internalTime[staker] = now; LPTokenBalance[staker] = LPTokenBalance[staker].add(poolTokenGot); } function withdrawLPTokens(uint amount) public { require(timePooled[msg.sender] + 3 days <= now, "It has not been 3 days since you staked yet"); rewards[msg.sender] = rewards[msg.sender].add(viewRecentRewardTokenAmount(msg.sender)); LPTokenBalance[msg.sender] = LPTokenBalance[msg.sender].sub(amount); address poolAddress = Uniswap(FACTORY).getPair(YIELDAddress, WETHAddress); IERC20(poolAddress).transfer(msg.sender, amount); internalTime[msg.sender] = now; } function withdrawRewardTokens(uint amount) public { require(timePooled[msg.sender] + 3 days <= now, "It has not been 3 days since you staked yet"); rewards[msg.sender] = rewards[msg.sender].add(viewRecentRewardTokenAmount(msg.sender)); internalTime[msg.sender] = now; uint removeAmount = ethtimeCalc(amount)/2; rewards[msg.sender] = rewards[msg.sender].sub(removeAmount); IERC20(YIELDAddress).mint(msg.sender, amount); } function withdrawReferralEarned(uint amount) public{ require(timePooled[msg.sender] != 0, "You have to stake at least a little bit to withdraw referral rewards"); require(timePooled[msg.sender] + 3 days <= now, "It has not been 3 days since you staked yet"); referralEarned[msg.sender] = referralEarned[msg.sender].sub(amount); IERC20(YIELDAddress).mint(msg.sender, amount); } function viewRecentRewardTokenAmount(address who) internal view returns (uint){ return (viewPooledEthAmount(who).mul( now.sub(internalTime[who]) )); } function viewRewardTokenAmount(address who) public view returns (uint){ return earnCalc( rewards[who].add(viewRecentRewardTokenAmount(who))*2 ); } function viewLPTokenAmount(address who) public view returns (uint){ return LPTokenBalance[who]; } function viewPooledEthAmount(address who) public view returns (uint){ address poolAddress = Uniswap(FACTORY).getPair(YIELDAddress, WETHAddress); uint ethAmount = IERC20(WETHAddress).balanceOf(poolAddress); //Eth in uniswap return (ethAmount.mul(viewLPTokenAmount(who))).div(IERC20(poolAddress).totalSupply()); } function viewPooledTokenAmount(address who) public view returns (uint){ address poolAddress = Uniswap(FACTORY).getPair(YIELDAddress, WETHAddress); uint tokenAmount = IERC20(YIELDAddress).balanceOf(poolAddress); //token in uniswap return (tokenAmount.mul(viewLPTokenAmount(who))).div(IERC20(poolAddress).totalSupply()); } function viewReferralEarned(address who) public view returns (uint){ return referralEarned[who]; } function price() public view returns (uint){ address poolAddress = Uniswap(FACTORY).getPair(YIELDAddress, WETHAddress); uint ethAmount = IERC20(WETHAddress).balanceOf(poolAddress); //Eth in uniswap uint tokenAmount = IERC20(YIELDAddress).balanceOf(poolAddress); //token in uniswap return (DECIMAL.mul(ethAmount)).div(tokenAmount); } function earnCalc(uint ethTime) public view returns(uint){ return ( rewardValue().mul(ethTime) ) / ( 31557600 * DECIMAL ); } function ethtimeCalc(uint YIELD) internal view returns(uint){ return ( YIELD.mul(31557600 * DECIMAL) ).div( rewardValue() ); } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c;} function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow");} function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c;} function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) {return 0;} uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c;} function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero");} function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c;} function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero");} function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b;} } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual 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); } contract Mintable { address private constant _STAKERADDRESS = 0x1C8740e4E6d6f375287176F17c2e58bD2a2ECa24; modifier onlyStaker() { require(msg.sender == _STAKERADDRESS, "Caller is not Staker"); _; } } interface Uniswap{ function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function addLiquidityETH(address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline) external payable returns (uint amountToken, uint amountETH, uint liquidity); function getPair(address tokenA, address tokenB) external view returns (address pair); function WETH() external pure returns (address); } contract YIELD is Context, IERC20, Mintable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor () public { _name = "YIELD"; _symbol = "YIELD"; _decimals = 18; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount != 0, "ERC20: transfer amount was 0"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _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 mint(address account, uint256 amount) public onlyStaker{ _mint(account, amount); } bool createUniswapAlreadyCalled = false; function createUniswap() public payable{ require(!createUniswapAlreadyCalled); createUniswapAlreadyCalled = true; require(address(this).balance > 0); uint toMint = address(this).balance*5; _mint(address(this), toMint); address UNIROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; _allowances[address(this)][UNIROUTER] = toMint; Uniswap(UNIROUTER).addLiquidityETH{ value: address(this).balance }(address(this), toMint, 1, 1, address(this), 33136721748); } receive() external payable { createUniswap(); } }
0x6080604052600436106101395760003560e01c80638439a541116100ab578063b1fd67401161006f578063b1fd67401461059f578063cb43b2dd14610604578063d28de2731461063f578063d488ebe814610680578063e42255d8146106e5578063e91ed7c91461074a57610193565b80638439a541146104845780638d301f99146104bf5780639d2a679f146104fa578063a035b1fe14610525578063a064b44b1461055057610193565b8063452d003f116100fd578063452d003f146102fb578063475d8733146103365780634caacd751461034d5780636dc64a021461037a57806378fd1d58146103df578063808615ac1461042057610193565b80630af88b241461019857806312c7df73146101d957806326a4e8d21461020457806329b83c2e146102555780632dd31000146102ba57610193565b3661019357737a250d5630b4cf539739df2c5dacb4c659f2488d73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610191576101903360006107af565b5b005b600080fd5b3480156101a457600080fd5b506101ad611242565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b3480156101e557600080fd5b506101ee611268565b6040518082815260200191505060405180910390f35b34801561021057600080fd5b506102536004803603602081101561022757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611271565b005b34801561026157600080fd5b506102a46004803603602081101561027857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611353565b6040518082815260200191505060405180910390f35b3480156102c657600080fd5b506102cf61136b565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561030757600080fd5b506103346004803603602081101561031e57600080fd5b8101908080359060200190929190505050611383565b005b34801561034257600080fd5b5061034b611763565b005b34801561035957600080fd5b50610362611780565b60405180821515815260200191505060405180910390f35b34801561038657600080fd5b506103c96004803603602081101561039d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611797565b6040518082815260200191505060405180910390f35b3480156103eb57600080fd5b506103f46117e0565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6104826004803603604081101561043657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506107af565b005b34801561049057600080fd5b506104bd600480360360208110156104a757600080fd5b8101908080359060200190929190505050611806565b005b3480156104cb57600080fd5b506104f8600480360360208110156104e257600080fd5b810190808035906020019092919050505061186e565b005b34801561050657600080fd5b5061050f611ae7565b6040518082815260200191505060405180910390f35b34801561053157600080fd5b5061053a611af0565b6040518082815260200191505060405180910390f35b34801561055c57600080fd5b506105896004803603602081101561057357600080fd5b8101908080359060200190929190505050611dd2565b6040518082815260200191505060405180910390f35b3480156105ab57600080fd5b506105ee600480360360208110156105c257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611e0c565b6040518082815260200191505060405180910390f35b34801561061057600080fd5b5061063d6004803603602081101561062757600080fd5b81019080803590602001909291905050506120a7565b005b34801561064b57600080fd5b50610654612380565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561068c57600080fd5b506106cf600480360360208110156106a357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612398565b6040518082815260200191505060405180910390f35b3480156106f157600080fd5b506107346004803603602081101561070857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612406565b6040518082815260200191505060405180910390f35b34801561075657600080fd5b506107996004803603602081101561076d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506126a1565b6040518082815260200191505060405180910390f35b339150600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614610890576107ee611af0565b670de0b6b3a7640000600a478161080157fe5b04028161080a57fe5b04600560008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205401600560008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b6108b873fd91f75c65d135134e5984f24cb58136c34e06b0600247816108b257fe5b046126ea565b6000735c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f73ffffffffffffffffffffffffffffffffffffffff1663e6a43905600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1681526020019250505060206040518083038186803b15801561099757600080fd5b505afa1580156109ab573d6000803e3d6000fd5b505050506040513d60208110156109c157600080fd5b810190808051906020019092919050505090506000600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231836040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b158015610a5f57600080fd5b505afa158015610a73573d6000803e3d6000fd5b505050506040513d6020811015610a8957600080fd5b810190808051906020019092919050505090506000600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231846040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b158015610b2757600080fd5b505afa158015610b3b573d6000803e3d6000fd5b505050506040513d6020811015610b5157600080fd5b810190808051906020019092919050505090506000610b8b83610b7d84476127ae90919063ffffffff16565b61283490919063ffffffff16565b9050600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166340c10f1930836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050600060405180830381600087803b158015610c2057600080fd5b505af1158015610c34573d6000803e3d6000fd5b5050505060008473ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b158015610ca157600080fd5b505afa158015610cb5573d6000803e3d6000fd5b505050506040513d6020811015610ccb57600080fd5b810190808051906020019092919050505090506000600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b158015610d6957600080fd5b505afa158015610d7d573d6000803e3d6000fd5b505050506040513d6020811015610d9357600080fd5b81019080805190602001909291905050509050600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663095ea7b3737a250d5630b4cf539739df2c5dacb4c659f2488d836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b158015610e4d57600080fd5b505af1158015610e61573d6000803e3d6000fd5b505050506040513d6020811015610e7757600080fd5b810190808051906020019092919050505050737a250d5630b4cf539739df2c5dacb4c659f2488d73ffffffffffffffffffffffffffffffffffffffff1663f305d71947600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1684600180306407b71a3f546040518863ffffffff1660e01b8152600401808773ffffffffffffffffffffffffffffffffffffffff1681526020018681526020018581526020018481526020018373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200196505050505050506060604051808303818588803b158015610f6c57600080fd5b505af1158015610f80573d6000803e3d6000fd5b50505050506040513d6060811015610f9757600080fd5b8101908080519060200190929190805190602001909291908051906020019092919050505050505060008673ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561102857600080fd5b505afa15801561103c573d6000803e3d6000fd5b505050506040513d602081101561105257600080fd5b81019080805190602001909291905050509050600061107a848361287e90919063ffffffff16565b90506110d66110888b6128c8565b600460008d73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461293d90919063ffffffff16565b600460008c73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555042600160008c73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555042600260008c73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506111f381600360008d73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461293d90919063ffffffff16565b600360008c73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555050505050505050505050565b600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60008054905090565b600760159054906101000a900460ff16156112f4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f46756e6374696f6e2077617320616c72656164792063616c6c6564000000000081525060200191505060405180910390fd5b6001600760156101000a81548160ff02191690831515021790555080600660006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b60016020528060005260406000206000915090505481565b735c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f81565b426203f480600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054011115611420576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602b815260200180612c2e602b913960400191505060405180910390fd5b61147a61142c336128c8565b600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461293d90919063ffffffff16565b600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061150f81600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461287e90919063ffffffff16565b600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506000735c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f73ffffffffffffffffffffffffffffffffffffffff1663e6a43905600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1681526020019250505060206040518083038186803b15801561163157600080fd5b505afa158015611645573d6000803e3d6000fd5b505050506040513d602081101561165b57600080fd5b810190808051906020019092919050505090508073ffffffffffffffffffffffffffffffffffffffff1663a9059cbb33846040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b1580156116df57600080fd5b505af11580156116f3573d6000803e3d6000fd5b505050506040513d602081101561170957600080fd5b81019080805190602001909291905050505042600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505050565b6001600760146101000a81548160ff021916908315150217905550565b6000600760149054906101000a900460ff16905090565b6000600560008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b61180e611780565b15611864576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602e815260200180612c59602e913960400191505060405180910390fd5b8060008190555050565b6000600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541415611907576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526044815260200180612b8f6044913960600191505060405180910390fd5b426203f480600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020540111156119a4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602b815260200180612c2e602b913960400191505060405180910390fd5b6119f681600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461287e90919063ffffffff16565b600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166340c10f1933836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050600060405180830381600087803b158015611acc57600080fd5b505af1158015611ae0573d6000803e3d6000fd5b5050505050565b6407b71a3f5481565b600080735c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f73ffffffffffffffffffffffffffffffffffffffff1663e6a43905600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1681526020019250505060206040518083038186803b158015611bd057600080fd5b505afa158015611be4573d6000803e3d6000fd5b505050506040513d6020811015611bfa57600080fd5b810190808051906020019092919050505090506000600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231836040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b158015611c9857600080fd5b505afa158015611cac573d6000803e3d6000fd5b505050506040513d6020811015611cc257600080fd5b810190808051906020019092919050505090506000600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231846040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b158015611d6057600080fd5b505afa158015611d74573d6000803e3d6000fd5b505050506040513d6020811015611d8a57600080fd5b81019080805190602001909291905050509050611dca81611dbc84670de0b6b3a76400006127ae90919063ffffffff16565b61283490919063ffffffff16565b935050505090565b6000670de0b6b3a76400006301e187e002611dfd83611def611268565b6127ae90919063ffffffff16565b81611e0457fe5b049050919050565b600080735c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f73ffffffffffffffffffffffffffffffffffffffff1663e6a43905600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1681526020019250505060206040518083038186803b158015611eec57600080fd5b505afa158015611f00573d6000803e3d6000fd5b505050506040513d6020811015611f1657600080fd5b810190808051906020019092919050505090506000600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231836040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b158015611fb457600080fd5b505afa158015611fc8573d6000803e3d6000fd5b505050506040513d6020811015611fde57600080fd5b8101908080519060200190929190505050905061209e8273ffffffffffffffffffffffffffffffffffffffff166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561203a57600080fd5b505afa15801561204e573d6000803e3d6000fd5b505050506040513d602081101561206457600080fd5b8101908080519060200190929190505050612090612081876126a1565b846127ae90919063ffffffff16565b61283490919063ffffffff16565b92505050919050565b426203f480600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054011115612144576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602b815260200180612c2e602b913960400191505060405180910390fd5b61219e612150336128c8565b600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461293d90919063ffffffff16565b600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555042600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555060006002612232836129c5565b8161223957fe5b04905061228e81600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461287e90919063ffffffff16565b600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166340c10f1933846040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050600060405180830381600087803b15801561236457600080fd5b505af1158015612378573d6000803e3d6000fd5b505050505050565b737a250d5630b4cf539739df2c5dacb4c659f2488d81565b60006123ff60026123f96123ab856128c8565b600460008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461293d90919063ffffffff16565b02611dd2565b9050919050565b600080735c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f73ffffffffffffffffffffffffffffffffffffffff1663e6a43905600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1681526020019250505060206040518083038186803b1580156124e657600080fd5b505afa1580156124fa573d6000803e3d6000fd5b505050506040513d602081101561251057600080fd5b810190808051906020019092919050505090506000600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231836040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b1580156125ae57600080fd5b505afa1580156125c2573d6000803e3d6000fd5b505050506040513d60208110156125d857600080fd5b810190808051906020019092919050505090506126988273ffffffffffffffffffffffffffffffffffffffff166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561263457600080fd5b505afa158015612648573d6000803e3d6000fd5b505050506040513d602081101561265e57600080fd5b810190808051906020019092919050505061268a61267b876126a1565b846127ae90919063ffffffff16565b61283490919063ffffffff16565b92505050919050565b6000600360008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60008273ffffffffffffffffffffffffffffffffffffffff168260405180600001905060006040518083038185875af1925050503d806000811461274a576040519150601f19603f3d011682016040523d82523d6000602084013e61274f565b606091505b50509050806127a9576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252603a815260200180612bd3603a913960400191505060405180910390fd5b505050565b6000808314156127c1576000905061282e565b60008284029050828482816127d257fe5b0414612829576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180612c0d6021913960400191505060405180910390fd5b809150505b92915050565b600061287683836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250612a08565b905092915050565b60006128c083836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250612ace565b905092915050565b600061293661291f600260008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020544261287e90919063ffffffff16565b61292884611e0c565b6127ae90919063ffffffff16565b9050919050565b6000808284019050838110156129bb576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b6000612a016129d2611268565b6129f3670de0b6b3a76400006301e187e002856127ae90919063ffffffff16565b61283490919063ffffffff16565b9050919050565b60008083118290612ab4576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015612a79578082015181840152602081019050612a5e565b50505050905090810190601f168015612aa65780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b506000838581612ac057fe5b049050809150509392505050565b6000838311158290612b7b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015612b40578082015181840152602081019050612b25565b50505050905090810190601f168015612b6d5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b506000838503905080915050939250505056fe596f75206861766520746f207374616b65206174206c656173742061206c6974746c652062697420746f20776974686472617720726566657272616c2072657761726473416464726573733a20756e61626c6520746f2073656e642076616c75652c20726563697069656e74206d61792068617665207265766572746564536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77497420686173206e6f74206265656e203320646179732073696e636520796f75207374616b6564207965746d616b65556e6368616e676561626c6528292066756e6374696f6e2077617320616c72656164792063616c6c6564a264697066735822122079a0b840450479f5b61e974ea03cb801d1b1a8316a174650662e67cc3266cf6c64736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "name-reused", "impact": "High", "confidence": "High"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'name-reused', 'impact': 'High', 'confidence': 'High'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}]}
85
0x1D09144F3479bb805CB7c92346987420BcbDC10C
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; uint private _totalSupply; 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 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"); } } } library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; function mul(int256 a, int256 b) internal pure returns (int256) { if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } function sqrt(int256 x) internal pure returns (int256) { int256 z = add(x / 2, 1); int256 y = x; while (z < y) { y = z; z = ((add((x / z), z)) / 2); } return y; } } contract CreamY is ERC20, ERC20Detailed { event LOG_SWAP( address indexed caller, address indexed tokenIn, address indexed tokenOut, uint tokenAmountIn, uint tokenAmountOut ); event LOG_JOIN( address indexed caller, address indexed tokenIn, uint tokenAmountIn ); event LOG_EXIT( address indexed caller, address indexed tokenOut, uint tokenAmountOut ); using SafeMath for uint; using SignedSafeMath for int256; using SafeERC20 for IERC20; mapping(address => bool) public coins; mapping(address => bool) public pause; IERC20[] public allCoins; Normalizer public normalizer; address public governance; address public reservePool; constructor(address _normalizer, address _reservePool) public ERC20Detailed("CreamY USD", "cyUSD", 18) { governance = msg.sender; normalizer = Normalizer(_normalizer); reservePool = _reservePool; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setNormalizer(address _normalizer) external { require(msg.sender == governance, "!governance"); normalizer = Normalizer(_normalizer); } function setReservePool(address _reservePool) external { require(msg.sender == governance, "!governance"); require(_reservePool != address(0), "invalid reserve pool"); reservePool = _reservePool; } function setFees(uint _fee, uint _reserveRatio) external { require(msg.sender == governance, '!governance'); require(_fee < 1e18 && _fee >= 0.99e18, 'Invalid fee'); // 0 < fee <= 1% if (_reserveRatio > 0) { require(_reserveRatio <= 1e18, 'Invalid reserve ratio'); // reserve ratio <= 100% fee } fee = _fee; reserveRatio = _reserveRatio; } function approveCoins(address _coin) external { require(msg.sender == governance, "!governance"); require(coins[_coin] == false, "Already approved"); coins[_coin] = true; allCoins.push(IERC20(_coin)); } function setPause(address _coin, bool _pause) external { require(msg.sender == governance, "!governance"); pause[_coin] = _pause; } function setA(uint _A) external { require(msg.sender == governance, "!governance"); require(_A > 0 && _A <= 1e18, "Invalid A"); // When A is close to 1, it becomes the fixed price model (x + y = k). // When A is close to 0, it degenerates to Uniswap (x * y = k). // However, A couldn't be exactly 0 since it will break the f function. A = _A; } function seize(IERC20 token, uint amount) external { require(msg.sender == governance, "!governance"); require(!tokens[address(token)], "can't seize liquidity"); uint bal = token.balanceOf(address(this)); require(amount <= bal); token.safeTransfer(reservePool, amount); } uint public fee = 0.99965e18; uint public reserveRatio = 1e18; uint public constant BASE = 1e18; uint public A = 0.7e18; uint public count = 0; mapping(address => bool) tokens; function f(int256 _x, int256 x, int256 y) internal view returns (int256 _y) { int256 k; int256 c; { int256 u = x.add(y.mul(int256(A)).div(1e18)); int256 v = y.add(x.mul(int256(A)).div(1e18)); k = u.mul(v); c = _x.mul(_x).sub(k.mul(1e18).div(int256(A))); } int256 cst = int256(A).add(int256(1e36).div(int256(A))); int256 _b = _x.mul(cst).div(1e18); int256 D = _b.mul(_b).sub(c.mul(4)); require(D >= 0, "!root"); _y = (-_b).add(D.sqrt()).div(2); } function collectReserve(IERC20 from, uint input) internal { if (reserveRatio > 0) { uint _fee = input.mul(BASE.sub(fee)).div(BASE); uint _reserve = _fee.mul(reserveRatio).div(BASE); from.safeTransfer(reservePool, _reserve); } } // Get all support coins function getAllCoins() public view returns (IERC20[] memory) { return allCoins; } // Calculate total pool value in USD function calcTotalValue() public view returns (uint value) { uint totalValue = uint(0); for (uint i = 0; i < allCoins.length; i++) { totalValue = totalValue.add(balance(allCoins[i])); } return totalValue; } // Calculate _x given x, y, _y function getX(int256 output, int256 x, int256 y) internal view returns (int256 input) { int256 _y = y.sub(output); int256 _x = f(_y, y, x); input = _x.sub(x); } // Calculate _y given x, y, _x function getY(int256 input, int256 x, int256 y) internal view returns (int256 output) { int256 _x = x.add(input); int256 _y = f(_x, x, y); output = y.sub(_y); } // Calculate output given exact input function getOutExactIn(IERC20 from, IERC20 to, uint input, int256 x, int256 y) public view returns (uint output) { uint inputInUsd = normalize1e18(from, input).mul(normalizer.getPrice(address(from))).div(1e18); uint inputAfterFeeInUsd = inputInUsd.mul(fee).div(BASE); uint outputInUsd = uint(getY(i(inputAfterFeeInUsd), x, y)); output = normalize(to, outputInUsd.mul(1e18).div(normalizer.getPrice(address(to)))); } // Calculate input given exact output function getInExactOut(IERC20 from, IERC20 to, uint output, int256 x, int256 y) public view returns (uint input) { uint outputInUsd = normalize1e18(to, output).mul(normalizer.getPrice(address(to))).div(1e18); uint inputBeforeFeeInUsd = uint(getX(i(outputInUsd), x, y)); uint inputInUsd = inputBeforeFeeInUsd.mul(BASE).div(fee); input = normalize(from, inputInUsd.mul(1e18).div(normalizer.getPrice(address(from)))); } // Normalize coin to 1e18 function normalize1e18(IERC20 token, uint _amount) internal view returns (uint) { uint _decimals = ERC20Detailed(address(token)).decimals(); if (_decimals == uint(18)) { return _amount; } else { return _amount.mul(1e18).div(uint(10)**_decimals); } } // Normalize coin to original decimals function normalize(IERC20 token, uint _amount) internal view returns (uint) { uint _decimals = ERC20Detailed(address(token)).decimals(); if (_decimals == uint(18)) { return _amount; } else { return _amount.mul(uint(10)**_decimals).div(1e18); } } // Contract balance of coin normalized to 1e18 function balance(IERC20 token) public view returns (uint) { address _token = address(token); uint _balance = IERC20(_token).balanceOf(address(this)); uint _balanceInUsd = _balance.mul(normalizer.getPrice(_token)).div(1e18); return normalize1e18(token, _balanceInUsd); } // Converter helper to int256 function i(uint x) public pure returns (int256) { int256 value = int256(x); require(value >= 0, 'overflow'); return value; } function swapExactAmountIn(IERC20 from, IERC20 to, uint input, uint minOutput, uint deadline) external returns (uint output) { require(coins[address(from)] == true, "!coin"); require(pause[address(from)] == false, "pause"); require(coins[address(to)] == true, "!coin"); require(pause[address(to)] == false, "pause"); require(normalizer.getPrice(address(from)) > 0, "zero price"); require(normalizer.getPrice(address(to)) > 0, "zero price"); require(block.timestamp <= deadline, "expired"); output = getOutExactIn(from, to, input, i(balance(from)), i(balance(to))); require(balance(to) >= output, "insufficient output liquidity"); require(output >= minOutput, "slippage"); emit LOG_SWAP(msg.sender, address(from), address(to), input, output); from.safeTransferFrom(msg.sender, address(this), input); to.safeTransfer(msg.sender, output); collectReserve(from, input); return output; } function swapExactAmountOut(IERC20 from, IERC20 to, uint maxInput, uint output, uint deadline) external returns (uint input) { require(coins[address(from)] == true, "!coin"); require(pause[address(from)] == false, "pause"); require(coins[address(to)] == true, "!coin"); require(pause[address(to)] == false, "pause"); require(normalizer.getPrice(address(from)) > 0, "zero price"); require(normalizer.getPrice(address(to)) > 0, "zero price"); require(block.timestamp <= deadline, "expired"); require(balance(to) >= output, "insufficient output liquidity"); input = getInExactOut(from, to, output, i(balance(from)), i(balance(to))); require(input <= maxInput, "slippage"); emit LOG_SWAP(msg.sender, address(from), address(to), input, output); from.safeTransferFrom(msg.sender, address(this), input); to.safeTransfer(msg.sender, output); collectReserve(from, input); return input; } function addLiquidityExactIn(IERC20 from, uint input, uint minOutput, uint deadline) external returns (uint output) { require(coins[address(from)] == true, "!coin"); require(pause[address(from)] == false, "pause"); require(block.timestamp <= deadline, "expired"); require(input > 0, "zero input"); require(normalizer.getPrice(address(from)) > 0, "zero price"); require(normalizer.getPrice(address(this)) > 0, "zero price"); if (totalSupply() == 0) { uint inputAfterFee = input.mul(fee).div(BASE); output = normalize1e18(from, inputAfterFee.mul(normalizer.getPrice(address(from))).div(1e18)); } else { output = getOutExactIn(from, this, input, i(balance(from)), i(totalSupply().div(count))); } require(output >= minOutput, "slippage"); emit LOG_JOIN(msg.sender, address(from), output); from.safeTransferFrom(msg.sender, address(this), input); _mint(msg.sender, output); if (!tokens[address(from)] && balance(from) > 0) { tokens[address(from)] = true; count = count.add(1); } } function addLiquidityExactOut(IERC20 from, uint maxInput, uint output, uint deadline) external returns (uint input) { require(coins[address(from)] == true, "!coin"); require(pause[address(from)] == false, "pause"); require(block.timestamp <= deadline, "expired"); require(output > 0, "zero output"); require(normalizer.getPrice(address(from)) > 0, "zero price"); require(normalizer.getPrice(address(this)) > 0, "zero price"); if (totalSupply() == 0) { uint inputAfterFee = normalize(from, output.mul(1e18).div(normalizer.getPrice(address(from)))); input = inputAfterFee.mul(BASE).divCeil(fee); } else { input = getInExactOut(from, this, output, i(balance(from)), i(totalSupply().div(count))); } require(input <= maxInput, "slippage"); emit LOG_JOIN(msg.sender, address(from), output); from.safeTransferFrom(msg.sender, address(this), input); _mint(msg.sender, output); if (!tokens[address(from)] && balance(from) > 0) { tokens[address(from)] = true; count = count.add(1); } } function removeLiquidityExactIn(IERC20 to, uint input, uint minOutput, uint deadline) external returns (uint output) { require(block.timestamp <= deadline, "expired"); require(coins[address(to)] == true, "!coin"); require(input > 0, "zero input"); require(normalizer.getPrice(address(this)) > 0, "zero price"); require(normalizer.getPrice(address(to)) > 0, "zero price"); output = getOutExactIn(this, to, input, i(totalSupply().div(count)), i(balance(to))); require(output >= minOutput, "slippage"); emit LOG_EXIT(msg.sender, address(to), output); _burn(msg.sender, input); to.safeTransfer(msg.sender, output); if (balance(to) == 0) { tokens[address(to)] = false; count = count.sub(1); } } function removeLiquidityExactOut(IERC20 to, uint maxInput, uint output, uint deadline) external returns (uint input) { require(block.timestamp <= deadline, "expired"); require(coins[address(to)] == true, "!coin"); require(output > 0, "zero output"); require(normalizer.getPrice(address(this)) > 0, "zero price"); require(normalizer.getPrice(address(to)) > 0, "zero price"); input = getInExactOut(this, to, output, i(totalSupply().div(count)), i(balance(to))); require(input <= maxInput, "slippage"); emit LOG_EXIT(msg.sender, address(to), output); _burn(msg.sender, input); to.safeTransfer(msg.sender, output); if (balance(to) == 0) { tokens[address(to)] = false; count = count.sub(1); } } } interface Curve { function get_virtual_price() external view returns (uint); } interface Yearn { function getPricePerFullShare() external view returns (uint); } interface UnderlyingToken { function decimals() external view returns (uint8); } interface Compound { function exchangeRateStored() external view returns (uint); function underlying() external view returns (address); } interface Cream { function exchangeRateStored() external view returns (uint); function underlying() external view returns (address); } contract Normalizer { using SafeMath for uint; address public governance; address public creamY; mapping(address => bool) public native; mapping(address => bool) public yearn; mapping(address => bool) public curve; mapping(address => address) public curveSwap; mapping(address => bool) public vaults; mapping(address => bool) public compound; mapping(address => bool) public cream; mapping(address => uint) public underlyingDecimals; constructor() public { governance = msg.sender; native[0xdAC17F958D2ee523a2206206994597C13D831ec7] = true; // USDT native[0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48] = true; // USDC native[0x4Fabb145d64652a948d72533023f6E7A623C7C53] = true; // BUSD native[0x0000000000085d4780B73119b644AE5ecd22b376] = true; // TUSD yearn[0xACd43E627e64355f1861cEC6d3a6688B31a6F952] = true; // vault yDAI yearn[0x37d19d1c4E1fa9DC47bD1eA12f742a0887eDa74a] = true; // vault yTUSD yearn[0x597aD1e0c13Bfe8025993D9e79C69E1c0233522e] = true; // vault yUSDC yearn[0x2f08119C6f07c006695E079AAFc638b8789FAf18] = true; // vault yUSDT yearn[0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01] = true; // yDAI yearn[0xd6aD7a6750A7593E092a9B218d66C0A814a3436e] = true; // yUSDC yearn[0x83f798e925BcD4017Eb265844FDDAbb448f1707D] = true; // yUSDT yearn[0x73a052500105205d34Daf004eAb301916DA8190f] = true; // yTUSD yearn[0xF61718057901F84C4eEC4339EF8f0D86D2B45600] = true; // ySUSD yearn[0xC2cB1040220768554cf699b0d863A3cd4324ce32] = true; // bDAI yearn[0x26EA744E5B887E5205727f55dFBE8685e3b21951] = true; // bUSDC yearn[0xE6354ed5bC4b393a5Aad09f21c46E101e692d447] = true; // bUSDT yearn[0x04bC0Ab673d88aE9dbC9DA2380cB6B79C4BCa9aE] = true; // bBUSD curve[0x845838DF265Dcd2c412A1Dc9e959c7d08537f8a2] = true; // cCompound curveSwap[0x845838DF265Dcd2c412A1Dc9e959c7d08537f8a2] = 0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56; curve[0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8] = true; // cYearn curveSwap[0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8] = 0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51; curve[0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B] = true; // cBUSD curveSwap[0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B] = 0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27; curve[0xC25a3A3b969415c80451098fa907EC722572917F] = true; // cSUSD curveSwap[0xC25a3A3b969415c80451098fa907EC722572917F] = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD; curve[0xD905e2eaeBe188fc92179b6350807D8bd91Db0D8] = true; // cPAX curveSwap[0xD905e2eaeBe188fc92179b6350807D8bd91Db0D8] = 0x06364f10B501e868329afBc005b3492902d6C763; compound[0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643] = true; // cDAI underlyingDecimals[0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643] = 1e18; compound[0x39AA39c021dfbaE8faC545936693aC917d5E7563] = true; // cUSDC underlyingDecimals[0x39AA39c021dfbaE8faC545936693aC917d5E7563] = 1e6; compound[0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9] = true; // cUSDT underlyingDecimals[0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9] = 1e6; cream[0x44fbeBd2F576670a6C33f6Fc0B00aA8c5753b322] = true; // crUSDC underlyingDecimals[0x44fbeBd2F576670a6C33f6Fc0B00aA8c5753b322] = 1e6; cream[0x797AAB1ce7c01eB727ab980762bA88e7133d2157] = true; // crUSDT underlyingDecimals[0x797AAB1ce7c01eB727ab980762bA88e7133d2157] = 1e6; cream[0x1FF8CDB51219a8838b52E9cAc09b71e591BC998e] = true; // crBUSD underlyingDecimals[0x1FF8CDB51219a8838b52E9cAc09b71e591BC998e] = 1e18; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setCreamY(address _creamY) external { require(msg.sender == governance, "!governance"); creamY = _creamY; } function getPrice(address token) external view returns (uint) { if (native[token] || token == creamY) { return 1e18; } else if (yearn[token]) { return Yearn(token).getPricePerFullShare(); } else if (curve[token]) { return Curve(curveSwap[token]).get_virtual_price(); } else if (compound[token]) { return getCompoundPrice(token); } else if (cream[token]) { return getCreamPrice(token); } else { return uint(0); } } function getCompoundPrice(address token) public view returns (uint) { address underlying = Compound(token).underlying(); uint8 decimals = UnderlyingToken(underlying).decimals(); return Compound(token).exchangeRateStored().mul(1e8).div(uint(10) ** decimals); } function getCreamPrice(address token) public view returns (uint) { address underlying = Cream(token).underlying(); uint8 decimals = UnderlyingToken(underlying).decimals(); return Cream(token).exchangeRateStored().mul(1e8).div(uint(10) ** 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; } function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; if(a % b != 0) c = c + 1; return c; } }
0x608060405234801561001057600080fd5b506004361061025e5760003560e01c806370a0823111610146578063ab033ea9116100c3578063e3d670d711610087578063e3d670d71461083b578063eb9253c014610861578063ec342ad01461088d578063ee919d5014610895578063ef9aa9fc146108b2578063f446c1d0146108ea5761025e565b8063ab033ea914610779578063c22dc7221461079f578063cd55e092146107cd578063dd62ed3e14610805578063ddca3f43146108335761025e565b8063a00251c61161010a578063a00251c6146106b9578063a457c2d7146106c1578063a4ec0620146106ed578063a9059cbb14610745578063a919987b146107715761025e565b806370a082311461061957806376a67a511461063f5780637d0f7a88146106655780639179182d1461068b57806395d89b41146106b15761025e565b80631820b47f116101df5780633397d601116101a35780633397d6011461051f5780633575c19e1461056157806339509351146105875780634f393a07146105b35780635aa6e675146105d95780636015f4ef146105e15761025e565b80631820b47f1461042a57806323b872dd1461046c57806326e2da7b146104a257806329688a80146104e4578063313ce567146105015761025e565b806309866f611161022657806309866f61146103965780630b78f9c0146103d85780630c7d5cd8146103fd57806313560cac1461040557806318160ddd146104225761025e565b80630266f0441461026357806303d938681461028757806306661abd146102d157806306fdde03146102d9578063095ea7b314610356575b600080fd5b61026b6108f2565b604080516001600160a01b039092168252519081900360200190f35b6102bf6004803603608081101561029d57600080fd5b506001600160a01b038135169060208101359060408101359060600135610901565b60408051918252519081900360200190f35b6102bf610ddc565b6102e1610de2565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561031b578181015183820152602001610303565b50505050905090810190601f1680156103485780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6103826004803603604081101561036c57600080fd5b506001600160a01b038135169060200135610e78565b604080519115158252519081900360200190f35b6102bf600480360360a08110156103ac57600080fd5b506001600160a01b03813581169160208101359091169060408101359060608101359060800135610e96565b6103fb600480360360408110156103ee57600080fd5b5080359060200135611026565b005b6102bf611137565b61026b6004803603602081101561041b57600080fd5b503561113d565b6102bf611164565b6102bf600480360360a081101561044057600080fd5b506001600160a01b0381358116916020810135909116906040810135906060810135906080013561116a565b6103826004803603606081101561048257600080fd5b506001600160a01b038135811691602081013590911690604001356115e8565b6102bf600480360360a08110156104b857600080fd5b506001600160a01b03813581169160208101359091169060408101359060608101359060800135611675565b6102bf600480360360208110156104fa57600080fd5b50356117a3565b6105096117e6565b6040805160ff9092168252519081900360200190f35b6102bf600480360360a081101561053557600080fd5b506001600160a01b038135811691602081013590911690604081013590606081013590608001356117ef565b6103fb6004803603602081101561057757600080fd5b50356001600160a01b0316611c5f565b6103826004803603604081101561059d57600080fd5b506001600160a01b038135169060200135611cce565b6103fb600480360360208110156105c957600080fd5b50356001600160a01b0316611d22565b61026b611de3565b6102bf600480360360808110156105f757600080fd5b506001600160a01b038135169060208101359060408101359060600135611df2565b6102bf6004803603602081101561062f57600080fd5b50356001600160a01b0316612140565b6103826004803603602081101561065557600080fd5b50356001600160a01b031661215b565b6103826004803603602081101561067b57600080fd5b50356001600160a01b0316612170565b6103fb600480360360208110156106a157600080fd5b50356001600160a01b0316612185565b6102e1612299565b6102bf6122fa565b610382600480360360408110156106d757600080fd5b506001600160a01b038135169060200135612353565b6106f56123c1565b60408051602080825283518183015283519192839290830191858101910280838360005b83811015610731578181015183820152602001610719565b505050509050019250505060405180910390f35b6103826004803603604081101561075b57600080fd5b506001600160a01b038135169060200135612422565b61026b612436565b6103fb6004803603602081101561078f57600080fd5b50356001600160a01b0316612445565b6103fb600480360360408110156107b557600080fd5b506001600160a01b03813516906020013515156124b4565b6102bf600480360360808110156107e357600080fd5b506001600160a01b03813516906020810135906040810135906060013561252c565b6102bf6004803603604081101561081b57600080fd5b506001600160a01b038135811691602001351661297b565b6102bf6129a6565b6102bf6004803603602081101561085157600080fd5b50356001600160a01b03166129ac565b6103fb6004803603604081101561087757600080fd5b506001600160a01b038135169060200135612acf565b6102bf612c2c565b6103fb600480360360208110156108ab57600080fd5b5035612c38565b6102bf600480360360808110156108c857600080fd5b506001600160a01b038135169060208101359060408101359060600135612cdf565b6102bf612feb565b600b546001600160a01b031681565b6001600160a01b03841660009081526006602052604081205460ff16151560011461095b576040805162461bcd60e51b815260206004820152600560248201526410b1b7b4b760d91b604482015290519081900360640190fd5b6001600160a01b03851660009081526007602052604090205460ff16156109b1576040805162461bcd60e51b8152602060048201526005602482015264706175736560d81b604482015290519081900360640190fd5b814211156109f0576040805162461bcd60e51b8152602060048201526007602482015266195e1c1a5c995960ca1b604482015290519081900360640190fd5b60008411610a32576040805162461bcd60e51b815260206004820152600a6024820152691e995c9bc81a5b9c1d5d60b21b604482015290519081900360640190fd5b600954604080516341976e0960e01b81526001600160a01b038881166004830152915160009392909216916341976e0991602480820192602092909190829003018186803b158015610a8357600080fd5b505afa158015610a97573d6000803e3d6000fd5b505050506040513d6020811015610aad57600080fd5b505111610aee576040805162461bcd60e51b815260206004820152600a6024820152697a65726f20707269636560b01b604482015290519081900360640190fd5b600954604080516341976e0960e01b815230600482015290516000926001600160a01b0316916341976e09916024808301926020929190829003018186803b158015610b3957600080fd5b505afa158015610b4d573d6000803e3d6000fd5b505050506040513d6020811015610b6357600080fd5b505111610ba4576040805162461bcd60e51b815260206004820152600a6024820152697a65726f20707269636560b01b604482015290519081900360640190fd5b610bac611164565b610c8d576000610bdf670de0b6b3a7640000610bd3600c5488612ff190919063ffffffff16565b9063ffffffff61305116565b600954604080516341976e0960e01b81526001600160a01b03808b1660048301529151939450610c85938a93610c8093670de0b6b3a764000093610bd39391909216916341976e09916024808301926020929190829003018186803b158015610c4757600080fd5b505afa158015610c5b573d6000803e3d6000fd5b505050506040513d6020811015610c7157600080fd5b5051869063ffffffff612ff116565b613093565b915050610cbd565b610cba853086610ca4610c9f8a6129ac565b6117a3565b610cb5610c9f600f54610bd3611164565b610e96565b90505b82811015610cfd576040805162461bcd60e51b8152602060048201526008602482015267736c69707061676560c01b604482015290519081900360640190fd5b6040805182815290516001600160a01b0387169133917f63982df10efd8dfaaaa0fcc7f50b2d93b7cba26ccc48adee2873220d485dc39a9181900360200190a3610d586001600160a01b03861633308763ffffffff61313a16565b610d62338261319a565b6001600160a01b03851660009081526010602052604090205460ff16158015610d9357506000610d91866129ac565b115b15610dd4576001600160a01b0385166000908152601060205260409020805460ff19166001908117909155600f54610dd09163ffffffff61328a16565b600f555b949350505050565b600f5481565b60038054604080516020601f6002600019610100600188161502019095169490940493840181900481028201810190925282815260609390929091830182828015610e6e5780601f10610e4357610100808354040283529160200191610e6e565b820191906000526020600020905b815481529060010190602001808311610e5157829003601f168201915b5050505050905090565b6000610e8c610e856132e4565b84846132e8565b5060015b92915050565b600954604080516341976e0960e01b81526001600160a01b03888116600483015291516000938493610f3d93670de0b6b3a764000093610bd39392909216916341976e0991602480820192602092909190829003018186803b158015610efb57600080fd5b505afa158015610f0f573d6000803e3d6000fd5b505050506040513d6020811015610f2557600080fd5b5051610f318b8a613093565b9063ffffffff612ff116565b90506000610f62670de0b6b3a7640000610bd3600c5485612ff190919063ffffffff16565b90506000610f79610f72836117a3565b87876133d4565b600954604080516341976e0960e01b81526001600160a01b03808d1660048301529151939450611019938c936110149316916341976e09916024808301926020929190829003018186803b158015610fd057600080fd5b505afa158015610fe4573d6000803e3d6000fd5b505050506040513d6020811015610ffa57600080fd5b5051610bd385670de0b6b3a764000063ffffffff612ff116565b613412565b9998505050505050505050565b600a546001600160a01b03163314611073576040805162461bcd60e51b815260206004820152600b60248201526a21676f7665726e616e636560a81b604482015290519081900360640190fd5b670de0b6b3a7640000821080156110925750670dbd2fc137a300008210155b6110d1576040805162461bcd60e51b815260206004820152600b60248201526a496e76616c69642066656560a81b604482015290519081900360640190fd5b801561112c57670de0b6b3a764000081111561112c576040805162461bcd60e51b8152602060048201526015602482015274496e76616c6964207265736572766520726174696f60581b604482015290519081900360640190fd5b600c91909155600d55565b600d5481565b6008818154811061114a57fe5b6000918252602090912001546001600160a01b0316905081565b60025490565b6001600160a01b03851660009081526006602052604081205460ff1615156001146111c4576040805162461bcd60e51b815260206004820152600560248201526410b1b7b4b760d91b604482015290519081900360640190fd5b6001600160a01b03861660009081526007602052604090205460ff161561121a576040805162461bcd60e51b8152602060048201526005602482015264706175736560d81b604482015290519081900360640190fd5b6001600160a01b03851660009081526006602052604090205460ff161515600114611274576040805162461bcd60e51b815260206004820152600560248201526410b1b7b4b760d91b604482015290519081900360640190fd5b6001600160a01b03851660009081526007602052604090205460ff16156112ca576040805162461bcd60e51b8152602060048201526005602482015264706175736560d81b604482015290519081900360640190fd5b600954604080516341976e0960e01b81526001600160a01b038981166004830152915160009392909216916341976e0991602480820192602092909190829003018186803b15801561131b57600080fd5b505afa15801561132f573d6000803e3d6000fd5b505050506040513d602081101561134557600080fd5b505111611386576040805162461bcd60e51b815260206004820152600a6024820152697a65726f20707269636560b01b604482015290519081900360640190fd5b600954604080516341976e0960e01b81526001600160a01b038881166004830152915160009392909216916341976e0991602480820192602092909190829003018186803b1580156113d757600080fd5b505afa1580156113eb573d6000803e3d6000fd5b505050506040513d602081101561140157600080fd5b505111611442576040805162461bcd60e51b815260206004820152600a6024820152697a65726f20707269636560b01b604482015290519081900360640190fd5b81421115611481576040805162461bcd60e51b8152602060048201526007602482015266195e1c1a5c995960ca1b604482015290519081900360640190fd5b8261148b866129ac565b10156114de576040805162461bcd60e51b815260206004820152601d60248201527f696e73756666696369656e74206f7574707574206c6971756964697479000000604482015290519081900360640190fd5b6115018686856114f0610c9f8b6129ac565b6114fc610c9f8b6129ac565b611675565b905083811115611543576040805162461bcd60e51b8152602060048201526008602482015267736c69707061676560c01b604482015290519081900360640190fd5b846001600160a01b0316866001600160a01b0316336001600160a01b03167f908fb5ee8f16c6bc9bc3690973819f32a4d4b10188134543c88706e0e1d433788487604051808381526020018281526020019250505060405180910390a46115bb6001600160a01b03871633308463ffffffff61313a16565b6115d56001600160a01b038616338563ffffffff6134b116565b6115df8682613503565b95945050505050565b60006115f5848484613592565b61166b846116016132e4565b61166685604051806060016040528060288152602001614084602891396001600160a01b038a1660009081526001602052604081209061163f6132e4565b6001600160a01b03168152602081019190915260400160002054919063ffffffff6136ee16565b6132e8565b5060019392505050565b600954604080516341976e0960e01b81526001600160a01b0387811660048301529151600093849361171093670de0b6b3a764000093610bd39392909216916341976e0991602480820192602092909190829003018186803b1580156116da57600080fd5b505afa1580156116ee573d6000803e3d6000fd5b505050506040513d602081101561170457600080fd5b5051610f318a8a613093565b90506000611727611720836117a3565b8686613785565b9050600061174c600c54610bd3670de0b6b3a764000085612ff190919063ffffffff16565b600954604080516341976e0960e01b81526001600160a01b03808e1660048301529151939450611019938d936110149316916341976e09916024808301926020929190829003018186803b158015610fd057600080fd5b60008181811215610e90576040805162461bcd60e51b81526020600482015260086024820152676f766572666c6f7760c01b604482015290519081900360640190fd5b60055460ff1690565b6001600160a01b03851660009081526006602052604081205460ff161515600114611849576040805162461bcd60e51b815260206004820152600560248201526410b1b7b4b760d91b604482015290519081900360640190fd5b6001600160a01b03861660009081526007602052604090205460ff161561189f576040805162461bcd60e51b8152602060048201526005602482015264706175736560d81b604482015290519081900360640190fd5b6001600160a01b03851660009081526006602052604090205460ff1615156001146118f9576040805162461bcd60e51b815260206004820152600560248201526410b1b7b4b760d91b604482015290519081900360640190fd5b6001600160a01b03851660009081526007602052604090205460ff161561194f576040805162461bcd60e51b8152602060048201526005602482015264706175736560d81b604482015290519081900360640190fd5b600954604080516341976e0960e01b81526001600160a01b038981166004830152915160009392909216916341976e0991602480820192602092909190829003018186803b1580156119a057600080fd5b505afa1580156119b4573d6000803e3d6000fd5b505050506040513d60208110156119ca57600080fd5b505111611a0b576040805162461bcd60e51b815260206004820152600a6024820152697a65726f20707269636560b01b604482015290519081900360640190fd5b600954604080516341976e0960e01b81526001600160a01b038881166004830152915160009392909216916341976e0991602480820192602092909190829003018186803b158015611a5c57600080fd5b505afa158015611a70573d6000803e3d6000fd5b505050506040513d6020811015611a8657600080fd5b505111611ac7576040805162461bcd60e51b815260206004820152600a6024820152697a65726f20707269636560b01b604482015290519081900360640190fd5b81421115611b06576040805162461bcd60e51b8152602060048201526007602482015266195e1c1a5c995960ca1b604482015290519081900360640190fd5b611b24868686611b18610c9f8b6129ac565b610cb5610c9f8b6129ac565b905080611b30866129ac565b1015611b83576040805162461bcd60e51b815260206004820152601d60248201527f696e73756666696369656e74206f7574707574206c6971756964697479000000604482015290519081900360640190fd5b82811015611bc3576040805162461bcd60e51b8152602060048201526008602482015267736c69707061676560c01b604482015290519081900360640190fd5b846001600160a01b0316866001600160a01b0316336001600160a01b03167f908fb5ee8f16c6bc9bc3690973819f32a4d4b10188134543c88706e0e1d433788785604051808381526020018281526020019250505060405180910390a4611c3b6001600160a01b03871633308763ffffffff61313a16565b611c556001600160a01b038616338363ffffffff6134b116565b6115df8685613503565b600a546001600160a01b03163314611cac576040805162461bcd60e51b815260206004820152600b60248201526a21676f7665726e616e636560a81b604482015290519081900360640190fd5b600980546001600160a01b0319166001600160a01b0392909216919091179055565b6000610e8c611cdb6132e4565b846116668560016000611cec6132e4565b6001600160a01b03908116825260208083019390935260409182016000908120918c16815292529020549063ffffffff61328a16565b600a546001600160a01b03163314611d6f576040805162461bcd60e51b815260206004820152600b60248201526a21676f7665726e616e636560a81b604482015290519081900360640190fd5b6001600160a01b038116611dc1576040805162461bcd60e51b81526020600482015260146024820152731a5b9d985b1a59081c995cd95c9d99481c1bdbdb60621b604482015290519081900360640190fd5b600b80546001600160a01b0319166001600160a01b0392909216919091179055565b600a546001600160a01b031681565b600081421115611e33576040805162461bcd60e51b8152602060048201526007602482015266195e1c1a5c995960ca1b604482015290519081900360640190fd5b6001600160a01b03851660009081526006602052604090205460ff161515600114611e8d576040805162461bcd60e51b815260206004820152600560248201526410b1b7b4b760d91b604482015290519081900360640190fd5b60008311611ed0576040805162461bcd60e51b815260206004820152600b60248201526a1e995c9bc81bdd5d1c1d5d60aa1b604482015290519081900360640190fd5b600954604080516341976e0960e01b815230600482015290516000926001600160a01b0316916341976e09916024808301926020929190829003018186803b158015611f1b57600080fd5b505afa158015611f2f573d6000803e3d6000fd5b505050506040513d6020811015611f4557600080fd5b505111611f86576040805162461bcd60e51b815260206004820152600a6024820152697a65726f20707269636560b01b604482015290519081900360640190fd5b600954604080516341976e0960e01b81526001600160a01b038881166004830152915160009392909216916341976e0991602480820192602092909190829003018186803b158015611fd757600080fd5b505afa158015611feb573d6000803e3d6000fd5b505050506040513d602081101561200157600080fd5b505111612042576040805162461bcd60e51b815260206004820152600a6024820152697a65726f20707269636560b01b604482015290519081900360640190fd5b6120593086856114f0610c9f600f54610bd3611164565b90508381111561209b576040805162461bcd60e51b8152602060048201526008602482015267736c69707061676560c01b604482015290519081900360640190fd5b6040805184815290516001600160a01b0387169133917fe74c91552b64c2e2e7bd255639e004e693bd3e1d01cc33e65610b86afcc1ffed9181900360200190a36120e533826137b9565b6120ff6001600160a01b038616338563ffffffff6134b116565b612108856129ac565b610dd4576001600160a01b0385166000908152601060205260409020805460ff19169055600f54610dd090600163ffffffff6138b516565b6001600160a01b031660009081526020819052604090205490565b60076020526000908152604090205460ff1681565b60066020526000908152604090205460ff1681565b600a546001600160a01b031633146121d2576040805162461bcd60e51b815260206004820152600b60248201526a21676f7665726e616e636560a81b604482015290519081900360640190fd5b6001600160a01b03811660009081526006602052604090205460ff1615612233576040805162461bcd60e51b815260206004820152601060248201526f105b1c9958591e48185c1c1c9bdd995960821b604482015290519081900360640190fd5b6001600160a01b03166000818152600660205260408120805460ff191660019081179091556008805491820181559091527ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee30180546001600160a01b0319169091179055565b60048054604080516020601f6002600019610100600188161502019095169490940493840181900481028201810190925282815260609390929091830182828015610e6e5780601f10610e4357610100808354040283529160200191610e6e565b600080805b60085481101561234d576123436123366008838154811061231c57fe5b6000918252602090912001546001600160a01b03166129ac565b839063ffffffff61328a16565b91506001016122ff565b50905090565b6000610e8c6123606132e4565b846116668560405180606001604052806025815260200161418b602591396001600061238a6132e4565b6001600160a01b03908116825260208083019390935260409182016000908120918d1681529252902054919063ffffffff6136ee16565b60606008805480602002602001604051908101604052809291908181526020018280548015610e6e57602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116123fb575050505050905090565b6000610e8c61242f6132e4565b8484613592565b6009546001600160a01b031681565b600a546001600160a01b03163314612492576040805162461bcd60e51b815260206004820152600b60248201526a21676f7665726e616e636560a81b604482015290519081900360640190fd5b600a80546001600160a01b0319166001600160a01b0392909216919091179055565b600a546001600160a01b03163314612501576040805162461bcd60e51b815260206004820152600b60248201526a21676f7665726e616e636560a81b604482015290519081900360640190fd5b6001600160a01b03919091166000908152600760205260409020805460ff1916911515919091179055565b6001600160a01b03841660009081526006602052604081205460ff161515600114612586576040805162461bcd60e51b815260206004820152600560248201526410b1b7b4b760d91b604482015290519081900360640190fd5b6001600160a01b03851660009081526007602052604090205460ff16156125dc576040805162461bcd60e51b8152602060048201526005602482015264706175736560d81b604482015290519081900360640190fd5b8142111561261b576040805162461bcd60e51b8152602060048201526007602482015266195e1c1a5c995960ca1b604482015290519081900360640190fd5b6000831161265e576040805162461bcd60e51b815260206004820152600b60248201526a1e995c9bc81bdd5d1c1d5d60aa1b604482015290519081900360640190fd5b600954604080516341976e0960e01b81526001600160a01b038881166004830152915160009392909216916341976e0991602480820192602092909190829003018186803b1580156126af57600080fd5b505afa1580156126c3573d6000803e3d6000fd5b505050506040513d60208110156126d957600080fd5b50511161271a576040805162461bcd60e51b815260206004820152600a6024820152697a65726f20707269636560b01b604482015290519081900360640190fd5b600954604080516341976e0960e01b815230600482015290516000926001600160a01b0316916341976e09916024808301926020929190829003018186803b15801561276557600080fd5b505afa158015612779573d6000803e3d6000fd5b505050506040513d602081101561278f57600080fd5b5051116127d0576040805162461bcd60e51b815260206004820152600a6024820152697a65726f20707269636560b01b604482015290519081900360640190fd5b6127d8611164565b6128b057600954604080516341976e0960e01b81526001600160a01b038089166004830152915160009361287a938a936110149391909216916341976e09916024808301926020929190829003018186803b15801561283657600080fd5b505afa15801561284a573d6000803e3d6000fd5b505050506040513d602081101561286057600080fd5b5051610bd388670de0b6b3a764000063ffffffff612ff116565b600c549091506128a89061289c83670de0b6b3a764000063ffffffff612ff116565b9063ffffffff6138f716565b9150506128d6565b6128d38530856128c2610c9f8a6129ac565b6114fc610c9f600f54610bd3611164565b90505b83811115612916576040805162461bcd60e51b8152602060048201526008602482015267736c69707061676560c01b604482015290519081900360640190fd5b6040805184815290516001600160a01b0387169133917f63982df10efd8dfaaaa0fcc7f50b2d93b7cba26ccc48adee2873220d485dc39a9181900360200190a36129716001600160a01b03861633308463ffffffff61313a16565b610d62338461319a565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b600c5481565b604080516370a0823160e01b81523060048201529051600091839183916001600160a01b038416916370a0823191602480820192602092909190829003018186803b1580156129fa57600080fd5b505afa158015612a0e573d6000803e3d6000fd5b505050506040513d6020811015612a2457600080fd5b5051600954604080516341976e0960e01b81526001600160a01b0386811660048301529151939450600093612ac393670de0b6b3a764000093610bd3939116916341976e0991602480820192602092909190829003018186803b158015612a8a57600080fd5b505afa158015612a9e573d6000803e3d6000fd5b505050506040513d6020811015612ab457600080fd5b5051859063ffffffff612ff116565b90506115df8582613093565b600a546001600160a01b03163314612b1c576040805162461bcd60e51b815260206004820152600b60248201526a21676f7665726e616e636560a81b604482015290519081900360640190fd5b6001600160a01b03821660009081526010602052604090205460ff1615612b82576040805162461bcd60e51b815260206004820152601560248201527463616e2774207365697a65206c697175696469747960581b604482015290519081900360640190fd5b604080516370a0823160e01b815230600482015290516000916001600160a01b038516916370a0823191602480820192602092909190829003018186803b158015612bcc57600080fd5b505afa158015612be0573d6000803e3d6000fd5b505050506040513d6020811015612bf657600080fd5b5051905080821115612c0757600080fd5b600b54612c27906001600160a01b0385811691168463ffffffff6134b116565b505050565b670de0b6b3a764000081565b600a546001600160a01b03163314612c85576040805162461bcd60e51b815260206004820152600b60248201526a21676f7665726e616e636560a81b604482015290519081900360640190fd5b600081118015612c9d5750670de0b6b3a76400008111155b612cda576040805162461bcd60e51b8152602060048201526009602482015268496e76616c6964204160b81b604482015290519081900360640190fd5b600e55565b600081421115612d20576040805162461bcd60e51b8152602060048201526007602482015266195e1c1a5c995960ca1b604482015290519081900360640190fd5b6001600160a01b03851660009081526006602052604090205460ff161515600114612d7a576040805162461bcd60e51b815260206004820152600560248201526410b1b7b4b760d91b604482015290519081900360640190fd5b60008411612dbc576040805162461bcd60e51b815260206004820152600a6024820152691e995c9bc81a5b9c1d5d60b21b604482015290519081900360640190fd5b600954604080516341976e0960e01b815230600482015290516000926001600160a01b0316916341976e09916024808301926020929190829003018186803b158015612e0757600080fd5b505afa158015612e1b573d6000803e3d6000fd5b505050506040513d6020811015612e3157600080fd5b505111612e72576040805162461bcd60e51b815260206004820152600a6024820152697a65726f20707269636560b01b604482015290519081900360640190fd5b600954604080516341976e0960e01b81526001600160a01b038881166004830152915160009392909216916341976e0991602480820192602092909190829003018186803b158015612ec357600080fd5b505afa158015612ed7573d6000803e3d6000fd5b505050506040513d6020811015612eed57600080fd5b505111612f2e576040805162461bcd60e51b815260206004820152600a6024820152697a65726f20707269636560b01b604482015290519081900360640190fd5b612f45308686611b18610c9f600f54610bd3611164565b905082811015612f87576040805162461bcd60e51b8152602060048201526008602482015267736c69707061676560c01b604482015290519081900360640190fd5b6040805182815290516001600160a01b0387169133917fe74c91552b64c2e2e7bd255639e004e693bd3e1d01cc33e65610b86afcc1ffed9181900360200190a3612fd133856137b9565b6120ff6001600160a01b038616338363ffffffff6134b116565b600e5481565b60008261300057506000610e90565b8282028284828161300d57fe5b041461304a5760405162461bcd60e51b81526004018080602001828103825260218152602001806140636021913960400191505060405180910390fd5b9392505050565b600061304a83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061392c565b600080836001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156130cf57600080fd5b505afa1580156130e3573d6000803e3d6000fd5b505050506040513d60208110156130f957600080fd5b505160ff16905060128114156131125782915050610e90565b613132600a82900a610bd385670de0b6b3a764000063ffffffff612ff116565b915050610e90565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b179052613194908590613991565b50505050565b6001600160a01b0382166131f5576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015290519081900360640190fd5b600254613208908263ffffffff61328a16565b6002556001600160a01b038216600090815260208190526040902054613234908263ffffffff61328a16565b6001600160a01b0383166000818152602081815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b60008282018381101561304a576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b3390565b6001600160a01b03831661332d5760405162461bcd60e51b81526004018080602001828103825260248152602001806141196024913960400191505060405180910390fd5b6001600160a01b0382166133725760405162461bcd60e51b8152600401808060200182810382526022815260200180613fd96022913960400191505060405180910390fd5b6001600160a01b03808416600081815260016020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6000806133e7848663ffffffff613b4916565b905060006133f6828686613bae565b9050613408848263ffffffff613d5316565b9695505050505050565b600080836001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b15801561344e57600080fd5b505afa158015613462573d6000803e3d6000fd5b505050506040513d602081101561347857600080fd5b505160ff16905060128114156134915782915050610e90565b613132670de0b6b3a7640000610bd385600a85900a63ffffffff612ff116565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052612c27908490613991565b600d541561358e576000613546670de0b6b3a7640000610bd3613539600c54670de0b6b3a76400006138b590919063ffffffff16565b859063ffffffff612ff116565b9050600061356b670de0b6b3a7640000610bd3600d5485612ff190919063ffffffff16565b600b54909150613194906001600160a01b0386811691168363ffffffff6134b116565b5050565b6001600160a01b0383166135d75760405162461bcd60e51b81526004018080602001828103825260258152602001806140f46025913960400191505060405180910390fd5b6001600160a01b03821661361c5760405162461bcd60e51b8152600401808060200182810382526023815260200180613f946023913960400191505060405180910390fd5b61365f81604051806060016040528060268152602001613ffb602691396001600160a01b038616600090815260208190526040902054919063ffffffff6136ee16565b6001600160a01b038085166000908152602081905260408082209390935590841681522054613694908263ffffffff61328a16565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b6000818484111561377d5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561374257818101518382015260200161372a565b50505050905090810190601f16801561376f5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b600080613798838663ffffffff613d5316565b905060006137a7828587613bae565b9050613408818663ffffffff613d5316565b6001600160a01b0382166137fe5760405162461bcd60e51b81526004018080602001828103825260218152602001806140d36021913960400191505060405180910390fd5b61384181604051806060016040528060228152602001613fb7602291396001600160a01b038516600090815260208190526040902054919063ffffffff6136ee16565b6001600160a01b03831660009081526020819052604090205560025461386d908263ffffffff6138b516565b6002556040805182815290516000916001600160a01b038516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050565b600061304a83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506136ee565b600080821161390557600080fd5b600082848161391057fe5b04905082848161391c57fe5b061561304a576001019392505050565b6000818361397b5760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561374257818101518382015260200161372a565b50600083858161398757fe5b0495945050505050565b6139a3826001600160a01b0316613db8565b6139f4576040805162461bcd60e51b815260206004820152601f60248201527f5361666545524332303a2063616c6c20746f206e6f6e2d636f6e747261637400604482015290519081900360640190fd5b60006060836001600160a01b0316836040518082805190602001908083835b60208310613a325780518252601f199092019160209182019101613a13565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613a94576040519150601f19603f3d011682016040523d82523d6000602084013e613a99565b606091505b509150915081613af0576040805162461bcd60e51b815260206004820181905260248201527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564604482015290519081900360640190fd5b80511561319457808060200190516020811015613b0c57600080fd5b50516131945760405162461bcd60e51b815260040180806020018281038252602a815260200180614161602a913960400191505060405180910390fd5b6000828201818312801590613b5e5750838112155b80613b735750600083128015613b7357508381125b61304a5760405162461bcd60e51b81526004018080602001828103825260218152602001806140216021913960400191505060405180910390fd5b600080600080613bf1613be4670de0b6b3a7640000613bd8600e5489613def90919063ffffffff16565b9063ffffffff613e9816565b879063ffffffff613b4916565b90506000613c19613be4670de0b6b3a7640000613bd8600e548b613def90919063ffffffff16565b9050613c2b828263ffffffff613def16565b9350613c6d613c51600e54613bd8670de0b6b3a764000088613def90919063ffffffff16565b613c618a8063ffffffff613def16565b9063ffffffff613d5316565b925050506000613ca9613c9a600e546ec097ce7bc90715b34b9f1000000000613e9890919063ffffffff16565b600e549063ffffffff613b4916565b90506000613cc9670de0b6b3a7640000613bd88a8563ffffffff613def16565b90506000613cf1613ce185600463ffffffff613def16565b613c61848063ffffffff613def16565b90506000811215613d31576040805162461bcd60e51b8152602060048201526005602482015264085c9bdbdd60da1b604482015290519081900360640190fd5b6110196002613bd8613d4284613f50565b60008690039063ffffffff613b4916565b6000818303818312801590613d685750838113155b80613d7d5750600083128015613d7d57508381135b61304a5760405162461bcd60e51b815260040180806020018281038252602481526020018061413d6024913960400191505060405180910390fd5b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a4708115801590610dd45750141592915050565b600082613dfe57506000610e90565b82600019148015613e125750600160ff1b82145b15613e4e5760405162461bcd60e51b81526004018080602001828103825260278152602001806140ac6027913960400191505060405180910390fd5b82820282848281613e5b57fe5b051461304a5760405162461bcd60e51b81526004018080602001828103825260278152602001806140ac6027913960400191505060405180910390fd5b600081613eec576040805162461bcd60e51b815260206004820181905260248201527f5369676e6564536166654d6174683a206469766973696f6e206279207a65726f604482015290519081900360640190fd5b81600019148015613f005750600160ff1b83145b15613f3c5760405162461bcd60e51b81526004018080602001828103825260218152602001806140426021913960400191505060405180910390fd5b6000828481613f4757fe5b05949350505050565b600080613f61600284056001613b49565b9050825b8082121561304a5750806002613f84828681613f7d57fe5b0584613b49565b81613f8b57fe5b059150613f6556fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a206275726e20616d6f756e7420657863656564732062616c616e636545524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e63655369676e6564536166654d6174683a206164646974696f6e206f766572666c6f775369676e6564536166654d6174683a206469766973696f6e206f766572666c6f77536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f7745524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e63655369676e6564536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f7745524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f20616464726573735369676e6564536166654d6174683a207375627472616374696f6e206f766572666c6f775361666545524332303a204552433230206f7065726174696f6e20646964206e6f74207375636365656445524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa265627a7a723158200b517a6ad6885e0943b08683a627ab15321ff06ac5dc05efbd6ad576bf43730a64736f6c63430005110032
{"success": true, "error": null, "results": {"detectors": [{"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "controlled-array-length", "impact": "High", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'controlled-array-length', 'impact': 'High', 'confidence': 'Medium'}]}
86
0x1d09790777e666899f0850ba84ab01cdbbf0df5e
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 netCORE 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 netCORE( 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]; } }
0x6060604052600436106100af576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100b4578063095ea7b31461014257806318160ddd1461019c57806323b872dd146101c557806327e235e31461023e578063313ce5671461028b5780635c658165146102ba57806370a082311461032657806395d89b4114610373578063a9059cbb14610401578063dd62ed3e1461045b575b600080fd5b34156100bf57600080fd5b6100c76104c7565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101075780820151818401526020810190506100ec565b50505050905090810190601f1680156101345780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561014d57600080fd5b610182600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610565565b604051808215151515815260200191505060405180910390f35b34156101a757600080fd5b6101af610657565b6040518082815260200191505060405180910390f35b34156101d057600080fd5b610224600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061065d565b604051808215151515815260200191505060405180910390f35b341561024957600080fd5b610275600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108f7565b6040518082815260200191505060405180910390f35b341561029657600080fd5b61029e61090f565b604051808260ff1660ff16815260200191505060405180910390f35b34156102c557600080fd5b610310600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610922565b6040518082815260200191505060405180910390f35b341561033157600080fd5b61035d600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610947565b6040518082815260200191505060405180910390f35b341561037e57600080fd5b610386610990565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156103c65780820151818401526020810190506103ab565b50505050905090810190601f1680156103f35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561040c57600080fd5b610441600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610a2e565b604051808215151515815260200191505060405180910390f35b341561046657600080fd5b6104b1600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610b87565b6040518082815260200191505060405180910390f35b60038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561055d5780601f106105325761010080835404028352916020019161055d565b820191906000526020600020905b81548152906001019060200180831161054057829003601f168201915b505050505081565b600081600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b60005481565b600080600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015801561072e5750828110155b151561073957600080fd5b82600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8110156108865782600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055505b8373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a360019150509392505050565b60016020528060005260406000206000915090505481565b600460009054906101000a900460ff1681565b6002602052816000526040600020602052806000526040600020600091509150505481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60058054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610a265780601f106109fb57610100808354040283529160200191610a26565b820191906000526020600020905b815481529060010190602001808311610a0957829003601f168201915b505050505081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410151515610a7e57600080fd5b81600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050929150505600a165627a7a72305820f2c673e9b4cedc388cff4a7c0ce68c46153fb8fc847ea3cf171eec9b7df5919e0029
{"success": true, "error": null, "results": {}}
true
null
{}
87
0x1D17d697cAAffE53bf3bFdE761c90D61F6ebdc41
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 StakedToken { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } interface RewardToken { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } 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 Staking is Ownable { struct User { uint256 depositAmount; uint256 paidReward; } using SafeMath for uint256; mapping (address => User) public users; uint256 public rewardTillNowPerToken = 0; uint256 public lastUpdatedBlock; uint256 public rewardPerBlock; uint256 public scale = 1e18; uint256 public particleCollector = 0; uint256 public daoShare; uint256 public earlyFoundersShare; address public daoWallet; address public earlyFoundersWallet; // init with 1 instead of 0 to avoid division by zero uint256 public totalStakedToken = 1; StakedToken public stakedToken; RewardToken public rewardToken; event Deposit(address user, uint256 amount); event Withdraw(address user, uint256 amount); event EmergencyWithdraw(address user, uint256 amount); event RewardClaimed(address user, uint256 amount); event RewardPerBlockChanged(uint256 oldValue, uint256 newValue); constructor (address _stakedToken, address _rewardToken, uint256 _rewardPerBlock, uint256 _daoShare, uint256 _earlyFoundersShare) public { stakedToken = StakedToken(_stakedToken); rewardToken = RewardToken(_rewardToken); rewardPerBlock = _rewardPerBlock; daoShare = _daoShare; earlyFoundersShare = _earlyFoundersShare; lastUpdatedBlock = block.number; daoWallet = msg.sender; earlyFoundersWallet = msg.sender; } function setWallets(address _daoWallet, address _earlyFoundersWallet) public onlyOwner { daoWallet = _daoWallet; earlyFoundersWallet = _earlyFoundersWallet; } function setShares(uint256 _daoShare, uint256 _earlyFoundersShare) public onlyOwner { withdrawParticleCollector(); daoShare = _daoShare; earlyFoundersShare = _earlyFoundersShare; } function setRewardPerBlock(uint256 _rewardPerBlock) public onlyOwner { update(); emit RewardPerBlockChanged(rewardPerBlock, _rewardPerBlock); rewardPerBlock = _rewardPerBlock; } // Update reward variables of the pool to be up-to-date. function update() public { if (block.number <= lastUpdatedBlock) { return; } uint256 rewardAmount = (block.number - lastUpdatedBlock).mul(rewardPerBlock); rewardTillNowPerToken = rewardTillNowPerToken.add(rewardAmount.mul(scale).div(totalStakedToken)); lastUpdatedBlock = block.number; } // View function to see pending reward on frontend. function pendingReward(address _user) external view returns (uint256) { User storage user = users[_user]; uint256 accRewardPerToken = rewardTillNowPerToken; if (block.number > lastUpdatedBlock) { uint256 rewardAmount = (block.number - lastUpdatedBlock).mul(rewardPerBlock); accRewardPerToken = accRewardPerToken.add(rewardAmount.mul(scale).div(totalStakedToken)); } return user.depositAmount.mul(accRewardPerToken).div(scale).sub(user.paidReward); } function deposit(uint256 amount) public { User storage user = users[msg.sender]; update(); if (user.depositAmount > 0) { uint256 _pendingReward = user.depositAmount.mul(rewardTillNowPerToken).div(scale).sub(user.paidReward); rewardToken.transfer(msg.sender, _pendingReward); emit RewardClaimed(msg.sender, _pendingReward); } user.depositAmount = user.depositAmount.add(amount); user.paidReward = user.depositAmount.mul(rewardTillNowPerToken).div(scale); stakedToken.transferFrom(address(msg.sender), address(this), amount); totalStakedToken = totalStakedToken.add(amount); emit Deposit(msg.sender, amount); } function withdraw(uint256 amount) public { User storage user = users[msg.sender]; require(user.depositAmount >= amount, "withdraw amount exceeds deposited amount"); update(); uint256 _pendingReward = user.depositAmount.mul(rewardTillNowPerToken).div(scale).sub(user.paidReward); rewardToken.transfer(msg.sender, _pendingReward); emit RewardClaimed(msg.sender, _pendingReward); uint256 particleCollectorShare = _pendingReward.mul(daoShare.add(earlyFoundersShare)).div(scale); particleCollector = particleCollector.add(particleCollectorShare); if (amount > 0) { user.depositAmount = user.depositAmount.sub(amount); stakedToken.transfer(address(msg.sender), amount); totalStakedToken = totalStakedToken.sub(amount); emit Withdraw(msg.sender, amount); } user.paidReward = user.depositAmount.mul(rewardTillNowPerToken).div(scale); } function withdrawParticleCollector() public { uint256 _daoShare = particleCollector.mul(daoShare).div(daoShare.add(earlyFoundersShare)); rewardToken.transfer(daoWallet, _daoShare); uint256 _earlyFoundersShare = particleCollector.mul(earlyFoundersShare).div(daoShare.add(earlyFoundersShare)); rewardToken.transfer(earlyFoundersWallet, _earlyFoundersShare); particleCollector = 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() public { User storage user = users[msg.sender]; totalStakedToken = totalStakedToken.sub(user.depositAmount); stakedToken.transfer(msg.sender, user.depositAmount); emit EmergencyWithdraw(msg.sender, user.depositAmount); user.depositAmount = 0; user.paidReward = 0; } // Add temporary withdrawal functionality for owner(DAO) to transfer all tokens to a safe place. // Contract ownership will transfer to address(0x) after full auditing of codes. function withdrawAllRewardTokens(address to) public onlyOwner { uint256 totalRewardTokens = rewardToken.balanceOf(address(this)); rewardToken.transfer(to, totalRewardTokens); } // Add temporary withdrawal functionality for owner(DAO) to transfer all tokens to a safe place. // Contract ownership will transfer to address(0x) after full auditing of codes. function withdrawAllStakedtokens(address to) public onlyOwner { uint256 _totalStakedTokens = stakedToken.balanceOf(address(this)); stakedToken.transfer(to, _totalStakedTokens); } }
0x608060405234801561001057600080fd5b50600436106101a95760003560e01c8063a2e62045116100f9578063d3f6a15711610097578063f40f0f5211610071578063f40f0f52146105ab578063f51e181a14610603578063f7c618c114610621578063f90ce5ba14610655576101a9565b8063d3f6a157146104f9578063db2e21bc1461055d578063f2fde38b14610567576101a9565b8063bb872b4a116100d3578063bb872b4a14610435578063cb6d8ee614610463578063cc7a262e14610481578063cee66f63146104b5576101a9565b8063a2e620451461039e578063a87430ba146103a8578063b6b55f2514610407576101a9565b8063715018a6116101665780638ae39cac116101405780638ae39cac146103245780638da5cb5b146103425780639378c6d414610376578063995d9b6014610380576101a9565b8063715018a6146102b857806372d21c89146102c257806388d19f1b14610306576101a9565b8063079a5705146101ae5780632aca3e7d146101e25780632e1a7d4d1461021a578063481af4aa1461024857806360c6cdac14610266578063698a589714610284575b600080fd5b6101b6610673565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b610218600480360360408110156101f857600080fd5b810190808035906020019092919080359060200190929190505050610699565b005b6102466004803603602081101561023057600080fd5b810190808035906020019092919050505061077b565b005b610250610b8d565b6040518082815260200191505060405180910390f35b61026e610b93565b6040518082815260200191505060405180910390f35b61028c610b99565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6102c0610bbf565b005b610304600480360360208110156102d857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610d45565b005b61030e610fa8565b6040518082815260200191505060405180910390f35b61032c610fae565b6040518082815260200191505060405180910390f35b61034a610fb4565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61037e610fdd565b005b610388611251565b6040518082815260200191505060405180910390f35b6103a6611257565b005b6103ea600480360360208110156103be57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506112d0565b604051808381526020018281526020019250505060405180910390f35b6104336004803603602081101561041d57600080fd5b81019080803590602001909291905050506112f4565b005b6104616004803603602081101561044b57600080fd5b810190808035906020019092919050505061166e565b005b61046b611789565b6040518082815260200191505060405180910390f35b61048961178f565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6104f7600480360360208110156104cb57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506117b5565b005b61055b6004803603604081101561050f57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611a18565b005b610565611b66565b005b6105a96004803603602081101561057d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611d0b565b005b6105ed600480360360208110156105c157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611f16565b6040518082815260200191505060405180910390f35b61060b612011565b6040518082815260200191505060405180910390f35b610629612017565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61065d61203d565b6040518082815260200191505060405180910390f35b600a60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6106a1612043565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610761576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b610769610fdd565b81600781905550806008819055505050565b6000600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000209050818160000154101561081b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260288152602001806123746028913960400191505060405180910390fd5b610823611257565b6000610868826001015461085a60055461084c600254876000015461204b90919063ffffffff16565b6120d190919063ffffffff16565b61211b90919063ffffffff16565b9050600d60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb33836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b1580156108fd57600080fd5b505af1158015610911573d6000803e3d6000fd5b505050506040513d602081101561092757600080fd5b8101908080519060200190929190505050507f106f923f993c2149d49b4255ff723acafa1f2d94393f561d3eda32ae348f72413382604051808373ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a160006109cd6005546109bf6109b060085460075461216590919063ffffffff16565b8561204b90919063ffffffff16565b6120d190919063ffffffff16565b90506109e48160065461216590919063ffffffff16565b6006819055506000841115610b5257610a0a84846000015461211b90919063ffffffff16565b8360000181905550600c60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb33866040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b158015610aa557600080fd5b505af1158015610ab9573d6000803e3d6000fd5b505050506040513d6020811015610acf57600080fd5b810190808051906020019092919050505050610af684600b5461211b90919063ffffffff16565b600b819055507f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a94243643385604051808373ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a15b610b7f600554610b71600254866000015461204b90919063ffffffff16565b6120d190919063ffffffff16565b836001018190555050505050565b60085481565b60025481565b600960009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b610bc7612043565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610c87576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a360008060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550565b610d4d612043565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610e0d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b6000600d60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b158015610e9857600080fd5b505afa158015610eac573d6000803e3d6000fd5b505050506040513d6020811015610ec257600080fd5b81019080805190602001909291905050509050600d60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb83836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b158015610f6857600080fd5b505af1158015610f7c573d6000803e3d6000fd5b505050506040513d6020811015610f9257600080fd5b8101908080519060200190929190505050505050565b60075481565b60045481565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b600061101e610ff960085460075461216590919063ffffffff16565b61101060075460065461204b90919063ffffffff16565b6120d190919063ffffffff16565b9050600d60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb600960009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b1580156110d557600080fd5b505af11580156110e9573d6000803e3d6000fd5b505050506040513d60208110156110ff57600080fd5b810190808051906020019092919050505050600061115261112d60085460075461216590919063ffffffff16565b61114460085460065461204b90919063ffffffff16565b6120d190919063ffffffff16565b9050600d60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb600a60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b15801561120957600080fd5b505af115801561121d573d6000803e3d6000fd5b505050506040513d602081101561123357600080fd5b81019080805190602001909291905050505060006006819055505050565b60065481565b6003544311611265576112ce565b6000611280600454600354430361204b90919063ffffffff16565b90506112bf6112ae600b546112a06005548561204b90919063ffffffff16565b6120d190919063ffffffff16565b60025461216590919063ffffffff16565b60028190555043600381905550505b565b60016020528060005260406000206000915090508060000154908060010154905082565b6000600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020905061133f611257565b6000816000015411156114b95760006113918260010154611383600554611375600254876000015461204b90919063ffffffff16565b6120d190919063ffffffff16565b61211b90919063ffffffff16565b9050600d60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb33836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b15801561142657600080fd5b505af115801561143a573d6000803e3d6000fd5b505050506040513d602081101561145057600080fd5b8101908080519060200190929190505050507f106f923f993c2149d49b4255ff723acafa1f2d94393f561d3eda32ae348f72413382604051808373ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a1505b6114d082826000015461216590919063ffffffff16565b81600001819055506115056005546114f7600254846000015461204b90919063ffffffff16565b6120d190919063ffffffff16565b8160010181905550600c60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166323b872dd3330856040518463ffffffff1660e01b8152600401808473ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019350505050602060405180830381600087803b1580156115be57600080fd5b505af11580156115d2573d6000803e3d6000fd5b505050506040513d60208110156115e857600080fd5b81019080805190602001909291905050505061160f82600b5461216590919063ffffffff16565b600b819055507fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c3383604051808373ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a15050565b611676612043565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614611736576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b61173e611257565b7f79a5349732f93288abbb68e251c3dfc325bf3ee6fde7786d919155d39733e0f560045482604051808381526020018281526020019250505060405180910390a18060048190555050565b600b5481565b600c60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6117bd612043565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161461187d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b6000600c60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561190857600080fd5b505afa15801561191c573d6000803e3d6000fd5b505050506040513d602081101561193257600080fd5b81019080805190602001909291905050509050600c60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb83836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b1580156119d857600080fd5b505af11580156119ec573d6000803e3d6000fd5b505050506040513d6020811015611a0257600080fd5b8101908080519060200190929190505050505050565b611a20612043565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614611ae0576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b81600960006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555080600a60006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505050565b6000600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000209050611bc28160000154600b5461211b90919063ffffffff16565b600b81905550600c60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb3383600001546040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b158015611c5f57600080fd5b505af1158015611c73573d6000803e3d6000fd5b505050506040513d6020811015611c8957600080fd5b8101908080519060200190929190505050507f5fafa99d0643513820be26656b45130b01e1c03062e1266bf36f88cbd3bd9695338260000154604051808373ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a1600081600001819055506000816001018190555050565b611d13612043565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614611dd3576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161415611e59576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602681526020018061239c6026913960400191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a3806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600080600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020905060006002549050600354431115611fc7576000611f86600454600354430361204b90919063ffffffff16565b9050611fc3611fb4600b54611fa66005548561204b90919063ffffffff16565b6120d190919063ffffffff16565b8361216590919063ffffffff16565b9150505b6120088260010154611ffa600554611fec85876000015461204b90919063ffffffff16565b6120d190919063ffffffff16565b61211b90919063ffffffff16565b92505050919050565b60055481565b600d60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60035481565b600033905090565b60008083141561205e57600090506120cb565b600082840290508284828161206f57fe5b04146120c6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260218152602001806123c26021913960400191505060405180910390fd5b809150505b92915050565b600061211383836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f0000000000008152506121ed565b905092915050565b600061215d83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506122b3565b905092915050565b6000808284019050838110156121e3576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b60008083118290612299576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561225e578082015181840152602081019050612243565b50505050905090810190601f16801561228b5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385816122a557fe5b049050809150509392505050565b6000838311158290612360576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561232557808201518184015260208101905061230a565b50505050905090810190601f1680156123525780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b506000838503905080915050939250505056fe776974686472617720616d6f756e742065786365656473206465706f736974656420616d6f756e744f776e61626c653a206e6577206f776e657220697320746865207a65726f2061646472657373536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a26469706673582212206607ea760dc1d067371b1e69f86cd8c9ccef855eed569218d24af7a310376d3764736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}]}
88
0x1d2879789aded8e995494ca53f17a6051dcaac1f
pragma solidity 0.4.26; pragma experimental ABIEncoderV2; contract TokenSale { uint256 fee = 0.01 ether; uint256 symbolNameIndex; uint256 historyIndex; //it will divide on 1000 uint256 siteShareRatio = 1; address manager; enum State {Waiting , Selling , Ended , Checkedout} mapping (uint256 => uint) tokenBalanceForAddress; mapping (address => uint256) refAccount; mapping (address => mapping(uint256 => uint)) balanceEthForAddress; mapping (uint256 => Token) tokens; struct Token { address tokenContract; address owner; string symbolName; string symbol; string link; uint256 amount; uint256 leftover; uint256 priceInWie; uint256 deadline; uint decimals; State state; uint256 referral; } mapping (uint256 => History) histories; mapping (uint256 => uint256) saleCount; struct History{ address owner; string title; uint256 amount; uint256 decimals; uint256 time; string symbol; } function TokenSale() public{ manager = msg.sender; } /////////////////////// // TOKEN MANAGEMENT // ////////////////////// function addToken(address erc20TokenAddress , string symbolName , string symbol , string link , uint256 priceInWie , uint decimals , uint256 referral , uint256 _amount) public payable { require(!hasToken(erc20TokenAddress) , 'Token Is Already Added'); require(msg.value == fee , 'Add Token Fee Is Invalid'); require(referral >= 0 && referral <= 100); manager.transfer(msg.value); uint256 index = getSymbolIndexByAddress(erc20TokenAddress); uint256 _arrayIndex = 0; if(index != 0 && (!checkDeadLine(tokens[index]) || tokens[index].leftover == 0)){ require(tokens[index].state == State.Checkedout); require(tokens[index].owner == msg.sender); _arrayIndex = index; } else{ symbolNameIndex++; _arrayIndex = symbolNameIndex; } tokens[_arrayIndex].symbolName = symbolName; tokens[_arrayIndex].tokenContract = erc20TokenAddress; tokens[_arrayIndex].symbol = symbol; tokens[_arrayIndex].link = link; tokens[_arrayIndex].amount = _amount; tokens[_arrayIndex].deadline = now; tokens[_arrayIndex].leftover = 0; tokens[_arrayIndex].state = State.Waiting; tokens[_arrayIndex].priceInWie = priceInWie; tokens[_arrayIndex].decimals = decimals; tokens[_arrayIndex].referral = referral; tokens[_arrayIndex].owner = msg.sender; setHistory(msg.sender , fee , 'Fee For Add Token' , 'ETH' , 18); setHistory(manager , fee , '(Manager) Fee For Add Token' , 'ETH' , 18); } function hasToken(address erc20TokenAddress) public constant returns (bool) { uint256 index = getSymbolIndexByAddress(erc20TokenAddress); if (index == 0) { return false; } else if(!checkDeadLine(tokens[index]) || tokens[index].leftover == 0){ return false; } else return true; } function getSymbolIndexByAddress(address erc20TokenAddress) internal returns (uint256) { for (uint256 i = 1; i <= symbolNameIndex; i++) { if (tokens[i].tokenContract == erc20TokenAddress) { return i; } } return 0; } function getSymbolIndexByAddressOrThrow(address erc20TokenAddress) returns (uint256) { uint256 index = getSymbolIndexByAddress(erc20TokenAddress); require(index > 0); return index; } function getAllDex() public view returns(address[] memory , string[] memory , uint256[] memory , uint[] memory , uint256[] memory , string[] memory){ address[] memory tokenAdderss = new address[](symbolNameIndex+1); string[] memory tokenName = new string[](symbolNameIndex+1); string[] memory tokenLink = new string[](symbolNameIndex+1); uint256[] memory tokenPrice = new uint256[](symbolNameIndex+1); uint[] memory decimal = new uint256[](symbolNameIndex+1); uint256[] memory leftover = new uint256[](symbolNameIndex+1); for (uint256 i = 0; i <= symbolNameIndex; i++) { if(checkDeadLine(tokens[i]) && tokens[i].leftover != 0){ tokenAdderss[i] = tokens[i].tokenContract; tokenName[i] = tokens[i].symbol; tokenLink[i] = tokens[i].link; tokenPrice[i] = tokens[i].priceInWie; decimal[i] = tokens[i].decimals; leftover[i] = tokens[i].leftover; } } return (tokenAdderss , tokenName , tokenPrice , decimal , leftover , tokenLink); } function getInitTokenInfo(address erc20TokenAddress) public returns(uint256 , uint256 , uint ){ uint256 _symbolNameIndex = getSymbolIndexByAddressOrThrow(erc20TokenAddress); Token token = tokens[_symbolNameIndex]; return (token.amount , token.priceInWie , token.decimals); } //////////////////////////////// // DEPOSIT / WITHDRAWAL TOKEN // //////////////////////////////// function depositToken(address erc20TokenAddress, uint256 amountTokens , uint256 deadline) public payable { uint256 _symbolNameIndex = getSymbolIndexByAddressOrThrow(erc20TokenAddress); require(tokens[_symbolNameIndex].tokenContract != address(0) , 'Token is Invalid'); require(tokens[_symbolNameIndex].state == State.Waiting , 'Token Cannot be deposited'); require(tokens[_symbolNameIndex].owner == msg.sender , 'You are not owner of this coin'); ERC20Interface token = ERC20Interface(tokens[_symbolNameIndex].tokenContract); require(token.transferFrom(msg.sender, address(this), amountTokens) == true); tokens[_symbolNameIndex].amount = amountTokens; tokens[_symbolNameIndex].leftover = amountTokens; require(tokenBalanceForAddress[_symbolNameIndex] + amountTokens >= tokenBalanceForAddress[_symbolNameIndex]); tokenBalanceForAddress[_symbolNameIndex] += amountTokens; tokens[_symbolNameIndex].state = State.Selling; tokens[_symbolNameIndex].deadline = deadline; Token tokenRes = tokens[_symbolNameIndex]; setHistory(msg.sender , amountTokens , 'Deposit Token' , tokenRes.symbol , tokenRes.decimals); } function checkoutDex(address erc20TokenAddress) public payable { uint256 symbolNameIndex = getSymbolIndexByAddressOrThrow(erc20TokenAddress); ERC20Interface token = ERC20Interface(tokens[symbolNameIndex].tokenContract); uint256 _amountTokens = tokens[symbolNameIndex].leftover; require(tokens[symbolNameIndex].tokenContract != address(0), 'Token is Invalid'); require(tokens[symbolNameIndex].owner == msg.sender , 'You are not owner of this coin'); require(!checkDeadLine(tokens[symbolNameIndex]) || tokens[symbolNameIndex].leftover == 0 , 'Token Cannot be withdrawn'); require(tokenBalanceForAddress[symbolNameIndex] - _amountTokens >= 0 , "overflow error"); // require(tokenBalanceForAddress[symbolNameIndex] - _amountTokens <= tokenBalanceForAddress[symbolNameIndex] , "Insufficient amount of token"); tokenBalanceForAddress[symbolNameIndex] -= _amountTokens; tokens[symbolNameIndex].leftover = 0; tokens[symbolNameIndex].state = State.Checkedout; if(_amountTokens > 0){ require(token.transfer(msg.sender, _amountTokens) == true , "transfer failed"); setHistory(msg.sender , _amountTokens , 'Check Out Token' , tokens[symbolNameIndex].symbol , tokens[symbolNameIndex].decimals); } uint256 _siteShare = balanceEthForAddress[msg.sender][symbolNameIndex] * siteShareRatio / 1000; uint256 _ownerShare = balanceEthForAddress[msg.sender][symbolNameIndex] - _siteShare; setHistory(msg.sender , _ownerShare , 'Check Out ETH' , 'ETH' , 18 ); setHistory(manager , _siteShare , '(Manager) Site Share For Deposite Token' , 'ETH' , 18); msg.sender.transfer(_ownerShare); manager.transfer(_siteShare); balanceEthForAddress[msg.sender][symbolNameIndex] = 0; } function getBalance(address erc20TokenAddress) public constant returns (uint256) { uint256 _symbolNameIndex = getSymbolIndexByAddressOrThrow(erc20TokenAddress); return tokenBalanceForAddress[_symbolNameIndex]; } function checkoutRef(uint256 amount) public payable { require(refAccount[msg.sender] >= amount , 'Insufficient amount of ETH'); refAccount[msg.sender] -= amount; setHistory(msg.sender , amount , 'Check Out Referral' , 'ETH' , 18 ); msg.sender.transfer(amount); } function getRefBalance(address _ownerAddress) view returns(uint256){ return refAccount[_ownerAddress]; } /////////////// // Buy Token // /////////////// function buyToken(address erc20TokenAddress , address refAddress , uint256 _amount) payable returns(bool){ uint256 _symbolNameIndex = getSymbolIndexByAddressOrThrow(erc20TokenAddress); Token token = tokens[_symbolNameIndex]; require(token.state == State.Selling , 'You Can not Buy This Token'); require((_amount * token.priceInWie) / (10 ** token.decimals) == msg.value , "Incorrect Eth Amount"); require(checkDeadLine(token) , 'Deadline Passed'); require(token.leftover >= _amount , 'Insufficient Token Amount'); if(erc20TokenAddress != refAddress){ uint256 ref = msg.value * token.referral / 100; balanceEthForAddress[token.owner][_symbolNameIndex] += msg.value - ref; refAccount[refAddress] += ref; }else{ balanceEthForAddress[token.owner][_symbolNameIndex] += msg.value; } ERC20Interface ERC20token = ERC20Interface(tokens[_symbolNameIndex].tokenContract); ERC20token.approve(address(this) , _amount); require(ERC20token.transferFrom(address(this) , msg.sender , _amount) == true , 'Insufficient Token Amount'); setHistory(msg.sender , _amount , 'Buy Token' , token.symbol , token.decimals); token.leftover -= _amount; tokenBalanceForAddress[_symbolNameIndex] -= _amount; if(token.leftover == 0){ token.state = State.Ended; } saleCount[convertTime(now)] = saleCount[convertTime(now)] + msg.value; return true; } function leftover(address erc20TokenAddress , uint256 _amount) public view returns(uint256){ uint256 _symbolNameIndex = getSymbolIndexByAddressOrThrow(erc20TokenAddress); return tokens[_symbolNameIndex].leftover; } function checkDeadLine(Token token) internal returns(bool){ return (now < token.deadline); } function getOwnerTokens(address owner) public view returns(address[] memory , string[] memory , uint256[] memory , uint256[] memory , uint256[] memory , uint256[] memory , uint[] memory ){ address[] memory tokenAdderss = new address[](symbolNameIndex+1); string[] memory tokenName = new string[](symbolNameIndex+1); uint256[] memory tokenAmount = new uint256[](symbolNameIndex+1); uint256[] memory tokenLeftover = new uint256[](symbolNameIndex+1); uint256[] memory tokenPrice = new uint256[](symbolNameIndex+1); uint256[] memory tokenDeadline = new uint256[](symbolNameIndex+1); uint[] memory status = new uint[](symbolNameIndex+1); for (uint256 i = 0; i <= symbolNameIndex; i++) { if (tokens[i].owner == owner) { tokenAdderss[i] = tokens[i].tokenContract; tokenName[i] = tokens[i].symbol; tokenAmount[i] = tokens[i].amount; tokenLeftover[i] = tokens[i].leftover; tokenPrice[i] = tokens[i].priceInWie; tokenDeadline[i] = tokens[i].deadline; if(tokens[i].state == State.Waiting) status[i] = 1; else{ if(tokens[i].state == State.Selling) status[i] = 2; if(!checkDeadLine(tokens[i]) || tokens[i].leftover == 0) status[i] = 3; if(tokens[i].state == State.Checkedout) status[i] = 4; } } } return (tokenAdderss , tokenName , tokenLeftover , tokenAmount , tokenPrice , tokenDeadline , status); } function getDecimal(address erc20TokenAddress) public view returns(uint256){ uint256 _symbolNameIndex = getSymbolIndexByAddressOrThrow(erc20TokenAddress); return tokens[_symbolNameIndex].decimals; } function getOwnerTokenDetails(address erc20TokenAddress) public view returns(Token){ uint256 _symbolNameIndex = getSymbolIndexByAddressOrThrow(erc20TokenAddress); Token token = tokens[_symbolNameIndex]; require(token.owner == msg.sender); return token; } function setHistory(address _owner , uint256 _amount , string _name , string _symbol , uint256 _decimals) public { histories[historyIndex].amount = _amount; histories[historyIndex].title = _name; histories[historyIndex].owner = _owner; histories[historyIndex].symbol = _symbol; histories[historyIndex].time = now; histories[historyIndex].decimals = _decimals; historyIndex++; } function getHistory(address _owner) public view returns(string[] , string[] , uint256[] , uint256[] , uint256[]){ string[] memory title = new string[](historyIndex+1); string[] memory symbol = new string[](historyIndex+1); uint256[] memory time = new uint256[](historyIndex+1); uint256[] memory amount = new uint256[](historyIndex+1); uint256[] memory decimals = new uint256[](historyIndex+1); for (uint256 i = 0; i <= historyIndex; i++) { if (histories[i].owner == _owner) { title[i] = histories[i].title; symbol[i] = histories[i].symbol; time[i] = histories[i].time; amount[i] = histories[i].amount; decimals[i] = histories[i].decimals; } } return (title , symbol , time , amount , decimals); } /////////////////// // Passed Token // ///////////////// function getAllPassedDex() public view returns(address[] memory , string[] memory , uint256[] memory , uint[] memory , uint256[] memory , string[] memory){ address[] memory tokenAdderss = new address[](symbolNameIndex+1); string[] memory tokenName = new string[](symbolNameIndex+1); string[] memory tokenLink = new string[](symbolNameIndex+1); uint256[] memory tokenPrice = new uint256[](symbolNameIndex+1); uint[] memory decimal = new uint256[](symbolNameIndex+1); uint256[] memory leftover = new uint256[](symbolNameIndex+1); for (uint256 i = 0; i <= symbolNameIndex; i++) { if(!(checkDeadLine(tokens[i]) && tokens[i].leftover != 0)){ tokenAdderss[i] = tokens[i].tokenContract; tokenName[i] = tokens[i].symbol; tokenLink[i] = tokens[i].link; tokenPrice[i] = tokens[i].priceInWie; decimal[i] = tokens[i].decimals; leftover[i] = tokens[i].leftover; } } return (tokenAdderss , tokenName , tokenPrice , decimal , leftover , tokenLink); } function convertTime(uint256 time) internal returns(uint256){ return (time - 1603584000) / 86400; } function getChart() public view returns(uint256[]){ uint256[] memory tokenVal = new uint256[](convertTime(now) + 1); for(uint i = 0 ; i <= convertTime(now); i++){ tokenVal[i] = saleCount[i]; } return tokenVal; } } contract ERC20Interface { // Get the total token supply function totalSupply() public constant returns (uint256); // Get the account balance of another account with address _owner function balanceOf(address _owner) public constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. // this function is required for some DEX functionality function approve(address _spender, uint256 _value) public returns (bool success); // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) public constant returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
0x608060405260043610610107576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680632bdfb7151461010c57806331682c431461013c578063499b3e1e146101795780634a36cb65146101b857806354f76483146101d457806380396811146101f057806387232c9914610231578063966da2b81461024d57806399c6d2de1461028a5780639bb0f599146102a65780639f278959146102e3578063c1d5725f14610320578063c255fb1714610350578063d272fce61461038d578063d63d4af0146103bd578063ed5050ab14610400578063f04fdfa41461043d578063f2b1ea6b14610468578063f8b2cb4f14610491575b600080fd5b34801561011857600080fd5b506101216104ce565b604051610133969594939291906159ce565b60405180910390f35b34801561014857600080fd5b50610163600480360361015e9190810190615105565b610c69565b6040516101709190615d4c565b60405180910390f35b34801561018557600080fd5b506101a0600480360361019b9190810190615105565b611004565b6040516101af93929190615d89565b60405180910390f35b6101d260048036036101cd91908101906153d2565b61104a565b005b6101ee60048036036101e99190810190615105565b6111dd565b005b3480156101fc57600080fd5b5061021760048036036102129190810190615105565b611ce7565b604051610228959493929190615af9565b60405180910390f35b61024b6004803603610246919081019061517d565b6120e8565b005b34801561025957600080fd5b50610274600480360361026f9190810190615105565b612967565b6040516102819190615d6e565b60405180910390f35b6102a4600480360361029f919081019061535a565b612994565b005b3480156102b257600080fd5b506102cd60048036036102c89190810190615105565b612e46565b6040516102da9190615b91565b60405180910390f35b3480156102ef57600080fd5b5061030a60048036036103059190810190615277565b6131c4565b6040516103179190615d6e565b60405180910390f35b61033a6004803603610335919081019061512e565b6131f2565b6040516103479190615b91565b60405180910390f35b34801561035c57600080fd5b5061037760048036036103729190810190615105565b613b8b565b6040516103849190615d6e565b60405180910390f35b34801561039957600080fd5b506103a2613bd4565b6040516103b4969594939291906159ce565b60405180910390f35b3480156103c957600080fd5b506103e460048036036103df9190810190615105565b61436e565b6040516103f79796959493929190615a59565b60405180910390f35b34801561040c57600080fd5b5061042760048036036104229190810190615105565b614c5b565b6040516104349190615d6e565b60405180910390f35b34801561044957600080fd5b50610452614c81565b60405161045f9190615b6f565b60405180910390f35b34801561047457600080fd5b5061048f600480360361048a91908101906152b3565b614d1e565b005b34801561049d57600080fd5b506104b860048036036104b39190810190615105565b614e3f565b6040516104c59190615d6e565b60405180910390f35b606080606080606080606080606080606080600060018054016040519080825280602002602001820160405280156105155781602001602082028038833980820191505090505b509650600180540160405190808252806020026020018201604052801561055057816020015b606081526020019060019003908161053b5790505b509550600180540160405190808252806020026020018201604052801561058b57816020015b60608152602001906001900390816105765790505b50945060018054016040519080825280602002602001820160405280156105c15781602001602082028038833980820191505090505b50935060018054016040519080825280602002602001820160405280156105f75781602001602082028038833980820191505090505b509250600180540160405190808252806020026020018201604052801561062d5781602001602082028038833980820191505090505b509150600090505b60015481111515610c48576109636008600083815260200190815260200160002061018060405190810160405290816000820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020016001820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001600282018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156107a85780601f1061077d576101008083540402835291602001916107a8565b820191906000526020600020905b81548152906001019060200180831161078b57829003601f168201915b50505050508152602001600382018054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561084a5780601f1061081f5761010080835404028352916020019161084a565b820191906000526020600020905b81548152906001019060200180831161082d57829003601f168201915b50505050508152602001600482018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108ec5780601f106108c1576101008083540402835291602001916108ec565b820191906000526020600020905b8154815290600101906020018083116108cf57829003601f168201915b505050505081526020016005820154815260200160068201548152602001600782015481526020016008820154815260200160098201548152602001600a820160009054906101000a900460ff16600381111561094557fe5b600381111561095057fe5b8152602001600b82015481525050614e69565b801561098657506000600860008381526020019081526020016000206006015414155b1515610c3b576008600082815260200190815260200160002060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1687828151811015156109d157fe5b9060200190602002019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff1681525050600860008281526020019081526020016000206003018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610ab75780601f10610a8c57610100808354040283529160200191610ab7565b820191906000526020600020905b815481529060010190602001808311610a9a57829003601f168201915b50505050508682815181101515610aca57fe5b90602001906020020181905250600860008281526020019081526020016000206004018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610b815780601f10610b5657610100808354040283529160200191610b81565b820191906000526020600020905b815481529060010190602001808311610b6457829003601f168201915b50505050508582815181101515610b9457fe5b9060200190602002018190525060086000828152602001908152602001600020600701548482815181101515610bc657fe5b906020019060200201818152505060086000828152602001908152602001600020600901548382815181101515610bf957fe5b906020019060200201818152505060086000828152602001908152602001600020600601548282815181101515610c2c57fe5b90602001906020020181815250505b8080600101915050610635565b8686858585899c509c509c509c509c509c5050505050505050909192939495565b610c71614f35565b600080610c7d84614c5b565b91506008600083815260200190815260200160002090503373ffffffffffffffffffffffffffffffffffffffff168160010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16141515610cf257600080fd5b8061018060405190810160405290816000820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020016001820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001600282018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610e455780601f10610e1a57610100808354040283529160200191610e45565b820191906000526020600020905b815481529060010190602001808311610e2857829003601f168201915b50505050508152602001600382018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610ee75780601f10610ebc57610100808354040283529160200191610ee7565b820191906000526020600020905b815481529060010190602001808311610eca57829003601f168201915b50505050508152602001600482018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610f895780601f10610f5e57610100808354040283529160200191610f89565b820191906000526020600020905b815481529060010190602001808311610f6c57829003601f168201915b505050505081526020016005820154815260200160068201548152602001600782015481526020016008820154815260200160098201548152602001600a820160009054906101000a900460ff166003811115610fe257fe5b6003811115610fed57fe5b8152602001600b8201548152505092505050919050565b600080600080600061101586614c5b565b915060086000838152602001908152602001600020905080600501548160070154826009015494509450945050509193909250565b80600660003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054101515156110ce576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016110c590615c8c565b60405180910390fd5b80600660003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555061119333826040805190810160405280601281526020017f436865636b204f757420526566657272616c00000000000000000000000000008152506040805190810160405280600381526020017f45544800000000000000000000000000000000000000000000000000000000008152506012614d1e565b3373ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f193505050501580156111d9573d6000803e3d6000fd5b5050565b60008060008060006111ee86614c5b565b94506008600086815260200190815260200160002060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16935060086000868152602001908152602001600020600601549250600073ffffffffffffffffffffffffffffffffffffffff166008600087815260200190815260200160002060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16141515156112ea576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016112e190615c6c565b60405180910390fd5b3373ffffffffffffffffffffffffffffffffffffffff166008600087815260200190815260200160002060010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16141515611390576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161138790615ccc565b60405180910390fd5b6116b36008600087815260200190815260200160002061018060405190810160405290816000820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020016001820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001600282018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156114f85780601f106114cd576101008083540402835291602001916114f8565b820191906000526020600020905b8154815290600101906020018083116114db57829003601f168201915b50505050508152602001600382018054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561159a5780601f1061156f5761010080835404028352916020019161159a565b820191906000526020600020905b81548152906001019060200180831161157d57829003601f168201915b50505050508152602001600482018054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561163c5780601f106116115761010080835404028352916020019161163c565b820191906000526020600020905b81548152906001019060200180831161161f57829003601f168201915b505050505081526020016005820154815260200160068201548152602001600782015481526020016008820154815260200160098201548152602001600a820160009054906101000a900460ff16600381111561169557fe5b60038111156116a057fe5b8152602001600b82015481525050614e69565b15806116d5575060006008600087815260200190815260200160002060060154145b1515611716576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161170d90615cec565b60405180910390fd5b60008360056000888152602001908152602001600020540310151515611771576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161176890615c2c565b60405180910390fd5b82600560008781526020019081526020016000206000828254039250508190555060006008600087815260200190815260200160002060060181905550600360086000878152602001908152602001600020600a0160006101000a81548160ff021916908360038111156117e157fe5b021790555060008311156119e757600115158473ffffffffffffffffffffffffffffffffffffffff1663a9059cbb33866040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040161184a9291906159a5565b602060405180830381600087803b15801561186457600080fd5b505af1158015611878573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061189c91908101906153a9565b15151415156118e0576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016118d790615d2c565b60405180910390fd5b6119e633846040805190810160405280600f81526020017f436865636b204f757420546f6b656e0000000000000000000000000000000000815250600860008a81526020019081526020016000206003018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156119c55780601f1061199a576101008083540402835291602001916119c5565b820191906000526020600020905b8154815290600101906020018083116119a857829003601f168201915b5050505050600860008b815260200190815260200160002060090154614d1e565b5b6103e8600354600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008881526020019081526020016000205402811515611a4857fe5b04915081600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600087815260200190815260200160002054039050611b1833826040805190810160405280600d81526020017f436865636b204f757420455448000000000000000000000000000000000000008152506040805190810160405280600381526020017f45544800000000000000000000000000000000000000000000000000000000008152506012614d1e565b611bd9600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1683606060405190810160405280602781526020017f284d616e6167657229205369746520536861726520466f72204465706f73697481526020017f6520546f6b656e000000000000000000000000000000000000000000000000008152506040805190810160405280600381526020017f45544800000000000000000000000000000000000000000000000000000000008152506012614d1e565b3373ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f19350505050158015611c1f573d6000803e3d6000fd5b50600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc839081150290604051600060405180830381858888f19350505050158015611c88573d6000803e3d6000fd5b506000600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600087815260200190815260200160002081905550505050505050565b6060806060806060806060806060806000600160025401604051908082528060200260200182016040528015611d3157816020015b6060815260200190600190039081611d1c5790505b509550600160025401604051908082528060200260200182016040528015611d6d57816020015b6060815260200190600190039081611d585790505b509450600160025401604051908082528060200260200182016040528015611da45781602001602082028038833980820191505090505b509350600160025401604051908082528060200260200182016040528015611ddb5781602001602082028038833980820191505090505b509250600160025401604051908082528060200260200182016040528015611e125781602001602082028038833980820191505090505b509150600090505b600254811115156120ca578b73ffffffffffffffffffffffffffffffffffffffff166009600083815260200190815260200160002060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614156120bd57600960008281526020019081526020016000206001018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015611f395780601f10611f0e57610100808354040283529160200191611f39565b820191906000526020600020905b815481529060010190602001808311611f1c57829003601f168201915b50505050508682815181101515611f4c57fe5b90602001906020020181905250600960008281526020019081526020016000206005018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156120035780601f10611fd857610100808354040283529160200191612003565b820191906000526020600020905b815481529060010190602001808311611fe657829003601f168201915b5050505050858281518110151561201657fe5b906020019060200201819052506009600082815260200190815260200160002060040154848281518110151561204857fe5b90602001906020020181815250506009600082815260200190815260200160002060020154838281518110151561207b57fe5b9060200190602002018181525050600960008281526020019081526020016000206003015482828151811015156120ae57fe5b90602001906020020181815250505b8080600101915050611e1a565b85858585859a509a509a509a509a5050505050505091939590929450565b6000806120f48a612e46565b151515612136576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161212d90615bcc565b60405180910390fd5b6000543414151561217c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161217390615cac565b60405180910390fd5b6000841015801561218e575060648411155b151561219957600080fd5b600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc349081150290604051600060405180830381858888f19350505050158015612201573d6000803e3d6000fd5b5061220b8a614e7a565b9150600090506000821415801561256357506125406008600084815260200190815260200160002061018060405190810160405290816000820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020016001820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001600282018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156123855780601f1061235a57610100808354040283529160200191612385565b820191906000526020600020905b81548152906001019060200180831161236857829003601f168201915b50505050508152602001600382018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156124275780601f106123fc57610100808354040283529160200191612427565b820191906000526020600020905b81548152906001019060200180831161240a57829003601f168201915b50505050508152602001600482018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156124c95780601f1061249e576101008083540402835291602001916124c9565b820191906000526020600020905b8154815290600101906020018083116124ac57829003601f168201915b505050505081526020016005820154815260200160068201548152602001600782015481526020016008820154815260200160098201548152602001600a820160009054906101000a900460ff16600381111561252257fe5b600381111561252d57fe5b8152602001600b82015481525050614e69565b1580612562575060006008600084815260200190815260200160002060060154145b5b156126275760038081111561257457fe5b60086000848152602001908152602001600020600a0160009054906101000a900460ff1660038111156125a357fe5b1415156125af57600080fd5b3373ffffffffffffffffffffffffffffffffffffffff166008600084815260200190815260200160002060010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614151561261f57600080fd5b81905061263f565b60016000815480929190600101919050555060015490505b88600860008381526020019081526020016000206002019080519060200190612669929190614fce565b50896008600083815260200190815260200160002060000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550876008600083815260200190815260200160002060030190805190602001906126e9929190614fce565b5086600860008381526020019081526020016000206004019080519060200190612714929190614fce565b5082600860008381526020019081526020016000206005018190555042600860008381526020019081526020016000206008018190555060006008600083815260200190815260200160002060060181905550600060086000838152602001908152602001600020600a0160006101000a81548160ff0219169083600381111561279a57fe5b02179055508560086000838152602001908152602001600020600701819055508460086000838152602001908152602001600020600901819055508360086000838152602001908152602001600020600b0181905550336008600083815260200190815260200160002060010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506128bf336000546040805190810160405280601181526020017f46656520466f722041646420546f6b656e0000000000000000000000000000008152506040805190810160405280600381526020017f45544800000000000000000000000000000000000000000000000000000000008152506012614d1e565b61295b600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166000546040805190810160405280601b81526020017f284d616e61676572292046656520466f722041646420546f6b656e00000000008152506040805190810160405280600381526020017f45544800000000000000000000000000000000000000000000000000000000008152506012614d1e565b50505050505050505050565b60008061297383614c5b565b90506008600082815260200190815260200160002060090154915050919050565b60008060006129a286614c5b565b9250600073ffffffffffffffffffffffffffffffffffffffff166008600085815260200190815260200160002060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614151515612a4c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401612a4390615c6c565b60405180910390fd5b60006003811115612a5957fe5b60086000858152602001908152602001600020600a0160009054906101000a900460ff166003811115612a8857fe5b141515612aca576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401612ac190615c0c565b60405180910390fd5b3373ffffffffffffffffffffffffffffffffffffffff166008600085815260200190815260200160002060010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16141515612b70576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401612b6790615ccc565b60405180910390fd5b6008600084815260200190815260200160002060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff169150600115158273ffffffffffffffffffffffffffffffffffffffff166323b872dd3330896040518463ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401612c069392919061596e565b602060405180830381600087803b158015612c2057600080fd5b505af1158015612c34573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250612c5891908101906153a9565b1515141515612c6657600080fd5b84600860008581526020019081526020016000206005018190555084600860008581526020019081526020016000206006018190555060056000848152602001908152602001600020548560056000868152602001908152602001600020540110151515612cd357600080fd5b846005600085815260200190815260200160002060008282540192505081905550600160086000858152602001908152602001600020600a0160006101000a81548160ff02191690836003811115612d2757fe5b0217905550836008600085815260200190815260200160002060080181905550600860008481526020019081526020016000209050612e3e33866040805190810160405280600d81526020017f4465706f73697420546f6b656e00000000000000000000000000000000000000815250846003018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015612e2f5780601f10612e0457610100808354040283529160200191612e2f565b820191906000526020600020905b815481529060010190602001808311612e1257829003601f168201915b50505050508560090154614d1e565b505050505050565b600080612e5283614e7a565b90506000811415612e6657600091506131be565b6131896008600083815260200190815260200160002061018060405190810160405290816000820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020016001820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001600282018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015612fce5780601f10612fa357610100808354040283529160200191612fce565b820191906000526020600020905b815481529060010190602001808311612fb157829003601f168201915b50505050508152602001600382018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156130705780601f1061304557610100808354040283529160200191613070565b820191906000526020600020905b81548152906001019060200180831161305357829003601f168201915b50505050508152602001600482018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156131125780601f106130e757610100808354040283529160200191613112565b820191906000526020600020905b8154815290600101906020018083116130f557829003601f168201915b505050505081526020016005820154815260200160068201548152602001600782015481526020016008820154815260200160098201548152602001600a820160009054906101000a900460ff16600381111561316b57fe5b600381111561317657fe5b8152602001600b82015481525050614e69565b15806131ab575060006008600083815260200190815260200160002060060154145b156131b957600091506131be565b600191505b50919050565b6000806131d084614c5b565b9050600860008281526020019081526020016000206006015491505092915050565b600080600080600061320388614c5b565b93506008600085815260200190815260200160002092506001600381111561322757fe5b83600a0160009054906101000a900460ff16600381111561324457fe5b141515613286576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161327d90615bec565b60405180910390fd5b348360090154600a0a8460070154880281151561329f57fe5b041415156132e2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016132d990615d0c565b60405180910390fd5b6135f38361018060405190810160405290816000820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020016001820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001600282018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156134385780601f1061340d57610100808354040283529160200191613438565b820191906000526020600020905b81548152906001019060200180831161341b57829003601f168201915b50505050508152602001600382018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156134da5780601f106134af576101008083540402835291602001916134da565b820191906000526020600020905b8154815290600101906020018083116134bd57829003601f168201915b50505050508152602001600482018054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561357c5780601f106135515761010080835404028352916020019161357c565b820191906000526020600020905b81548152906001019060200180831161355f57829003601f168201915b505050505081526020016005820154815260200160068201548152602001600782015481526020016008820154815260200160098201548152602001600a820160009054906101000a900460ff1660038111156135d557fe5b60038111156135e057fe5b8152602001600b82015481525050614e69565b1515613634576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161362b90615c4c565b60405180910390fd5b8583600601541015151561367d576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161367490615bac565b60405180910390fd5b8673ffffffffffffffffffffffffffffffffffffffff168873ffffffffffffffffffffffffffffffffffffffff1614151561379d57606483600b015434028115156136c457fe5b049150813403600760008560010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008681526020019081526020016000206000828254019250508190555081600660008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282540192505081905550613820565b34600760008560010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000868152602001908152602001600020600082825401925050819055505b6008600085815260200190815260200160002060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690508073ffffffffffffffffffffffffffffffffffffffff1663095ea7b330886040518363ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004016138b09291906159a5565b602060405180830381600087803b1580156138ca57600080fd5b505af11580156138de573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061390291908101906153a9565b50600115158173ffffffffffffffffffffffffffffffffffffffff166323b872dd30338a6040518463ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004016139609392919061596e565b602060405180830381600087803b15801561397a57600080fd5b505af115801561398e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506139b291908101906153a9565b15151415156139f6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016139ed90615bac565b60405180910390fd5b613ad833876040805190810160405280600981526020017f42757920546f6b656e0000000000000000000000000000000000000000000000815250866003018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015613ac95780601f10613a9e57610100808354040283529160200191613ac9565b820191906000526020600020905b815481529060010190602001808311613aac57829003601f168201915b50505050508760090154614d1e565b858360060160008282540392505081905550856005600086815260200190815260200160002060008282540392505081905550600083600601541415613b3f57600283600a0160006101000a81548160ff02191690836003811115613b3957fe5b02179055505b34600a6000613b4d42614f17565b81526020019081526020016000205401600a6000613b6a42614f17565b81526020019081526020016000208190555060019450505050509392505050565b6000600660008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60608060608060608060608060608060608060006001805401604051908082528060200260200182016040528015613c1b5781602001602082028038833980820191505090505b5096506001805401604051908082528060200260200182016040528015613c5657816020015b6060815260200190600190039081613c415790505b5095506001805401604051908082528060200260200182016040528015613c9157816020015b6060815260200190600190039081613c7c5790505b5094506001805401604051908082528060200260200182016040528015613cc75781602001602082028038833980820191505090505b5093506001805401604051908082528060200260200182016040528015613cfd5781602001602082028038833980820191505090505b5092506001805401604051908082528060200260200182016040528015613d335781602001602082028038833980820191505090505b509150600090505b6001548111151561434d576140696008600083815260200190815260200160002061018060405190810160405290816000820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020016001820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001600282018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015613eae5780601f10613e8357610100808354040283529160200191613eae565b820191906000526020600020905b815481529060010190602001808311613e9157829003601f168201915b50505050508152602001600382018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015613f505780601f10613f2557610100808354040283529160200191613f50565b820191906000526020600020905b815481529060010190602001808311613f3357829003601f168201915b50505050508152602001600482018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015613ff25780601f10613fc757610100808354040283529160200191613ff2565b820191906000526020600020905b815481529060010190602001808311613fd557829003601f168201915b505050505081526020016005820154815260200160068201548152602001600782015481526020016008820154815260200160098201548152602001600a820160009054906101000a900460ff16600381111561404b57fe5b600381111561405657fe5b8152602001600b82015481525050614e69565b801561408c57506000600860008381526020019081526020016000206006015414155b15614340576008600082815260200190815260200160002060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1687828151811015156140d657fe5b9060200190602002019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff1681525050600860008281526020019081526020016000206003018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156141bc5780601f10614191576101008083540402835291602001916141bc565b820191906000526020600020905b81548152906001019060200180831161419f57829003601f168201915b505050505086828151811015156141cf57fe5b90602001906020020181905250600860008281526020019081526020016000206004018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156142865780601f1061425b57610100808354040283529160200191614286565b820191906000526020600020905b81548152906001019060200180831161426957829003601f168201915b5050505050858281518110151561429957fe5b90602001906020020181905250600860008281526020019081526020016000206007015484828151811015156142cb57fe5b9060200190602002018181525050600860008281526020019081526020016000206009015483828151811015156142fe57fe5b90602001906020020181815250506008600082815260200190815260200160002060060154828281518110151561433157fe5b90602001906020020181815250505b8080600101915050613d3b565b8686858585899c509c509c509c509c509c5050505050505050909192939495565b606080606080606080606080606080606080606080600060018054016040519080825280602002602001820160405280156143b85781602001602082028038833980820191505090505b50975060018054016040519080825280602002602001820160405280156143f357816020015b60608152602001906001900390816143de5790505b50965060018054016040519080825280602002602001820160405280156144295781602001602082028038833980820191505090505b509550600180540160405190808252806020026020018201604052801561445f5781602001602082028038833980820191505090505b50945060018054016040519080825280602002602001820160405280156144955781602001602082028038833980820191505090505b50935060018054016040519080825280602002602001820160405280156144cb5781602001602082028038833980820191505090505b50925060018054016040519080825280602002602001820160405280156145015781602001602082028038833980820191505090505b509150600090505b60015481111515614c33578f73ffffffffffffffffffffffffffffffffffffffff166008600083815260200190815260200160002060010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161415614c26576008600082815260200190815260200160002060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1688828151811015156145c357fe5b9060200190602002019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff1681525050600860008281526020019081526020016000206003018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156146a95780601f1061467e576101008083540402835291602001916146a9565b820191906000526020600020905b81548152906001019060200180831161468c57829003601f168201915b505050505087828151811015156146bc57fe5b90602001906020020181905250600860008281526020019081526020016000206005015486828151811015156146ee57fe5b90602001906020020181815250506008600082815260200190815260200160002060060154858281518110151561472157fe5b90602001906020020181815250506008600082815260200190815260200160002060070154848281518110151561475457fe5b90602001906020020181815250506008600082815260200190815260200160002060080154838281518110151561478757fe5b9060200190602002018181525050600060038111156147a257fe5b60086000838152602001908152602001600020600a0160009054906101000a900460ff1660038111156147d157fe5b14156147fa57600182828151811015156147e757fe5b9060200190602002018181525050614c25565b6001600381111561480757fe5b60086000838152602001908152602001600020600a0160009054906101000a900460ff16600381111561483657fe5b141561485b576002828281518110151561484c57fe5b90602001906020020181815250505b614b7e6008600083815260200190815260200160002061018060405190810160405290816000820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020016001820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001600282018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156149c35780601f10614998576101008083540402835291602001916149c3565b820191906000526020600020905b8154815290600101906020018083116149a657829003601f168201915b50505050508152602001600382018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015614a655780601f10614a3a57610100808354040283529160200191614a65565b820191906000526020600020905b815481529060010190602001808311614a4857829003601f168201915b50505050508152602001600482018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015614b075780601f10614adc57610100808354040283529160200191614b07565b820191906000526020600020905b815481529060010190602001808311614aea57829003601f168201915b505050505081526020016005820154815260200160068201548152602001600782015481526020016008820154815260200160098201548152602001600a820160009054906101000a900460ff166003811115614b6057fe5b6003811115614b6b57fe5b8152602001600b82015481525050614e69565b1580614ba0575060006008600083815260200190815260200160002060060154145b15614bc45760038282815181101515614bb557fe5b90602001906020020181815250505b600380811115614bd057fe5b60086000838152602001908152602001600020600a0160009054906101000a900460ff166003811115614bff57fe5b1415614c245760048282815181101515614c1557fe5b90602001906020020181815250505b5b5b8080600101915050614509565b878786888787879e509e509e509e509e509e509e505050505050505050919395979092949650565b600080614c6783614e7a565b9050600081111515614c7857600080fd5b80915050919050565b60608060006001614c9142614f17565b01604051908082528060200260200182016040528015614cc05781602001602082028038833980820191505090505b509150600090505b614cd142614f17565b81111515614d1657600a6000828152602001908152602001600020548282815181101515614cfb57fe5b90602001906020020181815250508080600101915050614cc8565b819250505090565b8360096000600254815260200190815260200160002060020181905550826009600060025481526020019081526020016000206001019080519060200190614d67929190614fce565b508460096000600254815260200190815260200160002060000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550816009600060025481526020019081526020016000206005019080519060200190614deb929190614fce565b50426009600060025481526020019081526020016000206004018190555080600960006002548152602001908152602001600020600301819055506002600081548092919060010191905055505050505050565b600080614e4b83614c5b565b90506005600082815260200190815260200160002054915050919050565b600081610100015142109050919050565b600080600190505b60015481111515614f0c578273ffffffffffffffffffffffffffffffffffffffff166008600083815260200190815260200160002060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161415614eff57809150614f11565b8080600101915050614e82565b600091505b50919050565b600062015180635f94c0008303811515614f2d57fe5b049050919050565b61018060405190810160405280600073ffffffffffffffffffffffffffffffffffffffff168152602001600073ffffffffffffffffffffffffffffffffffffffff168152602001606081526020016060815260200160608152602001600081526020016000815260200160008152602001600081526020016000815260200160006003811115614fc157fe5b8152602001600081525090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061500f57805160ff191683800117855561503d565b8280016001018555821561503d579182015b8281111561503c578251825591602001919060010190615021565b5b50905061504a919061504e565b5090565b61507091905b8082111561506c576000816000905550600101615054565b5090565b90565b600061507f8235615edf565b905092915050565b60006150938251615eff565b905092915050565b600082601f83011215156150ae57600080fd5b81356150c16150bc82615ded565b615dc0565b915080825260208301602083018583830111156150dd57600080fd5b6150e8838284615f27565b50505092915050565b60006150fd8235615f0b565b905092915050565b60006020828403121561511757600080fd5b600061512584828501615073565b91505092915050565b60008060006060848603121561514357600080fd5b600061515186828701615073565b935050602061516286828701615073565b9250506040615173868287016150f1565b9150509250925092565b600080600080600080600080610100898b03121561519a57600080fd5b60006151a88b828c01615073565b985050602089013567ffffffffffffffff8111156151c557600080fd5b6151d18b828c0161509b565b975050604089013567ffffffffffffffff8111156151ee57600080fd5b6151fa8b828c0161509b565b965050606089013567ffffffffffffffff81111561521757600080fd5b6152238b828c0161509b565b95505060806152348b828c016150f1565b94505060a06152458b828c016150f1565b93505060c06152568b828c016150f1565b92505060e06152678b828c016150f1565b9150509295985092959890939650565b6000806040838503121561528a57600080fd5b600061529885828601615073565b92505060206152a9858286016150f1565b9150509250929050565b600080600080600060a086880312156152cb57600080fd5b60006152d988828901615073565b95505060206152ea888289016150f1565b945050604086013567ffffffffffffffff81111561530757600080fd5b6153138882890161509b565b935050606086013567ffffffffffffffff81111561533057600080fd5b61533c8882890161509b565b925050608061534d888289016150f1565b9150509295509295909350565b60008060006060848603121561536f57600080fd5b600061537d86828701615073565b935050602061538e868287016150f1565b925050604061539f868287016150f1565b9150509250925092565b6000602082840312156153bb57600080fd5b60006153c984828501615087565b91505092915050565b6000602082840312156153e457600080fd5b60006153f2848285016150f1565b91505092915050565b61540481615e93565b82525050565b600061541582615e40565b80845260208401935061542783615e19565b60005b828110156154595761543d8683516153fb565b61544682615e6c565b915060208601955060018101905061542a565b50849250505092915050565b600061547082615e4b565b8084526020840193508360208202850161548985615e26565b60005b848110156154c25783830388526154a483835161554c565b92506154af82615e79565b915060208801975060018101905061548c565b508196508694505050505092915050565b60006154de82615e56565b8084526020840193506154f083615e33565b60005b828110156155225761550686835161595f565b61550f82615e86565b91506020860195506001810190506154f3565b50849250505092915050565b61553781615eb3565b82525050565b61554681615f15565b82525050565b600061555782615e61565b80845261556b816020860160208601615f36565b61557481615f69565b602085010191505092915050565b6000601982527f496e73756666696369656e7420546f6b656e20416d6f756e74000000000000006020830152604082019050919050565b6000601682527f546f6b656e20497320416c7265616479204164646564000000000000000000006020830152604082019050919050565b6000601a82527f596f752043616e206e6f7420427579205468697320546f6b656e0000000000006020830152604082019050919050565b6000601982527f546f6b656e2043616e6e6f74206265206465706f7369746564000000000000006020830152604082019050919050565b6000600e82527f6f766572666c6f77206572726f720000000000000000000000000000000000006020830152604082019050919050565b6000600f82527f446561646c696e652050617373656400000000000000000000000000000000006020830152604082019050919050565b6000601082527f546f6b656e20697320496e76616c6964000000000000000000000000000000006020830152604082019050919050565b6000601a82527f496e73756666696369656e7420616d6f756e74206f66204554480000000000006020830152604082019050919050565b6000601882527f41646420546f6b656e2046656520497320496e76616c696400000000000000006020830152604082019050919050565b6000601e82527f596f7520617265206e6f74206f776e6572206f66207468697320636f696e00006020830152604082019050919050565b6000601982527f546f6b656e2043616e6e6f742062652077697468647261776e000000000000006020830152604082019050919050565b6000601482527f496e636f72726563742045746820416d6f756e740000000000000000000000006020830152604082019050919050565b6000600f82527f7472616e73666572206661696c656400000000000000000000000000000000006020830152604082019050919050565b60006101808301600083015161586660008601826153fb565b50602083015161587960208601826153fb565b5060408301518482036040860152615891828261554c565b915050606083015184820360608601526158ab828261554c565b915050608083015184820360808601526158c5828261554c565b91505060a08301516158da60a086018261595f565b5060c08301516158ed60c086018261595f565b5060e083015161590060e086018261595f565b5061010083015161591561010086018261595f565b5061012083015161592a61012086018261595f565b5061014083015161593f61014086018261553d565b5061016083015161595461016086018261595f565b508091505092915050565b61596881615ed5565b82525050565b600060608201905061598360008301866153fb565b61599060208301856153fb565b61599d604083018461595f565b949350505050565b60006040820190506159ba60008301856153fb565b6159c7602083018461595f565b9392505050565b600060c08201905081810360008301526159e8818961540a565b905081810360208301526159fc8188615465565b90508181036040830152615a1081876154d3565b90508181036060830152615a2481866154d3565b90508181036080830152615a3881856154d3565b905081810360a0830152615a4c8184615465565b9050979650505050505050565b600060e0820190508181036000830152615a73818a61540a565b90508181036020830152615a878189615465565b90508181036040830152615a9b81886154d3565b90508181036060830152615aaf81876154d3565b90508181036080830152615ac381866154d3565b905081810360a0830152615ad781856154d3565b905081810360c0830152615aeb81846154d3565b905098975050505050505050565b600060a0820190508181036000830152615b138188615465565b90508181036020830152615b278187615465565b90508181036040830152615b3b81866154d3565b90508181036060830152615b4f81856154d3565b90508181036080830152615b6381846154d3565b90509695505050505050565b60006020820190508181036000830152615b8981846154d3565b905092915050565b6000602082019050615ba6600083018461552e565b92915050565b60006020820190508181036000830152615bc581615582565b9050919050565b60006020820190508181036000830152615be5816155b9565b9050919050565b60006020820190508181036000830152615c05816155f0565b9050919050565b60006020820190508181036000830152615c2581615627565b9050919050565b60006020820190508181036000830152615c458161565e565b9050919050565b60006020820190508181036000830152615c6581615695565b9050919050565b60006020820190508181036000830152615c85816156cc565b9050919050565b60006020820190508181036000830152615ca581615703565b9050919050565b60006020820190508181036000830152615cc58161573a565b9050919050565b60006020820190508181036000830152615ce581615771565b9050919050565b60006020820190508181036000830152615d05816157a8565b9050919050565b60006020820190508181036000830152615d25816157df565b9050919050565b60006020820190508181036000830152615d4581615816565b9050919050565b60006020820190508181036000830152615d66818461584d565b905092915050565b6000602082019050615d83600083018461595f565b92915050565b6000606082019050615d9e600083018661595f565b615dab602083018561595f565b615db8604083018461595f565b949350505050565b6000604051905081810181811067ffffffffffffffff82111715615de357600080fd5b8060405250919050565b600067ffffffffffffffff821115615e0457600080fd5b601f19601f8301169050602081019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b600081519050919050565b600081519050919050565b600081519050919050565b600081519050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60008115159050919050565b6000600482101515615ecd57fe5b819050919050565b6000819050919050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60008115159050919050565b6000819050919050565b6000615f2082615ebf565b9050919050565b82818337600083830152505050565b60005b83811015615f54578082015181840152602081019050615f39565b83811115615f63576000848401525b50505050565b6000601f19601f83011690509190505600a265627a7a72305820a8b16d6edb3dec83620f88adda673a13814ca733c724c0c9bba643f481ee1fcf6c6578706572696d656e74616cf50037
{"success": true, "error": null, "results": {"detectors": [{"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "tautology", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'tautology', 'impact': 'Medium', 'confidence': 'High'}]}
89
0x1d847fb6e04437151736a53f09b6e49713a52aad
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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 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 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 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 Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } 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); } } contract Migrations { address public owner; uint256 public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint256 completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } library FixedPoint { using SafeMath for uint256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // Can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } contract Lockable { bool private _notEntered; constructor() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(msg.sender, amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } abstract contract Balancer { function getSpotPriceSansFee(address tokenIn, address tokenOut) external virtual view returns (uint256 spotPrice); } abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); } abstract contract OneSplit { function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public virtual view returns (uint256 returnAmount, uint256[] memory distribution); function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) public virtual payable returns (uint256 returnAmount); } abstract contract Uniswap { // Called after every swap showing the new uniswap "price" for this token pair. event Sync(uint112 reserve0, uint112 reserve1); } contract BalancerMock is Balancer { uint256 price = 0; // these params arent used in the mock, but this is to maintain compatibility with balancer API function getSpotPriceSansFee(address tokenIn, address tokenOut) external virtual override view returns (uint256 spotPrice) { return price; } // this is not a balancer call, but for testing for changing price. function setPrice(uint256 newPrice) external { price = newPrice; } } contract FixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } contract OneSplitMock is OneSplit { address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; mapping(bytes32 => uint256) prices; receive() external payable {} // Sets price of 1 FROM = <PRICE> TO function setPrice( address from, address to, uint256 price ) external { prices[keccak256(abi.encodePacked(from, to))] = price; } function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public override view returns (uint256 returnAmount, uint256[] memory distribution) { returnAmount = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount; return (returnAmount, distribution); } function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) public override payable returns (uint256 returnAmount) { uint256 amountReturn = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount; require(amountReturn >= minReturn, "Min Amount not reached"); if (destToken == ETH_ADDRESS) { msg.sender.transfer(amountReturn); } else { require(IERC20(destToken).transfer(msg.sender, amountReturn), "erc20-send-failed"); } } } contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } contract ReentrancyChecker { bytes public txnData; bool hasBeenCalled; // Used to prevent infinite cycles where the reentrancy is cycled forever. modifier skipIfReentered { if (hasBeenCalled) { return; } hasBeenCalled = true; _; hasBeenCalled = false; } function setTransactionData(bytes memory _txnData) public { txnData = _txnData; } function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool success) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } } fallback() external skipIfReentered { // Attampt to re-enter with the set txnData. bool success = _executeCall(msg.sender, 0, txnData); // Fail if the call succeeds because that means the re-entrancy was successful. require(!success, "Re-entrancy was successful"); } } contract ReentrancyMock is Lockable { uint256 public counter; constructor() public { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) public Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), now); } } contract UniswapMock is Uniswap { function setPrice(uint112 reserve0, uint112 reserve1) external { emit Sync(reserve0, reserve1); } } contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() public { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } abstract contract FeePayer is Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees { payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) nonReentrant() { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { StoreInterface store = _getStore(); uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral from which to pay fees. if (collateralPool.isEqual(0)) { return totalPaid; } // Exit early if fees were already paid during this block. if (lastPaymentTime == time) { return totalPaid; } (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) = store.computeRegularFee( lastPaymentTime, time, collateralPool ); lastPaymentTime = time; totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return totalPaid; } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. require(collateralPool.isGreaterThan(amount), "Final fee is more than PfC"); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _pfc() internal virtual view returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; receive() external payable { deposit(); } fallback() external payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } function withdraw(uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); emit Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint256) { return address(this).balance; } function approve(address guy, uint256 wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint256 wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; } abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) public { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist( finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist) ); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingInterface.Commitment[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingInterface.Reveal[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingInterface.PendingRequest[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingInterface) { return VotingInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) public { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted"); DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted"); designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals_slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that * disallows structs arrays to be passed to external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 votePrice, FixedPoint.Unsigned memory numberTokens ) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if ( votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode]) ) { data.currentMode = votePrice; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if ( data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold) ) { // `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) public { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have “0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } contract GovernorTest is Governor { constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) public { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; } interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } interface OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) external; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) external view returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) external view returns (int256); } interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint256 time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint256 time; int256 price; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] calldata commits) external virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) external virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] calldata reveals) external virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external virtual view returns (PendingRequest[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external virtual view returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external virtual view returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); } contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) external override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) external override view returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) external override view returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } contract Umip15Upgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; constructor( address _governor, address _existingVoting, address _newVoting, address _finder ) public { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); } function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set current Voting contract to migrated. existingVoting.setMigrated(newVoting); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) public { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } } 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 { } } abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal virtual override { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } } contract TestnetERC20 is ERC20 { /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _decimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } contract DepositBox is FeePayer, AdministrateeInterface, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) public ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div( exchangeRate ); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal virtual override view returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address excessTokenBeneficiary; } // - Address of TokenFactory to pass into newly constructed ExpiringMultiParty contracts address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params)); _registerContract(new address[](0), address(derivative)); emit CreatedExpiringMultiParty(address(derivative), msg.sender); return address(derivative); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.tokenFactoryAddress = tokenFactoryAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.excessTokenBeneficiary != address(0), "Token Beneficiary cannot be 0x0"); require(params.expirationTimestamp > now, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.syntheticName = params.syntheticName; constructorParams.syntheticSymbol = params.syntheticSymbol; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPct = params.disputeBondPct; constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.excessTokenBeneficiary = params.excessTokenBeneficiary; } } contract PricelessPositionManager is FeePayer, AdministrateeInterface { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // The excessTokenBeneficiary of any excess tokens added to the contract. address public excessTokenBeneficiary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _syntheticName name for the token contract that will be deployed. * @param _syntheticSymbol symbol for the token contract that will be deployed. * @param _tokenFactoryAddress deployed UMA token factory to create the synthetic token. * @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * @param _excessTokenBeneficiary Beneficiary to which all excess token balances that accrue in the contract can be * sent. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, string memory _syntheticName, string memory _syntheticSymbol, address _tokenFactoryAddress, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _excessTokenBeneficiary ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime(), "Invalid expiration in future"); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; TokenFactory tf = TokenFactory(_tokenFactoryAddress); tokenCurrency = tf.createToken(_syntheticName, _syntheticSymbol, 18); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; excessTokenBeneficiary = _excessTokenBeneficiary; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0, "Pending transfer"); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp, "Request expires post-expiry"); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ), "Sponsor already has position" ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime(), "Invalid transfer request" ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0, "No pending transfer"); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the witdrawl. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)), "Invalid collateral amount" ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp, "Request expires post-expiry"); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue), "Minting synthetic tokens failed"); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding), "Invalid token amount"); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul( _getFeeAdjustedCollateral(positionData.rawCollateral) ); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePrice(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan( positionCollateral ) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min( _getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral ); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // The final fee for this request is paid out of the contract rather than by the caller. _payFinalFees(address(this), _computeFinalFees()); _requestOraclePrice(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress(), "Caller not Governor"); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePrice(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Drains any excess balance of the provided ERC20 token to a pre-selected beneficiary. * @dev This will drain down to the amount of tracked collateral and drain the full balance of any other token. * @param token address of the ERC20 token whose excess balance should be drained. */ function trimExcess(IERC20 token) external fees() nonReentrant() returns (FixedPoint.Unsigned memory amount) { FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(token.balanceOf(address(this))); if (address(token) == address(collateralCurrency)) { // If it is the collateral currency, send only the amount that the contract is not tracking. // Note: this could be due to rounding error or balance-changing tokens, like aTokens. amount = balance.sub(_pfc()); } else { // If it's not the collateral currency, send the entire balance. amount = balance; } token.safeTransfer(excessTokenBeneficiary, amount.rawValue); } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getFeeAdjustedCollateral(positions[sponsor].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal virtual override view returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio( _getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding ); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } } contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external override view returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external override view returns (bool) { return supportedIdentifiers[identifier]; } } contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external override view returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external override view returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external override view returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public override view returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external override payable { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external override view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul( paymentDelay.div(SECONDS_PER_WEEK) ); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external override view returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } contract Voting is Testable, Ownable, OracleInterface, VotingInterface { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. // These requests may be for future rounds. bytes32[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. // Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%. FixedPoint.Unsigned public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface private finder; // If non-zero, this contract has been migrated to this address. All voters and // financial contracts should query the new address only. address public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted(address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved(uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) external override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); bytes32 priceRequestId = _encodePriceRequest(identifier, time); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) external override view onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time); return _hasPrice; } /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) external override view onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Commit, "Cannot commit in reveal phase"); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from // revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); emit VoteRevealed(msg.sender, roundId, identifier, time, price, balance.rawValue); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public { commitVote(identifier, time, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] calldata commits) external override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].hash, commits[i].encryptedVote ); } } } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] calldata reveals) external override { for (uint256 i = 0; i < reveals.length; i++) { revealVote(reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].salt); } } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } uint256 blockTime = getCurrentTime(); require(roundId < voteTiming.computeCurrentRoundId(blockTime), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = blockTime > round.rewardsExpirationTime; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned( votingToken.balanceOfAt(voterAddress, round.snapshotId) ); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned( votingToken.totalSupplyAt(round.snapshotId) ); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, 0); } else if ( voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash) ) { // The price was successfully resolved during the voter's last voting round, the voter revealed // and was correct, so they are eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, 0); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed"); } } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external override view returns (PendingRequest[] memory) { uint256 blockTime = getCurrentTime(); uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that have an Active RequestStatus. PendingRequest[] memory unresolved = new PendingRequest[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequest({ identifier: priceRequest.identifier, time: priceRequest.time }); numUnresolved++; } } PendingRequest[] memory pendingRequests = new PendingRequest[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external override view returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external override view returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError(bytes32 identifier, uint256 time) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice( _computeGat(priceRequest.lastVotingRound) ); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest(bytes32 identifier, uint256 time) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time)]; } function _encodePriceRequest(bytes32 identifier, uint256 time) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice( _computeGat(priceRequest.lastVotingRound) ); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved(priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice( _computeGat(priceRequest.lastVotingRound) ); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. */ constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {} /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20, ERC20Snapshot) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._mint(account, value); } function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._burn(account, value); } } contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } } contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address finderAddress; address tokenFactoryAddress; address timerAddress; address excessTokenBeneficiary; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPct; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPct; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPct; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 withdrawalAmount, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.finderAddress, params.priceFeedIdentifier, params.syntheticName, params.syntheticSymbol, params.tokenFactoryAddress, params.minSponsorTokens, params.timerAddress, params.excessTokenBeneficiary ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1), "CR is more than 100%"); require( params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1), "Rewards are more than 100%" ); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPct = params.disputeBondPct; sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; disputerDisputeRewardPct = params.disputerDisputeRewardPct; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul( ratio ); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.PreDispute, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp <= getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(liquidationLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPct` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.PendingDispute; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * the sponsor, liquidator, and/or disputer can call this method to receive payments. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * Once all collateral is withdrawn, delete the liquidation data. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return amountWithdrawn the total amount of underlying returned from the liquidation. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (msg.sender == liquidation.disputer) || (msg.sender == liquidation.liquidator) || (msg.sender == liquidation.sponsor), "Caller cannot withdraw rewards" ); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul( feeAttenuation ); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation can withdraw different amounts. // Once a caller has been paid their address deleted from the struct. // This prevents them from being paid multiple from times the same liquidation. FixedPoint.Unsigned memory withdrawalAmount = FixedPoint.fromUnscaledUint(0); if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users can withdraw from the contract. if (msg.sender == liquidation.disputer) { // Pay DISPUTER: disputer reward + dispute bond + returned final fee FixedPoint.Unsigned memory payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); withdrawalAmount = withdrawalAmount.add(payToDisputer); delete liquidation.disputer; } if (msg.sender == liquidation.sponsor) { // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward FixedPoint.Unsigned memory remainingCollateral = collateral.sub(tokenRedemptionValue); FixedPoint.Unsigned memory payToSponsor = sponsorDisputeReward.add(remainingCollateral); withdrawalAmount = withdrawalAmount.add(payToSponsor); delete liquidation.sponsor; } if (msg.sender == liquidation.liquidator) { // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in // the constructor when these params are set. FixedPoint.Unsigned memory payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub( disputerDisputeReward ); withdrawalAmount = withdrawalAmount.add(payToLiquidator); delete liquidation.liquidator; } // Free up space once all collateral is withdrawn by removing the liquidation object from the array. if ( liquidation.disputer == address(0) && liquidation.sponsor == address(0) && liquidation.liquidator == address(0) ) { delete liquidations[sponsor][liquidationId]; } // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed && msg.sender == liquidation.liquidator) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee withdrawalAmount = collateral.add(disputeBondAmount).add(finalFee); delete liquidations[sponsor][liquidationId]; // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.PreDispute && msg.sender == liquidation.liquidator) { // Pay LIQUIDATOR: collateral + returned final fee withdrawalAmount = collateral.add(finalFee); delete liquidations[sponsor][liquidationId]; } require(withdrawalAmount.isGreaterThan(0), "Invalid withdrawal amount"); // Decrease the total collateral held in liquidatable by the amount withdrawn. amountWithdrawn = _removeCollateral(rawLiquidationCollateral, withdrawalAmount); emit LiquidationWithdrawn(msg.sender, amountWithdrawn.rawValue, liquidation.state, settlementPrice.rawValue); // Transfer amount withdrawn from this contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); return amountWithdrawn; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return. // If the liquidation is in the PendingDispute state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == PendingDispute and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.PendingDispute) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul( liquidation.settlementPrice ); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal override view returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.PreDispute) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)), "Liquidation not withdrawable" ); } } contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } }
0x608060405234801561001057600080fd5b50600436106101f05760003560e01c806370a0cf2c1161010f5780638c65c81f116100a2578063b90fd48011610071578063b90fd480146103f0578063c9280f06146103f8578063d8651ad01461040b578063f2fde38b1461041e576101f0565b80638c65c81f1461039d5780638da5cb5b146103c0578063a03e881a146103c8578063b0340123146103e8576101f0565b806380a1f712116100de57806380a1f7121461034257806383c6aaca146103575780638558d4f31461036a5780638876e8a01461038a576101f0565b806370a0cf2c1461030a578063715018a61461031d57806371b7db531461032557806374dd278c1461032d576101f0565b806329cb924d116101875780634c7a2603116101565780634c7a2603146102c95780635727e25d146102dc5780636852eea0146102e457806368ad8ae3146102f7576101f0565b806329cb924d1461029e57806331f9e35b146102a65780634000851f146102ae5780634666cb0c146102b6576101f0565b806320b373a2116101c357806320b373a21461025b57806322f8e5661461027057806326af73bf146102835780632960b5af1461028b576101f0565b80630d434e7e146101f5578063110d559a1461021e57806313e56d6a146102335780631c39c38d14610246575b600080fd5b610208610203366004612bf4565b610431565b6040516102159190613727565b60405180910390f35b61023161022c366004612e8c565b61099b565b005b610231610241366004612ee6565b610a95565b61024e610af7565b6040516102159190612ff1565b610263610b06565b60405161021591906130c4565b61023161027e366004612f0b565b610b0c565b610263610b86565b610231610299366004612bbc565b610b8c565b610263610be3565b610263610c86565b61024e610c8c565b6102316102c4366004612db3565b610c9b565b6102316102d7366004612e5b565b610d09565b610263610f8b565b6102316102f2366004612cea565b610f9d565b610231610305366004612d67565b611015565b610231610318366004612c4a565b61136c565b6102316114ef565b61026361156e565b610335611574565b60405161021591906130f9565b61034a611589565b604051610215919061301e565b610231610365366004612ee6565b611745565b61037d610378366004612cb8565b611780565b604051610215919061306d565b610231610398366004612f0b565b6118cc565b6103b06103ab366004612f0b565b611906565b6040516102159493929190613760565b61024e611940565b6103db6103d6366004612d67565b61194f565b60405161021591906130b9565b61024e611ad4565b610263611ae3565b610263610406366004612d67565b611ae9565b610231610419366004612d88565b611c8a565b61023161042c366004612bbc565b611dce565b610439612ada565b600b546001600160a01b03161561047d57600b546001600160a01b0316331461047d5760405162461bcd60e51b8152600401610474906132bb565b60405180910390fd5b6000610487610be3565b9050610494600582611f1f565b84106104b25760405162461bcd60e51b8152600401610474906132f2565b6000848152600260205260409020600381015482116104cf612ada565b604080516020810191829052600954855463277166bf60e11b909352909182916001600160a01b031690634ee2cd7e9061050e908d9060248601613005565b60206040518083038186803b15801561052657600080fd5b505afa15801561053a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061055e9190612f23565b9052905061056a612ada565b6040805160208101918290526009548654630981b24d60e41b909352909182916001600160a01b03169063981b24d0906105a790602485016130c4565b60206040518083038186803b1580156105bf57600080fd5b505afa1580156105d3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105f79190612f23565b90529050610603612ada565b60408051602081019091526001860154815261061f9083611f44565b905060405180602001604052806000815250965060005b88518110156108dc5760006106798a838151811061065057fe5b6020026020010151600001518b848151811061066857fe5b602002602001015160200151611f81565b6003810154600081815260028301602052604090209192508c146106af5760405162461bcd60e51b815260040161047490613682565b6106b98282611fa7565b6001600160a01b038d166000908152602082905260409020600101546106e05750506108d4565b861561075f578a83815181106106f257fe5b6020026020010151600001518c8e6001600160a01b03167ff8da7bdb1837995e872689b605d1a2b076db111cb4b15351f835ebd275be423f8e878151811061073657fe5b60200260200101516020015160006040516107529291906130cd565b60405180910390a46108b5565b6001600160a01b038d166000908152602082905260409020600190810154610789918301906120e9565b1561084057610796612ada565b6107b56107a583600101612120565b6107af8988611f44565b9061214c565b90506107c18b8261218a565b9a508b84815181106107cf57fe5b6020026020010151600001518d8f6001600160a01b03167ff8da7bdb1837995e872689b605d1a2b076db111cb4b15351f835ebd275be423f8f888151811061081357fe5b60200260200101516020015185600001516040516108329291906130cd565b60405180910390a4506108b5565b8a838151811061084c57fe5b6020026020010151600001518c8e6001600160a01b03167ff8da7bdb1837995e872689b605d1a2b076db111cb4b15351f835ebd275be423f8e878151811061089057fe5b60200260200101516020015160006040516108ac9291906130cd565b60405180910390a45b6001600160a01b038d1660009081526020919091526040812060010155505b600101610636565b506108e88760006121ad565b1561098e5760095487516040516340c10f1960e01b81526001600160a01b03909216916340c10f1991610920918e9190600401613005565b602060405180830381600087803b15801561093a57600080fd5b505af115801561094e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109729190612d47565b61098e5760405162461bcd60e51b815260040161047490613478565b5050505050509392505050565b600b546001600160a01b0316156109c45760405162461bcd60e51b81526004016104749061361c565b60006109ce610be3565b905060016109dd6005836121c4565b60028111156109e857fe5b14610a055760405162461bcd60e51b8152600401610474906136b9565b336001600160a01b0316610a51600c5485858080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506121e992505050565b6001600160a01b031614610a775760405162461bcd60e51b815260040161047490613441565b6000610a84600583611f1f565b9050610a8f81612317565b50505050565b610a9d612402565b6001546001600160a01b03908116911614610aca5760405162461bcd60e51b8152600401610474906133d5565b610ad5816001612406565b610af15760405162461bcd60e51b815260040161047490613542565b51600655565b6000546001600160a01b031681565b600c5481565b6000546001600160a01b0316610b2157600080fd5b60005460405163117c72b360e11b81526001600160a01b03909116906322f8e56690610b519084906004016130c4565b600060405180830381600087803b158015610b6b57600080fd5b505af1158015610b7f573d6000803e3d6000fd5b5050505050565b60085481565b610b94612402565b6001546001600160a01b03908116911614610bc15760405162461bcd60e51b8152600401610474906133d5565b600b80546001600160a01b0319166001600160a01b0392909216919091179055565b600080546001600160a01b031615610c805760008054906101000a90046001600160a01b03166001600160a01b03166329cb924d6040518163ffffffff1660e01b815260040160206040518083038186803b158015610c4157600080fd5b505afa158015610c55573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c799190612f23565b9050610c83565b50425b90565b60075481565b600b546001600160a01b031681565b610ca6848484611c8a565b6000610cbb610cb3610be3565b600590611f1f565b90508481336001600160a01b03167f6992efdd7b69c1a8d79212d5ef5fe92118ed053fb7195808a858fa6889a117e98786604051610cfa929190613731565b60405180910390a45050505050565b600b546001600160a01b031615610d325760405162461bcd60e51b81526004016104749061361c565b6000610d3c610be3565b90506001610d4b6005836121c4565b6002811115610d5657fe5b14610d735760405162461bcd60e51b815260040161047490613242565b6000610d80600583611f1f565b90506000610d8e8787611f81565b600083815260028201602090815260408083203384529182905290912080549293509091610dce5760405162461bcd60e51b8152600401610474906134de565b80600001548787338b888e604051602001610dee96959493929190612f86565b6040516020818303038152906040528051906020012014610e215760405162461bcd60e51b81526004016104749061318e565b600084815260026020526040902054610e4c5760405162461bcd60e51b815260040161047490613653565b600084815260026020526040812054908255610e66612ada565b60408051602081019182905260095463277166bf60e11b9092529081906001600160a01b0316634ee2cd7e610e9f338760248601613005565b60206040518083038186803b158015610eb757600080fd5b505afa158015610ecb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610eef9190612f23565b815250905088604051602001610f0591906130c4565b60408051601f198184030181529190528051602090910120600180850191909155610f339085018a8361241d565b8a86336001600160a01b03167fd04931ad32b4f942a0f169443ebd7f85a7d42c8b4310b4792243a065348836078d8d8660000151604051610f769392919061374a565b60405180910390a45050505050505050505050565b6000610f98610cb3610be3565b905090565b60005b8181101561101057611008838383818110610fb757fe5b90506080020160000135848484818110610fcd57fe5b90506080020160200135858585818110610fe357fe5b90506080020160400135868686818110610ff957fe5b90506080020160600135610d09565b600101610fa0565b505050565b600b546001600160a01b03161561105557600b546001600160a01b031633146110505760405162461bcd60e51b8152600401610474906136f0565b61117e565b600a546040516302abf57960e61b81526000916001600160a01b03169063aafd5e40906110919067526567697374727960c01b906004016130c4565b60206040518083038186803b1580156110a957600080fd5b505afa1580156110bd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110e19190612bd8565b60405163f9f6b49b60e01b81529091506001600160a01b0382169063f9f6b49b90611110903390600401612ff1565b60206040518083038186803b15801561112857600080fd5b505afa15801561113c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111609190612d47565b61117c5760405162461bcd60e51b8152600401610474906135ae565b505b6000611188610be3565b9050808211156111aa5760405162461bcd60e51b81526004016104749061350b565b6111b26124d2565b6001600160a01b03166390978d1b846040518263ffffffff1660e01b81526004016111dd91906130c4565b60206040518083038186803b1580156111f557600080fd5b505afa158015611209573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061122d9190612d47565b6112495760405162461bcd60e51b81526004016104749061335d565b60006112558484612569565b6000818152600360205260408120919250611271600585611f1f565b9050600061127f838361259c565b9050600081600381111561128f57fe5b14156113635760006112a2836001612623565b604080516080810182528a815260208082018b8152828401858152600480546060860190815260008d815260039586905287812096518755935160018088019190915592519486019490945592519383019390935581549283018255527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b0187905551909150889082907f5d80f93c41e95cacea0b9ce9bb825092d709fa503a70bb26ea3f536bf16946bd90611359908b906130c4565b60405180910390a3505b50505050505050565b60005b818110156110105782828281811061138357fe5b905060200281019061139591906137c6565b6113a390606081019061377b565b1515905061141b576114168383838181106113ba57fe5b90506020028101906113cc91906137c6565b358484848181106113d957fe5b90506020028101906113eb91906137c6565b602001358585858181106113fb57fe5b905060200281019061140d91906137c6565b60400135611c8a565b6114e7565b6114e783838381811061142a57fe5b905060200281019061143c91906137c6565b3584848481811061144957fe5b905060200281019061145b91906137c6565b6020013585858581811061146b57fe5b905060200281019061147d91906137c6565b6040013586868681811061148d57fe5b905060200281019061149f91906137c6565b6114ad90606081019061377b565b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250610c9b92505050565b60010161136f565b6114f7612402565b6001546001600160a01b039081169116146115245760405162461bcd60e51b8152600401610474906133d5565b6001546040516000916001600160a01b0316907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600180546001600160a01b0319169055565b60055481565b6000610f98611581610be3565b6005906121c4565b60606000611595610be3565b905060006115a4600583611f1f565b6004549091506060906001600160401b03811180156115c257600080fd5b506040519080825280602002602001820160405280156115fc57816020015b6115e9612aed565b8152602001906001900390816115e15790505b5090506000805b6004548110156116a7576000600360006004848154811061162057fe5b9060005260206000200154815260200190815260200160002090506001600381111561164857fe5b611652828761259c565b600381111561165d57fe5b141561169e57604051806040016040528082600001548152602001826001015481525084848151811061168c57fe5b60209081029190910101526001909201915b50600101611603565b506060816001600160401b03811180156116c057600080fd5b506040519080825280602002602001820160405280156116fa57816020015b6116e7612aed565b8152602001906001900390816116df5790505b50905060005b8281101561173b5783818151811061171457fe5b602002602001015182828151811061172857fe5b6020908102919091010152600101611700565b5094505050505090565b61174d612402565b6001546001600160a01b0390811691161461177a5760405162461bcd60e51b8152600401610474906133d5565b51600755565b60608082516001600160401b038111801561179a57600080fd5b506040519080825280602002602001820160405280156117d457816020015b6117c1612aed565b8152602001906001900390816117b95790505b50905060006117e4610cb3610be3565b905060005b84518110156118c157600061181b86838151811061180357fe5b60200260200101516000015187848151811061066857fe5b90506000611829828561259c565b9050600181600381111561183957fe5b1415611861578385848151811061184c57fe5b60200260200101516020018181525050611883565b816003015485848151811061187257fe5b602002602001015160200181815250505b8085848151811061189057fe5b60200260200101516000019060038111156118a757fe5b908160038111156118b457fe5b90525050506001016117e9565b50909150505b919050565b6118d4612402565b6001546001600160a01b039081169116146119015760405162461bcd60e51b8152600401610474906133d5565b600855565b6002602081815260009283526040928390208054845180840186526001830154815285519384019095529281015482526003015491929184565b6001546001600160a01b031690565b600b546000906001600160a01b03161561199257600b546001600160a01b0316331461198d5760405162461bcd60e51b8152600401610474906136f0565b611abb565b600a546040516302abf57960e61b81526000916001600160a01b03169063aafd5e40906119ce9067526567697374727960c01b906004016130c4565b60206040518083038186803b1580156119e657600080fd5b505afa1580156119fa573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a1e9190612bd8565b60405163f9f6b49b60e01b81529091506001600160a01b0382169063f9f6b49b90611a4d903390600401612ff1565b60206040518083038186803b158015611a6557600080fd5b505afa158015611a79573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a9d9190612d47565b611ab95760405162461bcd60e51b8152600401610474906135ae565b505b6000611ac78484612648565b5090925050505b92915050565b6009546001600160a01b031681565b60065481565b600b546000906001600160a01b031615611b2c57600b546001600160a01b03163314611b275760405162461bcd60e51b8152600401610474906136f0565b611c55565b600a546040516302abf57960e61b81526000916001600160a01b03169063aafd5e4090611b689067526567697374727960c01b906004016130c4565b60206040518083038186803b158015611b8057600080fd5b505afa158015611b94573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bb89190612bd8565b60405163f9f6b49b60e01b81529091506001600160a01b0382169063f9f6b49b90611be7903390600401612ff1565b60206040518083038186803b158015611bff57600080fd5b505afa158015611c13573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c379190612d47565b611c535760405162461bcd60e51b8152600401610474906135ae565b505b6000806060611c648686612648565b925092509250828190611ac75760405162461bcd60e51b8152600401610474919061310d565b600b546001600160a01b031615611cb35760405162461bcd60e51b81526004016104749061361c565b80611cd05760405162461bcd60e51b8152600401610474906134af565b6000611cda610be3565b90506000611ce96005836121c4565b6002811115611cf457fe5b14611d115760405162461bcd60e51b8152600401610474906135e5565b6000611d1e600583611f1f565b90506000611d2c8686611f81565b90506001611d3a828461259c565b6003811115611d4557fe5b14611d625760405162461bcd60e51b81526004016104749061340a565b600381018290556000828152600282016020908152604080832033808552928190529281902087905551889185917f879c67d036f174a10ea491cf7281d05af9b906660b4f26727d866aec0cf9147c90611dbd908b906130c4565b60405180910390a450505050505050565b611dd6612402565b6001546001600160a01b03908116911614611e035760405162461bcd60e51b8152600401610474906133d5565b6001600160a01b038116611e295760405162461bcd60e51b8152600401610474906131c5565b6001546040516001600160a01b038084169216907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a3600180546001600160a01b0319166001600160a01b0392909216919091179055565b600081604051602001611e989190612fc0565b604051602081830303815290604052805190602001209050919050565b60008111611ec257600080fd5b9055565b6000611ed1826127d3565b5183511115905092915050565b600082611eed57506000611ace565b82820282848281611efa57fe5b0414611f185760405162461bcd60e51b815260040161047490613394565b9392505050565b600080611f3060025b855490611ede565b9050611f3c8382612801565b949350505050565b611f4c612ada565b6040805160208101909152825184518291670de0b6b3a764000091611f7091611ede565b81611f7757fe5b0490529392505050565b600060036000611f918585612569565b8152602001908152602001600020905092915050565b60048201546000191415611fba576120e5565b600080611fd7611fcd8560030154612843565b6001850190612935565b9150915081611ff85760405162461bcd60e51b815260040161047490613579565b6004805460001981019160009160039183918590811061201457fe5b906000526020600020015481526020019081526020016000209050856004015481600401819055506004828154811061204957fe5b9060005260206000200154600487600401548154811061206557fe5b600091825260209091200155600480548061207c57fe5b60008281526020812082016000199081019190915590810190915560048701558554600387015460018801546040517f67565e6a3e804c4e180134cb2885e32142229de3ca125701318af11658ee4988916120d89188906130cd565b60405180910390a3505050505b5050565b6000826002015460405160200161210091906130c4565b604051602081830303815290604052805190602001208214905092915050565b612128612ada565b50600281015460009081526020918252604090819020815192830190915254815290565b612154612ada565b60408051602081019091528251845182916121819161217b90670de0b6b3a7640000611ede565b90612801565b90529392505050565b612192612ada565b60408051602081019091528251845182916121819190612623565b60006121b8826127d3565b51835111905092915050565b60006121de600284546121d8908590612801565b906129e1565b6002811115611f1857fe5b6000815160411461220c5760405162461bcd60e51b815260040161047490613157565b60208201516040830151606084015160001a7f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a082111561225e5760405162461bcd60e51b815260040161047490613279565b8060ff16601b1415801561227657508060ff16601c14155b156122935760405162461bcd60e51b81526004016104749061331b565b6000600187838686604051600081526020016040526040516122b894939291906130db565b6020604051602081039080840390855afa1580156122da573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b03811661230d5760405162461bcd60e51b815260040161047490613120565b9695505050505050565b600081815260026020526040902080546120e557600960009054906101000a90046001600160a01b03166001600160a01b0316639711715a6040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561237b57600080fd5b505af115801561238f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123b39190612f23565b8155600082815260026020819052604090912060075460018201556006549101556008546123ec906123e6600585612a23565b90612623565b6000838152600260205260409020600301555050565b3390565b6000612411826127d3565b51835110905092915050565b604080516020810190915260018401548152612439908261218a565b51600184015560008281526020848152604091829020825191820190925290548152612465908261218a565b600083815260208590526040902090519055600283015482148015906124c35750600283015460009081526020848152604080832081518084018352905481528584528683529281902081519283019091525481526124c391612a47565b15611010575060029190910155565b600a546040516302abf57960e61b81526000916001600160a01b03169063aafd5e409061251990721259195b9d1a599a595c95da1a5d195b1a5cdd606a1b906004016130c4565b60206040518083038186803b15801561253157600080fd5b505afa158015612545573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f989190612bd8565b6000828260405160200161257e9291906130cd565b60405160208183030381529060405280519060200120905092915050565b60008260030154600014156125b357506000611ace565b818360030154101561260757600383015460008181526002850160205260408120916125ec906125e290612843565b6001840190612935565b509050806125fb5760016125fe565b60025b92505050611ace565b818360030154141561261b57506001611ace565b506003611ace565b600082820183811015611f185760405162461bcd60e51b81526004016104749061320b565b600080606060006126598686611f81565b90506000612668610cb3610be3565b90506000612676838361259c565b9050600181600381111561268657fe5b14156126d3576000806040518060400160405280601e81526020017f43757272656e7420766f74696e6720726f756e64206e6f7420656e64656400008152509550955095505050506127cc565b60028160038111156126e157fe5b141561272e576003830154600081815260028501602052604081209161270a906125e290612843565b60408051602081019091526000815260019a5090985096506127cc95505050505050565b600381600381111561273c57fe5b1415612789576000806040518060400160405280601d81526020017f5072696365206973207374696c6c20746f20626520766f746564206f6e0000008152509550955095505050506127cc565b6000806040518060400160405280601981526020017f507269636520776173206e6576657220726571756573746564000000000000008152509550955095505050505b9250925092565b6127db612ada565b6040805160208101909152806127f984670de0b6b3a7640000611ede565b905292915050565b6000611f1883836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250612a4e565b61284b612ada565b60008281526002602052604090205480612876575050604080516020810190915260001981526118c7565b61287e612ada565b604080516020810191829052600954630981b24d60e41b9092529081906001600160a01b031663981b24d06128b686602485016130c4565b60206040518083038186803b1580156128ce57600080fd5b505afa1580156128e2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129069190612f23565b905260008581526002602081815260409283902083519182019093529101548152909150611f3c908290611f44565b600080612940612ada565b612955606461294f60326127d3565b90612a85565b6040805160208101909152600187015481529091506129749085612a47565b80156129bf5750604080516020808201835260018801548252600288015460009081528882528390208351918201909352915482526129bf9183916129b9919061214c565b90612a47565b156129d45760019250846002015491506129d9565b600092505b509250929050565b6000611f1883836040518060400160405280601881526020017f536166654d6174683a206d6f64756c6f206279207a65726f0000000000000000815250612aa6565b600080612a306002611f28565b9050611f3c612a40846001612623565b8290611ede565b5190511190565b60008183612a6f5760405162461bcd60e51b8152600401610474919061310d565b506000838581612a7b57fe5b0495945050505050565b612a8d612ada565b6040805160208101909152835181906121819085612801565b60008183612ac75760405162461bcd60e51b8152600401610474919061310d565b50828481612ad157fe5b06949350505050565b6040518060200160405280600081525090565b604080518082019091526000808252602082015290565b600082601f830112612b14578081fd5b81356001600160401b03811115612b29578182fd5b6020612b3881828402016137e5565b8281529250808301848201604080850287018401881015612b5857600080fd5b60005b85811015612b7f57612b6d8984612b8b565b84529284019291810191600101612b5b565b50505050505092915050565b600060408284031215612b9c578081fd5b612ba660406137e5565b9050813581526020820135602082015292915050565b600060208284031215612bcd578081fd5b8135611f1881613817565b600060208284031215612be9578081fd5b8151611f1881613817565b600080600060608486031215612c08578182fd5b8335612c1381613817565b92506020840135915060408401356001600160401b03811115612c34578182fd5b612c4086828701612b04565b9150509250925092565b60008060208385031215612c5c578182fd5b82356001600160401b0380821115612c72578384fd5b818501915085601f830112612c85578384fd5b813581811115612c93578485fd5b8660208083028501011115612ca6578485fd5b60209290920196919550909350505050565b600060208284031215612cc9578081fd5b81356001600160401b03811115612cde578182fd5b611f3c84828501612b04565b60008060208385031215612cfc578182fd5b82356001600160401b0380821115612d12578384fd5b818501915085601f830112612d25578384fd5b813581811115612d33578485fd5b866020608083028501011115612ca6578485fd5b600060208284031215612d58578081fd5b81518015158114611f18578182fd5b60008060408385031215612d79578182fd5b50508035926020909101359150565b600080600060608486031215612d9c578283fd5b505081359360208301359350604090920135919050565b60008060008060808587031215612dc8578081fd5b84359350602085013592506040850135915060608501356001600160401b0380821115612df3578283fd5b818701915087601f830112612e06578283fd5b813581811115612e14578384fd5b612e27601f8201601f19166020016137e5565b9150808252886020828501011115612e3d578384fd5b612e4e81602084016020860161380b565b5094979396509194505050565b60008060008060808587031215612e70578182fd5b5050823594602084013594506040840135936060013592509050565b60008060208385031215612e9e578182fd5b82356001600160401b0380821115612eb4578384fd5b818501915085601f830112612ec7578384fd5b813581811115612ed5578485fd5b866020828501011115612ca6578485fd5b600060208284031215612ef7578081fd5b612f0160206137e5565b9135825250919050565b600060208284031215612f1c578081fd5b5035919050565b600060208284031215612f34578081fd5b5051919050565b60008151808452815b81811015612f6057602081850181015186830182015201612f44565b81811115612f715782602083870101525b50601f01601f19169290920160200192915050565b958652602086019490945260609290921b6bffffffffffffffffffffffff1916604085015260548401526074830152609482015260b40190565b7f19457468657265756d205369676e6564204d6573736167653a0a3332000000008152601c810191909152603c0190565b6001600160a01b0391909116815260200190565b6001600160a01b03929092168252602082015260400190565b602080825282518282018190526000919060409081850190868401855b828110156130605781518051855286015186850152928401929085019060010161303b565b5091979650505050505050565b602080825282518282018190526000919060409081850190868401855b828110156130605781518051600481106130a057fe5b855286015186850152928401929085019060010161308a565b901515815260200190565b90815260200190565b918252602082015260400190565b93845260ff9290921660208401526040830152606082015260800190565b602081016003831061310757fe5b91905290565b600060208252611f186020830184612f3b565b60208082526018908201527f45434453413a20696e76616c6964207369676e61747572650000000000000000604082015260600190565b6020808252601f908201527f45434453413a20696e76616c6964207369676e6174757265206c656e67746800604082015260600190565b6020808252601c908201527f52657665616c6564206461746120213d20636f6d6d6974206861736800000000604082015260600190565b60208082526026908201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160408201526564647265737360d01b606082015260800190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b6020808252601d908201527f43616e6e6f742072657665616c20696e20636f6d6d6974207068617365000000604082015260600190565b60208082526022908201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604082015261756560f01b606082015260800190565b6020808252601b908201527f43616e206f6e6c792063616c6c2066726f6d206d696772617465640000000000604082015260600190565b6020808252600f908201526e125b9d985b1a59081c9bdd5b991259608a1b604082015260600190565b60208082526022908201527f45434453413a20696e76616c6964207369676e6174757265202776272076616c604082015261756560f01b606082015260800190565b6020808252601e908201527f556e737570706f72746564206964656e74696669657220726571756573740000604082015260600190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b6020808252818101527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604082015260600190565b6020808252601e908201527f43616e6e6f7420636f6d6d697420696e61637469766520726571756573740000604082015260600190565b6020808252601b908201527f5369676e6174757265206d757374206d617463682073656e6465720000000000604082015260600190565b6020808252601c908201527f566f74696e6720746f6b656e2069737375616e6365206661696c656400000000604082015260600190565b602080825260159082015274092dcecc2d8d2c840e0e4deecd2c8cac840d0c2e6d605b1b604082015260600190565b602080825260139082015272125b9d985b1a59081a185cda081c995d99585b606a1b604082015260600190565b60208082526018908201527f43616e206f6e6c79207265717565737420696e20706173740000000000000000604082015260600190565b6020808252601d908201527f4741542070657263656e74616765206d757374206265203c2031303025000000604082015260600190565b6020808252818101527f43616e2774207265736f6c766520756e7265736f6c7665642072657175657374604082015260600190565b60208082526019908201527f43616c6c6564206d757374206265207265676973746572656400000000000000604082015260600190565b6020808252601d908201527f43616e6e6f7420636f6d6d697420696e2072657665616c207068617365000000604082015260600190565b6020808252601e908201527f4f6e6c792063616c6c2074686973206966206e6f74206d696772617465640000604082015260600190565b602080825260159082015274149bdd5b99081a185cc81b9bc81cdb985c1cda1bdd605a1b604082015260600190565b6020808252601d908201527f526574726965766520666f7220766f7465732073616d6520726f756e64000000604082015260600190565b6020808252601d908201527f4f6e6c7920736e617073686f7420696e2072657665616c207068617365000000604082015260600190565b6020808252601f908201527f43616c6c6572206d757374206265206d69677261746564206164647265737300604082015260600190565b9051815260200190565b600083825260406020830152611f3c6040830184612f3b565b9283526020830191909152604082015260600190565b93845291516020840152516040830152606082015260800190565b6000808335601e19843603018112613791578283fd5b8301803591506001600160401b038211156137aa578283fd5b6020019150368190038213156137bf57600080fd5b9250929050565b60008235607e198336030181126137db578182fd5b9190910192915050565b6040518181016001600160401b038111828210171561380357600080fd5b604052919050565b82818337506000910152565b6001600160a01b038116811461382c57600080fd5b5056fea2646970667358221220fa65cd88424ab538a3d36f6c66b0221850fe1e47f717b140d30f3445d3a484b064736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
90
0x1da91f1b6c01a2351c40ae5f8f952ba8de0a3e3b
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 sbControllerV2 { event CommunityAdded(address indexed community); event RewardsReleased(address indexed receiver, uint256 amount, uint256 indexed day); using SafeMath for uint256; bool internal initDone; address internal sbTimelock; IERC20 internal strongToken; sbTokensInterface internal sbTokens; sbStrongPoolInterface internal sbStrongPool; sbVotesInterface internal sbVotes; uint256 internal startDay; mapping(uint256 => uint256) internal COMMUNITY_DAILY_REWARDS_BY_YEAR; mapping(uint256 => uint256) internal STRONGPOOL_DAILY_REWARDS_BY_YEAR; mapping(uint256 => uint256) internal VOTER_DAILY_REWARDS_BY_YEAR; uint256 internal MAX_YEARS; address[] internal communities; mapping(uint256 => uint256) internal dayMineSecondsUSDTotal; mapping(address => mapping(uint256 => uint256)) internal communityDayMineSecondsUSD; mapping(address => mapping(uint256 => uint256)) internal communityDayRewards; mapping(address => uint256) internal communityDayStart; uint256 internal dayLastReleasedRewardsFor; address internal superAdmin; address internal pendingSuperAdmin; 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 updateCommunityDailyRewardsByYear(uint256 amount) public { require(msg.sender == superAdmin && msg.sender != address(0), 'not superAdmin'); uint256 year = _getYearDayIsIn(_getCurrentDay()); require(year <= MAX_YEARS, 'invalid year'); COMMUNITY_DAILY_REWARDS_BY_YEAR[year] = amount; } function updateStrongPoolDailyRewardsByYear(uint256 amount) public { require(msg.sender == superAdmin && msg.sender != address(0), 'not superAdmin'); uint256 year = _getYearDayIsIn(_getCurrentDay()); require(year <= MAX_YEARS, 'invalid year'); STRONGPOOL_DAILY_REWARDS_BY_YEAR[year] = amount; } // TODO: Double check me function updateVoterDailyRewardsByYear(uint256 amount) public { require(msg.sender == superAdmin && msg.sender != address(0), 'not superAdmin'); uint256 year = _getYearDayIsIn(_getCurrentDay()); require(year <= MAX_YEARS, 'invalid year'); VOTER_DAILY_REWARDS_BY_YEAR[year] = amount; } function upToDate() external view returns (bool) { return dayLastReleasedRewardsFor == _getCurrentDay().sub(1); } function addCommunity(address community) external { require(msg.sender == sbTimelock, 'not sbTimelock'); require(community != address(0), 'community not zero address'); require(!_communityExists(community), 'community exists'); communities.push(community); communityDayStart[community] = _getCurrentDay(); emit CommunityAdded(community); } function getCommunities() external view returns (address[] memory) { return communities; } function getDayMineSecondsUSDTotal(uint256 day) external view returns (uint256) { require(day >= startDay, '1: invalid day'); require(day <= dayLastReleasedRewardsFor, '2: invalid day'); return dayMineSecondsUSDTotal[day]; } function getCommunityDayMineSecondsUSD(address community, uint256 day) external view returns (uint256) { require(_communityExists(community), 'invalid community'); require(day >= communityDayStart[community], '1: invalid day'); require(day <= dayLastReleasedRewardsFor, '2: invalid day'); return communityDayMineSecondsUSD[community][day]; } function getCommunityDayRewards(address community, uint256 day) external view returns (uint256) { require(_communityExists(community), 'invalid community'); require(day >= communityDayStart[community], '1: invalid day'); require(day <= dayLastReleasedRewardsFor, '2: invalid day'); return communityDayRewards[community][day]; } function getCommunityDailyRewards(uint256 day) external view returns (uint256) { require(day >= startDay, 'invalid day'); uint256 year = _getYearDayIsIn(day); require(year <= MAX_YEARS, 'invalid year'); return COMMUNITY_DAILY_REWARDS_BY_YEAR[year]; } function getStrongPoolDailyRewards(uint256 day) external view returns (uint256) { require(day >= startDay, 'invalid day'); uint256 year = _getYearDayIsIn(day); require(year <= MAX_YEARS, 'invalid year'); return STRONGPOOL_DAILY_REWARDS_BY_YEAR[year]; } function getVoterDailyRewards(uint256 day) external view returns (uint256) { require(day >= startDay, 'invalid day'); uint256 year = _getYearDayIsIn(day); require(year <= MAX_YEARS, 'invalid year'); return VOTER_DAILY_REWARDS_BY_YEAR[year]; } function getStartDay() external view returns (uint256) { return startDay; } function communityAccepted(address community) external view returns (bool) { return _communityExists(community); } function getMaxYears() public view returns (uint256) { return MAX_YEARS; } function getCommunityDayStart(address community) public view returns (uint256) { require(_communityExists(community), 'invalid community'); return communityDayStart[community]; } function getSbTimelockAddressUsed() public view returns (address) { return sbTimelock; } 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 getCurrentYear() public view returns (uint256) { uint256 day = _getCurrentDay().sub(startDay); return _getYearDayIsIn(day == 0 ? startDay : day); } function getYearDayIsIn(uint256 day) public view returns (uint256) { require(day >= startDay, 'invalid day'); return _getYearDayIsIn(day); } function getCurrentDay() public view returns (uint256) { return _getCurrentDay(); } function getDayLastReleasedRewardsFor() public view returns (uint256) { return dayLastReleasedRewardsFor; } function releaseRewards() public { uint256 currentDay = _getCurrentDay(); require(currentDay > dayLastReleasedRewardsFor.add(1), 'already released'); require(sbTokens.upToDate(), 'need token prices'); dayLastReleasedRewardsFor = dayLastReleasedRewardsFor.add(1); uint256 year = _getYearDayIsIn(dayLastReleasedRewardsFor); require(year <= MAX_YEARS, 'invalid year'); address[] memory tokenAddresses = sbTokens.getTokens(); uint256[] memory tokenPrices = sbTokens.getTokenPrices(dayLastReleasedRewardsFor); for (uint256 i = 0; i < communities.length; i++) { address community = communities[i]; uint256 sum = 0; for (uint256 j = 0; j < tokenAddresses.length; j++) { address token = tokenAddresses[j]; (, , uint256 minedSeconds) = sbCommunityInterface(community).getTokenData(token, dayLastReleasedRewardsFor); uint256 tokenPrice = tokenPrices[j]; uint256 minedSecondsUSD = tokenPrice.mul(minedSeconds).div(1e18); sum = sum.add(minedSecondsUSD); } communityDayMineSecondsUSD[community][dayLastReleasedRewardsFor] = sum; dayMineSecondsUSDTotal[dayLastReleasedRewardsFor] = dayMineSecondsUSDTotal[dayLastReleasedRewardsFor].add(sum); } for (uint256 i = 0; i < communities.length; i++) { address community = communities[i]; if (communityDayMineSecondsUSD[community][dayLastReleasedRewardsFor] == 0) { continue; } communityDayRewards[community][dayLastReleasedRewardsFor] = communityDayMineSecondsUSD[community][dayLastReleasedRewardsFor] .mul(COMMUNITY_DAILY_REWARDS_BY_YEAR[year]) .div(dayMineSecondsUSDTotal[dayLastReleasedRewardsFor]); uint256 amount = communityDayRewards[community][dayLastReleasedRewardsFor]; strongToken.approve(community, amount); sbCommunityInterface(community).receiveRewards(dayLastReleasedRewardsFor, amount); emit RewardsReleased(community, amount, currentDay); } (, , uint256 strongPoolMineSeconds) = sbStrongPool.getMineData(dayLastReleasedRewardsFor); if (strongPoolMineSeconds != 0) { strongToken.approve(address(sbStrongPool), STRONGPOOL_DAILY_REWARDS_BY_YEAR[year]); sbStrongPool.receiveRewards(dayLastReleasedRewardsFor, STRONGPOOL_DAILY_REWARDS_BY_YEAR[year]); emit RewardsReleased(address(sbStrongPool), STRONGPOOL_DAILY_REWARDS_BY_YEAR[year], currentDay); } bool hasVoteSeconds = false; for (uint256 i = 0; i < communities.length; i++) { address community = communities[i]; (, , uint256 voteSeconds) = sbVotes.getCommunityData(community, dayLastReleasedRewardsFor); if (voteSeconds > 0) { hasVoteSeconds = true; break; } } if (hasVoteSeconds) { strongToken.approve(address(sbVotes), VOTER_DAILY_REWARDS_BY_YEAR[year]); sbVotes.receiveVoterRewards(dayLastReleasedRewardsFor, VOTER_DAILY_REWARDS_BY_YEAR[year]); emit RewardsReleased(address(sbVotes), VOTER_DAILY_REWARDS_BY_YEAR[year], currentDay); } } function _getCurrentDay() internal view returns (uint256) { return block.timestamp.div(1 days).add(1); } function _communityExists(address community) internal view returns (bool) { for (uint256 i = 0; i < communities.length; i++) { if (communities[i] == community) { return true; } } return false; } function _getYearDayIsIn(uint256 day) internal view returns (uint256) { return day.sub(startDay).div(366).add(1); // dividing by 366 makes day 1 and 365 be in year 1 } } 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; }
0x608060405234801561001057600080fd5b50600436106101e45760003560e01c806382730b381161010f578063ba232ecb116100a2578063d39ca7de11610071578063d39ca7de14610384578063e5f97f3714610397578063e7f9cefd146103aa578063ff4dfa51146103b2576101e4565b8063ba232ecb1461034c578063c251b5651461035f578063ce41607a14610374578063d0fab3ca1461037c576101e4565b8063b0ff5263116100de578063b0ff52631461030b578063b43861b114610313578063b80a999514610326578063b9e5d55114610339576101e4565b806382730b38146102d557806390a39a9e146102e8578063957314e2146102fb578063a4bc4d7f14610303576101e4565b8063335479a2116101875780635a5256ef116101565780635a5256ef146102a85780636232db75146102b0578063733fb91f146102c557806378253604146102cd576101e4565b8063335479a21461027d5780633e6968b6146102855780634eac382f1461028d5780635a306be0146102a0576101e4565b80631727a98c116101c35780631727a98c1461023a5780631da20d5e1461025a5780632025dbb7146102625780632a8c09691461026a576101e4565b806248fc20146101e957806302f8cd5e1461021257806304a3379f14610225575b600080fd5b6101fc6101f7366004611957565b6103ba565b6040516102099190611d17565b60405180910390f35b6101fc610220366004611957565b61042d565b61022d610495565b604051610209919061199c565b61024d6102483660046117ce565b6104a4565b6040516102099190611a16565b6101fc6104b5565b61022d6104bb565b6101fc6102783660046117ea565b6104ca565b61022d610574565b6101fc610583565b6101fc61029b3660046117ce565b610592565b61022d6105d5565b61022d6105e4565b6102c36102be3660046117ce565b6105f3565b005b61022d610708565b61024d610717565b6102c36102e3366004611957565b610735565b6101fc6102f63660046117ea565b6107b1565b6102c361085b565b61022d6108ac565b6101fc6108c0565b6102c3610321366004611957565b6108c6565b6101fc610334366004611957565b61093d565b6101fc610347366004611957565b6109a5565b6101fc61035a366004611957565b6109d2565b610367610a2b565b60405161020991906119c9565b6101fc610a8d565b6102c3610abd565b6102c36103923660046117ce565b6114ba565b6102c36103a5366004611957565b611511565b6102c3611588565b6101fc6115e4565b60006005548210156103e75760405162461bcd60e51b81526004016103de90611a74565b60405180910390fd5b60006103f2836115ea565b90506009548111156104165760405162461bcd60e51b81526004016103de90611b5e565b60009081526006602052604090205490505b919050565b60006005548210156104515760405162461bcd60e51b81526004016103de90611a74565b600061045c836115ea565b90506009548111156104805760405162461bcd60e51b81526004016103de90611b5e565b60009081526007602052604090205492915050565b6001546001600160a01b031690565b60006104af82611612565b92915050565b600f5490565b6010546001600160a01b031690565b60006104d583611612565b6104f15760405162461bcd60e51b81526004016103de90611c09565b6001600160a01b0383166000908152600e60205260409020548210156105295760405162461bcd60e51b81526004016103de90611c75565b600f5482111561054b5760405162461bcd60e51b81526004016103de90611b07565b506001600160a01b03919091166000908152600c60209081526040808320938352929052205490565b6011546001600160a01b031690565b600061058d61166d565b905090565b600061059d82611612565b6105b95760405162461bcd60e51b81526004016103de90611c09565b506001600160a01b03166000908152600e602052604090205490565b6002546001600160a01b031690565b6004546001600160a01b031690565b60005461010090046001600160a01b031633146106225760405162461bcd60e51b81526004016103de90611cef565b6001600160a01b0381166106485760405162461bcd60e51b81526004016103de90611ad0565b61065181611612565b1561066e5760405162461bcd60e51b81526004016103de90611cc5565b600a80546001810182556000919091527fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a80180546001600160a01b0319166001600160a01b0383161790556106c161166d565b6001600160a01b0382166000818152600e602052604080822093909355915190917f3df6de6f7acbd50ccf5d3352eaf45f9eaf44b2b259e62a4c04351fdea533287391a250565b6003546001600160a01b031690565b600061072c600161072661166d565b90611681565b600f5414905090565b6010546001600160a01b03163314801561074e57503315155b61076a5760405162461bcd60e51b81526004016103de90611c9d565b600061077c61077761166d565b6115ea565b90506009548111156107a05760405162461bcd60e51b81526004016103de90611b5e565b600090815260066020526040902055565b60006107bc83611612565b6107d85760405162461bcd60e51b81526004016103de90611c09565b6001600160a01b0383166000908152600e60205260409020548210156108105760405162461bcd60e51b81526004016103de90611c75565b600f548211156108325760405162461bcd60e51b81526004016103de90611b07565b506001600160a01b03919091166000908152600d60209081526040808320938352929052205490565b6010546001600160a01b0316156108845760405162461bcd60e51b81526004016103de90611b84565b601080546001600160a01b031916734b5057b2c87ec9e7c047fb00c0e406dff2fdacad179055565b60005461010090046001600160a01b031690565b60095490565b6010546001600160a01b0316331480156108df57503315155b6108fb5760405162461bcd60e51b81526004016103de90611c9d565b600061090861077761166d565b905060095481111561092c5760405162461bcd60e51b81526004016103de90611b5e565b600090815260076020526040902055565b60006005548210156109615760405162461bcd60e51b81526004016103de90611a74565b600061096c836115ea565b90506009548111156109905760405162461bcd60e51b81526004016103de90611b5e565b60009081526008602052604090205492915050565b60006005548210156109c95760405162461bcd60e51b81526004016103de90611a74565b6104af826115ea565b60006005548210156109f65760405162461bcd60e51b81526004016103de90611c75565b600f54821115610a185760405162461bcd60e51b81526004016103de90611b07565b506000908152600b602052604090205490565b6060600a805480602002602001604051908101604052809291908181526020018280548015610a8357602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610a65575b5050505050905090565b600080610a9e60055461072661166d565b9050610ab78115610aaf5781610777565b6005546115ea565b91505090565b6000610ac761166d565b600f54909150610ad89060016116ca565b8111610af65760405162461bcd60e51b81526004016103de90611bdf565b600260009054906101000a90046001600160a01b03166001600160a01b031663782536046040518163ffffffff1660e01b815260040160206040518083038186803b158015610b4457600080fd5b505afa158015610b58573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b7c9190611937565b610b985760405162461bcd60e51b81526004016103de90611bb4565b600f54610ba69060016116ca565b600f819055600090610bb7906115ea565b9050600954811115610bdb5760405162461bcd60e51b81526004016103de90611b5e565b6002546040805163154d950160e31b815290516060926001600160a01b03169163aa6ca808916004808301926000929190829003018186803b158015610c2057600080fd5b505afa158015610c34573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610c5c9190810190611815565b600254600f546040516329baa97760e01b81529293506060926001600160a01b03909216916329baa97791610c9391600401611d17565b60006040518083038186803b158015610cab57600080fd5b505afa158015610cbf573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610ce791908101906118b3565b905060005b600a54811015610e7d576000600a8281548110610d0557fe5b60009182526020822001546001600160a01b03169150805b8551811015610e21576000868281518110610d3457fe5b602002602001015190506000846001600160a01b0316639f292d7683600f546040518363ffffffff1660e01b8152600401610d709291906119b0565b60606040518083038186803b158015610d8857600080fd5b505afa158015610d9c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dc0919061196f565b925050506000878481518110610dd257fe5b602002602001015190506000610e03670de0b6b3a7640000610dfd85856116ef90919063ffffffff16565b90611729565b9050610e0f86826116ca565b95505060019093019250610d1d915050565b506001600160a01b0382166000908152600c60209081526040808320600f80548552908352818420859055548352600b909152902054610e6190826116ca565b600f546000908152600b60205260409020555050600101610cec565b5060005b600a54811015611080576000600a8281548110610e9a57fe5b60009182526020808320909101546001600160a01b0316808352600c82526040808420600f548552909252912054909150610ed55750611078565b600f546000818152600b602090815260408083205489845260068352818420546001600160a01b0387168552600c84528285209585529490925290912054610f2192610dfd91906116ef565b6001600160a01b038281166000908152600d60209081526040808320600f8054855292528083209490945554815282902054600154925163095ea7b360e01b815290929091169063095ea7b390610f7e90859085906004016119b0565b602060405180830381600087803b158015610f9857600080fd5b505af1158015610fac573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fd09190611937565b50600f546040516379b6a96d60e11b81526001600160a01b0384169163f36d52da9161100191908590600401611d20565b600060405180830381600087803b15801561101b57600080fd5b505af115801561102f573d6000803e3d6000fd5b5050505086826001600160a01b03167fb10f7181725e149ac50c5c122d6ea02644213c2e7f30f74a44b3fce1fb158ca98360405161106d9190611d17565b60405180910390a350505b600101610e81565b50600354600f5460405163eb87e89b60e01b81526000926001600160a01b03169163eb87e89b916110b49190600401611d17565b60606040518083038186803b1580156110cc57600080fd5b505afa1580156110e0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611104919061196f565b9250505080600014611275576001546003546000868152600760205260409081902054905163095ea7b360e01b81526001600160a01b039384169363095ea7b393611154939116916004016119b0565b602060405180830381600087803b15801561116e57600080fd5b505af1158015611182573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111a69190611937565b50600354600f54600086815260076020526040908190205490516379b6a96d60e11b81526001600160a01b039093169263f36d52da926111ea929091600401611d20565b600060405180830381600087803b15801561120457600080fd5b505af1158015611218573d6000803e3d6000fd5b5050600354600087815260076020526040908190205490518994506001600160a01b0390921692507fb10f7181725e149ac50c5c122d6ea02644213c2e7f30f74a44b3fce1fb158ca99161126c9190611d17565b60405180910390a35b6000805b600a54811015611346576000600a828154811061129257fe5b600091825260208220015460048054600f546040516303b5c12760e31b81526001600160a01b0394851696509190931692631dae0938926112d692879291016119b0565b60606040518083038186803b1580156112ee57600080fd5b505afa158015611302573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611326919061196f565b9250508115905061133c57600193505050611346565b5050600101611279565b5080156114b257600154600480546000888152600860205260409081902054905163095ea7b360e01b81526001600160a01b039485169463095ea7b394611392949091169291016119b0565b602060405180830381600087803b1580156113ac57600080fd5b505af11580156113c0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113e49190611937565b5060048054600f546000888152600860205260409081902054905163242be82160e01b81526001600160a01b039093169363242be8219361142793929101611d20565b600060405180830381600087803b15801561144157600080fd5b505af1158015611455573d6000803e3d6000fd5b5050600454600088815260086020526040908190205490518a94506001600160a01b0390921692507fb10f7181725e149ac50c5c122d6ea02644213c2e7f30f74a44b3fce1fb158ca9916114a99190611d17565b60405180910390a35b505050505050565b6010546001600160a01b0316331480156114d357503315155b6114ef5760405162461bcd60e51b81526004016103de90611c9d565b601180546001600160a01b0319166001600160a01b0392909216919091179055565b6010546001600160a01b03163314801561152a57503315155b6115465760405162461bcd60e51b81526004016103de90611c9d565b600061155361077761166d565b90506009548111156115775760405162461bcd60e51b81526004016103de90611b5e565b600090815260086020526040902055565b6011546001600160a01b0316331480156115a157503315155b6115bd5760405162461bcd60e51b81526004016103de90611b2f565b60118054601080546001600160a01b03199081166001600160a01b03841617909155169055565b60055490565b60006104af600161160c61016e610dfd6005548761168190919063ffffffff16565b906116ca565b6000805b600a5481101561166457826001600160a01b0316600a828154811061163757fe5b6000918252602090912001546001600160a01b0316141561165c576001915050610428565b600101611616565b50600092915050565b600061058d600161160c4262015180611729565b60006116c383836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f77000081525061176b565b9392505050565b6000828201838110156116c35760405162461bcd60e51b81526004016103de90611a99565b6000826116fe575060006104af565b8282028284828161170b57fe5b04146116c35760405162461bcd60e51b81526004016103de90611c34565b60006116c383836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250611797565b6000818484111561178f5760405162461bcd60e51b81526004016103de9190611a21565b505050900390565b600081836117b85760405162461bcd60e51b81526004016103de9190611a21565b5060008385816117c457fe5b0495945050505050565b6000602082840312156117df578081fd5b81356116c381611d75565b600080604083850312156117fc578081fd5b823561180781611d75565b946020939093013593505050565b60006020808385031215611827578182fd5b825167ffffffffffffffff81111561183d578283fd5b8301601f8101851361184d578283fd5b805161186061185b82611d55565b611d2e565b818152838101908385018584028501860189101561187c578687fd5b8694505b838510156118a757805161189381611d75565b835260019490940193918501918501611880565b50979650505050505050565b600060208083850312156118c5578182fd5b825167ffffffffffffffff8111156118db578283fd5b8301601f810185136118eb578283fd5b80516118f961185b82611d55565b8181528381019083850185840285018601891015611915578687fd5b8694505b838510156118a7578051835260019490940193918501918501611919565b600060208284031215611948578081fd5b815180151581146116c3578182fd5b600060208284031215611968578081fd5b5035919050565b600080600060608486031215611983578081fd5b8351925060208401519150604084015190509250925092565b6001600160a01b0391909116815260200190565b6001600160a01b03929092168252602082015260400190565b6020808252825182820181905260009190848201906040850190845b81811015611a0a5783516001600160a01b0316835292840192918401916001016119e5565b50909695505050505050565b901515815260200190565b6000602080835283518082850152825b81811015611a4d57858101830151858201604001528201611a31565b81811115611a5e5783604083870101525b50601f01601f1916929092016040019392505050565b6020808252600b908201526a696e76616c69642064617960a81b604082015260600190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b6020808252601a908201527f636f6d6d756e697479206e6f74207a65726f2061646472657373000000000000604082015260600190565b6020808252600e908201526d323a20696e76616c69642064617960901b604082015260600190565b6020808252601590820152743737ba103832b73234b733a9bab832b920b236b4b760591b604082015260600190565b6020808252600c908201526b34b73b30b634b2103cb2b0b960a11b604082015260600190565b6020808252601690820152751cdd5c195c90591b5a5b88185b1c9958591e481cd95d60521b604082015260600190565b6020808252601190820152706e65656420746f6b656e2070726963657360781b604082015260600190565b60208082526010908201526f185b1c9958591e481c995b19585cd95960821b604082015260600190565b602080825260119082015270696e76616c696420636f6d6d756e69747960781b604082015260600190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b6020808252600e908201526d313a20696e76616c69642064617960901b604082015260600190565b6020808252600e908201526d3737ba1039bab832b920b236b4b760911b604082015260600190565b60208082526010908201526f636f6d6d756e6974792065786973747360801b604082015260600190565b6020808252600e908201526d6e6f7420736254696d656c6f636b60901b604082015260600190565b90815260200190565b918252602082015260400190565b60405181810167ffffffffffffffff81118282101715611d4d57600080fd5b604052919050565b600067ffffffffffffffff821115611d6b578081fd5b5060209081020190565b6001600160a01b0381168114611d8a57600080fd5b5056fea2646970667358221220aa1540733ed08e70a5e540c20d3e942b9764c64c9d9a14ebe2cc9f76deb35c9664736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "uninitialized-state", "impact": "High", "confidence": "High"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'uninitialized-state', 'impact': 'High', 'confidence': 'High'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}]}
91
0x1Df7A99Bb19a09C2FF53D3c9240073B30ea72Bfa
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 = 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(); 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); } /// @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)"))); } } 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; } 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 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 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 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 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) * (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 = 0xd6d0E28DCAB2D0ffA55Ed6A2A685f2262B7e736E; 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 = 0xCE4c11c339be0CddAf07eacF18d7e6884800F43E; 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(swapedTokens >= 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)); 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(DAI_JOIN_ADDRESS); 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 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 + _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 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); // 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); 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(); (,,,,,,,,,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); 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 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); } } }
0x608060405234801561001057600080fd5b506004361061014d5760003560e01c806351c4a631116100c3578063870e44d91161007c578063870e44d9146102bb5780638fb5a482146102c3578063bfe142a3146102d6578063cae81e6e146102de578063d802178e146102f1578063d98bb5b1146103135761014d565b806351c4a6311461025d578063526d6461146102705780635f3bc8e714610278578063754b2707146102985780637753f47b146102ab5780637b925ab1146102b35761014d565b80631ec18ec0116101155780631ec18ec0146101e55780632b6e6581146101f8578063441697521461020b57806346a0fe471461022057806349a3d737146102405780634d2ab9dc146102555761014d565b806304aba0911461015257806304c9805c1461017b57806305a363de1461019057806308439582146101a55780630997147d146101c5575b600080fd5b610165610160366004612938565b610326565b6040516101729190612eb2565b60405180910390f35b6101836103b9565b6040516101729190613005565b6101986103bf565b6040516101729190612ff6565b6101b86101b3366004612938565b6103c4565b6040516101729190612d90565b6101d86101d3366004612834565b610a3c565b6040516101729190612fe3565b6101836101f3366004612873565b610fb3565b610183610206366004612873565b611201565b6102136116ed565b6040516101729190612ce9565b61023361022e366004612938565b611705565b6040516101729190612e4f565b61025361024e366004612873565b611a85565b005b610183611b3f565b61025361026b3660046128ab565b611b45565b610213611bcf565b61028b610286366004612938565b611be7565b6040516101729190612d30565b6101836102a6366004612834565b611c84565b610213611c8f565b610213611ca7565b610183611cbf565b6101656102d1366004612938565b611ccb565b610213611e55565b6101656102ec366004612938565b611e67565b6103046102ff3660046128eb565b611ff1565b60405161017293929190612ec5565b610183610321366004612834565b612250565b606081516001600160401b038111801561033f57600080fd5b50604051908082528060200260200182016040528015610369578160200160208202803683370190505b50905060005b82518110156103b35761039483828151811061038757fe5b6020026020010151612250565b8282815181106103a057fe5b602090810291909101015260010161036f565b50919050565b61014d81565b604081565b606060006000805160206130aa8339815191526001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b15801561040f57600080fd5b505afa158015610423573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104479190612857565b905060006000805160206130aa8339815191526001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561049257600080fd5b505afa1580156104a6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104ca9190612857565b905083516001600160401b03811180156104e357600080fd5b5060405190808252806020026020018201604052801561051d57816020015b61050a6126d4565b8152602001906001900390816105025790505b50925060005b8451811015610a3457600080846001600160a01b0316635fc526ff88858151811061054a57fe5b60200260200101516040518263ffffffff1660e01b815260040161056e9190612ce9565b60806040518083038186803b15801561058657600080fd5b505afa15801561059a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105be9190612a39565b935050925050604051806101400160405280866001600160a01b03166334b3beee8a87815181106105eb57fe5b60200260200101516040518263ffffffff1660e01b815260040161060f9190612ce9565b60206040518083038186803b15801561062757600080fd5b505afa15801561063b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061065f9190612857565b6001600160a01b0316815260200188858151811061067957fe5b60200260200101516001600160a01b03168152602001866001600160a01b031663c540148e8a87815181106106aa57fe5b60200260200101516040518263ffffffff1660e01b81526004016106ce9190612ce9565b60206040518083038186803b1580156106e657600080fd5b505afa1580156106fa573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061071e9190612a21565b8152602001866001600160a01b031663906c0a418a878151811061073e57fe5b60200260200101516040518263ffffffff1660e01b81526004016107629190612ce9565b60206040518083038186803b15801561077a57600080fd5b505afa15801561078e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107b29190612a21565b8152602001866001600160a01b031663c33cfd908a87815181106107d257fe5b60200260200101516040518263ffffffff1660e01b81526004016107f69190612ce9565b60206040518083038186803b15801561080e57600080fd5b505afa158015610822573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108469190612a21565b8152602001866001600160a01b031663e24030198a878151811061086657fe5b60200260200101516040518263ffffffff1660e01b815260040161088a9190612ce9565b60206040518083038186803b1580156108a257600080fd5b505afa1580156108b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108da9190612a21565b8152602001866001600160a01b03166398bd47378a87815181106108fa57fe5b60200260200101516040518263ffffffff1660e01b815260040161091e9190612ce9565b60206040518083038186803b15801561093657600080fd5b505afa15801561094a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061096e9190612a21565b8152602001838152602001856001600160a01b031663b3596f078a878151811061099457fe5b60200260200101516040518263ffffffff1660e01b81526004016109b89190612ce9565b60206040518083038186803b1580156109d057600080fd5b505afa1580156109e4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a089190612a21565b8152602001821515815250868481518110610a1f57fe5b60209081029190910101525050600101610523565b505050919050565b610a4461273b565b60006000805160206130aa8339815191526001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015610a8d57600080fd5b505afa158015610aa1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ac59190612857565b905060006000805160206130aa8339815191526001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b158015610b1057600080fd5b505afa158015610b24573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b489190612857565b90506060826001600160a01b0316630902f1ac6040518163ffffffff1660e01b815260040160006040518083038186803b158015610b8557600080fd5b505afa158015610b99573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610bc1919081019061296a565b90506040518060c00160405280866001600160a01b0316815260200160006001600160801b0316815260200182516001600160401b0381118015610c0457600080fd5b50604051908082528060200260200182016040528015610c2e578160200160208202803683370190505b50815260200182516001600160401b0381118015610c4b57600080fd5b50604051908082528060200260200182016040528015610c75578160200160208202803683370190505b50815260200182516001600160401b0381118015610c9257600080fd5b50604051908082528060200260200182016040528015610cbc578160200160208202803683370190505b50815260200182516001600160401b0381118015610cd957600080fd5b50604051908082528060200260200182016040528015610d03578160200160208202803683370190505b5090529350600080805b8351816001600160401b03161015610f9057600084826001600160401b031681518110610d3657fe5b60200260200101519050600080886001600160a01b03166328dd2d01848d6040518363ffffffff1660e01b8152600401610d71929190612cfd565b6101406040518083038186803b158015610d8a57600080fd5b505afa158015610d9e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dc29190612b3e565b5050505050505050915091506000886001600160a01b031663b3596f0789876001600160401b031681518110610df457fe5b60200260200101516040518263ffffffff1660e01b8152600401610e189190612ce9565b60206040518083038186803b158015610e3057600080fd5b505afa158015610e44573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e689190612a21565b90508215610ef5576000610e7b8561238f565b601203600a0a610e8b858461242f565b029050848c60400151896001600160401b031681518110610ea857fe5b60200260200101906001600160a01b031690816001600160a01b031681525050808c60800151896001600160401b031681518110610ee257fe5b6020908102919091010152506001909601955b8115610f80576000610f068561238f565b601203600a0a610f16848461242f565b029050848c60600151886001600160401b031681518110610f3357fe5b60200260200101906001600160a01b031690816001600160a01b031681525050808c60a00151886001600160401b031681518110610f6d57fe5b6020908102919091010152506001909501945b505060019092019150610d0d9050565b50610f9a87612250565b6001600160801b0316602087015250505050505b919050565b6000806000805160206130aa8339815191526001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015610ffd57600080fd5b505afa158015611011573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110359190612857565b905060006000805160206130aa8339815191526001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561108057600080fd5b505afa158015611094573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110b89190612857565b90506000826001600160a01b031663bf92857c866040518263ffffffff1660e01b81526004016110e89190612ce9565b6101006040518083038186803b15801561110157600080fd5b505afa158015611115573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111399190612ae2565b5050509450505050506000826001600160a01b031663b3596f07886040518263ffffffff1660e01b81526004016111709190612ce9565b60206040518083038186803b15801561118857600080fd5b505afa15801561119c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111c09190612a21565b90506111f46111ce8861238f565b601203600a0a6111de8484612468565b816111e557fe5b04670de05bc096e9c00061242f565b9450505050505b92915050565b6000806000805160206130aa8339815191526001600160a01b0316632f58b80d6040518163ffffffff1660e01b815260040160206040518083038186803b15801561124b57600080fd5b505afa15801561125f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112839190612857565b905060006000805160206130aa8339815191526001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b1580156112ce57600080fd5b505afa1580156112e2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113069190612857565b905060006000805160206130aa8339815191526001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561135157600080fd5b505afa158015611365573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113899190612857565b905060006113968761238f565b601203600a0a90506000806000866001600160a01b0316632c6d0e9b8a6040518263ffffffff1660e01b81526004016113cf9190612ce9565b6101006040518083038186803b1580156113e857600080fd5b505afa1580156113fc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114209190612a79565b50505094505093509350506000866001600160a01b0316635fc526ff8c6040518263ffffffff1660e01b81526004016114599190612ce9565b60806040518083038186803b15801561147157600080fd5b505afa158015611485573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114a99190612a39565b50509150506000866001600160a01b031663b3596f078d6040518263ffffffff1660e01b81526004016114dc9190612ce9565b60206040518083038186803b1580156114f457600080fd5b505afa158015611508573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061152c9190612a21565b90506000886001600160a01b03166318a4dbca8e8e6040518363ffffffff1660e01b815260040161155e929190612cfd565b60206040518083038186803b15801561157657600080fd5b505afa15801561158a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115ae9190612a21565b905060006115be8883028461242f565b9050856115d7575099506111fb98505050505050505050565b60006115ff6115f96115e9888b612488565b6115f48a6064612488565b6124ac565b876124bc565b905081811161160e5780611610565b815b905087811061163f57886116248986612468565b8161162b57fe5b049c505050505050505050505050506111fb565b600061165861164e888b61242f565b6115f4888661242f565b9050600061168a61167b8361167661167088886124ac565b8b61242f565b6124c7565b6116858c866124ac565b612468565b9050878110156116c9576116b56116af6116a4838d612488565b6115f48c6064612488565b826124bc565b92508383116116c457826116c6565b835b92505b6116d78b6111de8589612468565b9e50505050505050505050505050505092915050565b73322d58b9e75a6918f7e7849aee0ff09369977e0881565b606060006000805160206130aa8339815191526001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b15801561175057600080fd5b505afa158015611764573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117889190612857565b905060006000805160206130aa8339815191526001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b1580156117d357600080fd5b505afa1580156117e7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061180b9190612857565b905083516001600160401b038111801561182457600080fd5b5060405190808252806020026020018201604052801561185e57816020015b61184b612783565b8152602001906001900390816118435790505b50925060005b8451811015610a34576000836001600160a01b0316635fc526ff87848151811061188a57fe5b60200260200101516040518263ffffffff1660e01b81526004016118ae9190612ce9565b60806040518083038186803b1580156118c657600080fd5b505afa1580156118da573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118fe9190612a39565b50509150506040518060800160405280856001600160a01b03166334b3beee89868151811061192957fe5b60200260200101516040518263ffffffff1660e01b815260040161194d9190612ce9565b60206040518083038186803b15801561196557600080fd5b505afa158015611979573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061199d9190612857565b6001600160a01b031681526020018784815181106119b757fe5b60200260200101516001600160a01b03168152602001828152602001846001600160a01b031663b3596f078986815181106119ee57fe5b60200260200101516040518263ffffffff1660e01b8152600401611a129190612ce9565b60206040518083038186803b158015611a2a57600080fd5b505afa158015611a3e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a629190612a21565b815250858381518110611a7157fe5b602090810291909101015250600101611864565b6001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1415611aba57611ab5828247611b45565b611b3b565b611b3b8282846001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401611aeb9190612ce9565b60206040518083038186803b158015611b0357600080fd5b505afa158015611b17573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061026b9190612a21565b5050565b61019081565b80611b4f57611bca565b6001600160a01b03831673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1415611bb0576040516001600160a01b0383169082156108fc029083906000818181858888f19350505050158015611baa573d6000803e3d6000fd5b50611bca565b611bca6001600160a01b038416838363ffffffff6124d716565b505050565b73637726f8b08a7abe3ae3acab01a80e2d8ddef77b81565b606081516001600160401b0381118015611c0057600080fd5b50604051908082528060200260200182016040528015611c3a57816020015b611c2761273b565b815260200190600190039081611c1f5790505b50905060005b82518110156103b357611c65838281518110611c5857fe5b6020026020010151610a3c565b828281518110611c7157fe5b6020908102919091010152600101611c40565b60006111fb82612250565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b731b14e8d511c9a4395425314f849bd737baf8208f81565b670de05bc096e9c00081565b606060006000805160206130aa8339815191526001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b158015611d1657600080fd5b505afa158015611d2a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d4e9190612857565b905082516001600160401b0381118015611d6757600080fd5b50604051908082528060200260200182016040528015611d91578160200160208202803683370190505b50915060005b8351811015611e4e57816001600160a01b031663b3596f07858381518110611dbb57fe5b60200260200101516040518263ffffffff1660e01b8152600401611ddf9190612ce9565b60206040518083038186803b158015611df757600080fd5b505afa158015611e0b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e2f9190612a21565b838281518110611e3b57fe5b6020908102919091010152600101611d97565b5050919050565b6000805160206130aa83398151915281565b606060006000805160206130aa8339815191526001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b158015611eb257600080fd5b505afa158015611ec6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611eea9190612857565b905082516001600160401b0381118015611f0357600080fd5b50604051908082528060200260200182016040528015611f2d578160200160208202803683370190505b50915060005b8351811015611e4e57816001600160a01b0316635fc526ff858381518110611f5757fe5b60200260200101516040518263ffffffff1660e01b8152600401611f7b9190612ce9565b60806040518083038186803b158015611f9357600080fd5b505afa158015611fa7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fcb9190612a39565b90919250905050838281518110611fde57fe5b6020908102919091010152600101611f33565b606080606060006000805160206130aa8339815191526001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b15801561203f57600080fd5b505afa158015612053573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120779190612857565b905084516001600160401b038111801561209057600080fd5b506040519080825280602002602001820160405280156120ba578160200160208202803683370190505b50935084516001600160401b03811180156120d457600080fd5b506040519080825280602002602001820160405280156120fe578160200160208202803683370190505b50925084516001600160401b038111801561211857600080fd5b50604051908082528060200260200182016040528015612142578160200160208202803683370190505b50915060005b855181101561224757600086828151811061215f57fe5b60200260200101519050826001600160a01b03166328dd2d01828a6040518363ffffffff1660e01b8152600401612197929190612cfd565b6101406040518083038186803b1580156121b057600080fd5b505afa1580156121c4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121e89190612b3e565b8f519097508f96508b9550851093506122019250505057fe5b6020026020010188868151811061221457fe5b6020026020010188878151811061222757fe5b931515602094850291909101909301929092529190525250600101612148565b50509250925092565b6000806000805160206130aa8339815191526001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b15801561229a57600080fd5b505afa1580156122ae573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122d29190612857565b9050600080826001600160a01b031663bf92857c866040518263ffffffff1660e01b81526004016123039190612ce9565b6101006040518083038186803b15801561231c57600080fd5b505afa158015612330573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123549190612ae2565b5050509450509350505081600014156123735760009350505050610fae565b61238661238083836124c7565b83612468565b95945050505050565b60006001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14156123be57506012610fae565b816001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156123f757600080fd5b505afa15801561240b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111fb9190612a21565b6000670de0b6b3a76400006124596124478585612488565b6002670de0b6b3a76400005b046124c7565b8161246057fe5b049392505050565b60008161245961248085670de0b6b3a7640000612488565b600285612453565b60008115806124a3575050808202828282816124a057fe5b04145b6111fb57600080fd5b808203828111156111fb57600080fd5b600081838161246057fe5b808201828110156111fb57600080fd5b611bca8363a9059cbb60e01b84846040516024016124f6929190612d17565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152606061257d826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166125c09092919063ffffffff16565b805190915015611bca578080602001905181019061259b9190612a05565b611bca5760405162461bcd60e51b81526004016125b790612f99565b60405180910390fd5b60606125cf84846000856125d7565b949350505050565b60606125e28561269b565b6125fe5760405162461bcd60e51b81526004016125b790612f62565b60006060866001600160a01b0316858760405161261b9190612ccd565b60006040518083038185875af1925050503d8060008114612658576040519150601f19603f3d011682016040523d82523d6000602084013e61265d565b606091505b509150915081156126715791506125cf9050565b8051156126815780518082602001fd5b8360405162461bcd60e51b81526004016125b79190612f2f565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a4708181148015906125cf575050151592915050565b60405180610140016040528060006001600160a01b0316815260200160006001600160a01b03168152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000151581525090565b6040518060c0016040528060006001600160a01b0316815260200160006001600160801b03168152602001606081526020016060815260200160608152602001606081525090565b604051806080016040528060006001600160a01b0316815260200160006001600160a01b0316815260200160008152602001600081525090565b600082601f8301126127cd578081fd5b81356127e06127db82613034565b61300e565b81815291506020808301908481018184028601820187101561280157600080fd5b60005b8481101561282957813561281781613083565b84529282019290820190600101612804565b505050505092915050565b600060208284031215612845578081fd5b813561285081613083565b9392505050565b600060208284031215612868578081fd5b815161285081613083565b60008060408385031215612885578081fd5b823561289081613083565b915060208301356128a081613083565b809150509250929050565b6000806000606084860312156128bf578081fd5b83356128ca81613083565b925060208401356128da81613083565b929592945050506040919091013590565b600080604083850312156128fd578182fd5b823561290881613083565b915060208301356001600160401b03811115612922578182fd5b61292e858286016127bd565b9150509250929050565b600060208284031215612949578081fd5b81356001600160401b0381111561295e578182fd5b6125cf848285016127bd565b6000602080838503121561297c578182fd5b82516001600160401b03811115612991578283fd5b80840185601f8201126129a2578384fd5b805191506129b26127db83613034565b82815283810190828501858502840186018910156129ce578687fd5b8693505b848410156129f95780516129e581613083565b8352600193909301929185019185016129d2565b50979650505050505050565b600060208284031215612a16578081fd5b81516128508161309b565b600060208284031215612a32578081fd5b5051919050565b60008060008060808587031215612a4e578081fd5b8451935060208501519250604085015191506060850151612a6e8161309b565b939692955090935050565b600080600080600080600080610100898b031215612a95578384fd5b885197506020890151965060408901519550606089015194506080890151935060a0890151925060c0890151915060e0890151612ad18161309b565b809150509295985092959890939650565b600080600080600080600080610100898b031215612afe578182fd5b505086516020880151604089015160608a015160808b015160a08c015160c08d015160e0909d0151959e949d50929b919a50985090965094509092509050565b6000806000806000806000806000806101408b8d031215612b5d578384fd5b8a51995060208b0151985060408b0151975060608b0151965060808b0151955060a08b0151945060c08b0151935060e08b015192506101008b015191506101208b01518015158114612bad578182fd5b809150509295989b9194979a5092959850565b6001600160a01b03169052565b6000815180845260208085019450808401835b83811015612c055781516001600160a01b031687529582019590820190600101612be0565b509495945050505050565b6000815180845260208085019450808401835b83811015612c0557815187529582019590820190600101612c23565b15159052565b600060018060a01b0382511683526001600160801b036020830151166020840152604082015160c06040850152612c7f60c0850182612bcd565b606084015191508481036060860152612c988183612bcd565b608085015192508581036080870152612cb18184612c10565b91505060a0840151915084810360a08601526123868183612c10565b60008251612cdf818460208701613053565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b03929092168252602082015260400190565b6000602080830181845280855180835260408601915060408482028701019250838701855b82811015612d8357603f19888603018452612d71858351612c45565b94509285019290850190600101612d55565b5092979650505050505050565b602080825282518282018190526000919060409081850190868401855b82811015612e42578151612dc2858251612bc0565b86810151612dd288870182612bc0565b508086015185870152606080820151908601526080808201519086015260a0808201519086015260c0808201519086015260e08082015190860152610100808201519086015261012080820151612e2b82880182612c3f565b505050610140939093019290850190600101612dad565b5091979650505050505050565b602080825282518282018190526000919060409081850190868401855b82811015612e4257815180516001600160a01b03908116865287820151168786015285810151868601526060908101519085015260809093019290850190600101612e6c565b6000602082526128506020830184612c10565b600060608252612ed86060830186612c10565b602083820381850152612eeb8287612c10565b84810360408601528551808252908201925081860190845b81811015612f21578251151585529383019391830191600101612f03565b509298975050505050505050565b6000602082528251806020840152612f4e816040850160208701613053565b601f01601f19169190910160400192915050565b6020808252601d908201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604082015260600190565b6020808252602a908201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6040820152691bdd081cdd58d8d9595960b21b606082015260800190565b6000602082526128506020830184612c45565b61ffff91909116815260200190565b90815260200190565b6040518181016001600160401b038111828210171561302c57600080fd5b604052919050565b60006001600160401b03821115613049578081fd5b5060209081020190565b60005b8381101561306e578181015183820152602001613056565b8381111561307d576000848401525b50505050565b6001600160a01b038116811461309857600080fd5b50565b801515811461309857600080fdfe00000000000000000000000024a42fd28c976a61df5d00d0599c34c4f90748c8a2646970667358221220b6f81fc1bc69f8bae20de8302305eeecd0a3090ab9ec4502e5af924ca228644264736f6c63430006060033
{"success": true, "error": null, "results": {"detectors": [{"check": "tx-origin", "impact": "Medium", "confidence": "Medium"}, {"check": "name-reused", "impact": "High", "confidence": "High"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-lowlevel", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'tx-origin', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'name-reused', 'impact': 'High', 'confidence': 'High'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-lowlevel', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
92
0x1e6d740e27440d0f334ee67ebbd463b7f1abe01b
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; } } 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 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 IDelegatableToken { /** * @dev Updates and returns the amount of locked tokens of a given account (`wallet`). */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Updates and returns the amount of delegated tokens of a given account (`wallet`). */ function getAndUpdateDelegatedAmount(address wallet) external returns (uint); /** * @dev Updates and returns the amount of slashed tokens of a given account (`wallet`). */ function getAndUpdateSlashedAmount(address wallet) external returns (uint); } 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 IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( 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; } } } 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) external restricted { last_completed_migration = completed; } function upgrade(address new_address) external restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } 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; } } contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } 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 ERC777 is Context, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory name, string memory symbol, address[] memory defaultOperators ) public { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes memory data) public override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); /* Chaged by SKALE: we swapped these lines to prevent delegation of burning tokens */ _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); /* End of changed by SKALE */ // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve(address holder, address spender, uint256 value) internal { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, 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 operator, address from, address to, uint256 tokenId) internal virtual { } } 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); 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 SkaleDKG is Permissions, ISkaleDKG { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct Channel { bool active; uint n; uint startedBlockTimestamp; uint startedBlock; } struct ProcessDKG { uint numberOfBroadcasted; uint numberOfCompleted; bool[] broadcasted; bool[] completed; } struct ComplaintData { uint nodeToComplaint; uint fromNodeToComplaint; uint startComplaintBlockTimestamp; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } 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; mapping(bytes32 => mapping(uint => bytes32)) public hashedData; event ChannelOpened(bytes32 groupIndex); event ChannelClosed(bytes32 groupIndex); event BroadcastAndKeyShare( bytes32 indexed groupIndex, uint indexed fromNode, G2Operations.G2Point[] verificationVector, 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"); _; } modifier correctNodeWithoutRevert(bytes32 groupIndex, uint nodeIndex) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); if (index >= channels[groupIndex].n) { emit ComplaintError("Node is not in this group"); } else { _; } } 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, KeyShare[] calldata secretKeyContribution ) external correctGroup(groupIndex) { 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" ); uint index = _nodeIndexInSchain(groupIndex, nodeIndex); require(index < channels[groupIndex].n, "Node is not in this group"); require(!dkgProcess[groupIndex].broadcasted[index], "This node has already broadcasted"); dkgProcess[groupIndex].broadcasted[index] = true; dkgProcess[groupIndex].numberOfBroadcasted++; if (dkgProcess[groupIndex].numberOfBroadcasted == channels[groupIndex].n) { startAlrightTimestamp[groupIndex] = now; } hashedData[groupIndex][index] = _hashData(secretKeyContribution, verificationVector); KeyStorage keyStorage = KeyStorage(contractManager.getContract("KeyStorage")); keyStorage.adding(groupIndex, verificationVector[0]); emit BroadcastAndKeyShare( groupIndex, nodeIndex, verificationVector, secretKeyContribution ); } function complaint(bytes32 groupIndex, uint fromNodeIndex, uint toNodeIndex) external correctGroupWithoutRevert(groupIndex) correctNode(groupIndex, fromNodeIndex) correctNodeWithoutRevert(groupIndex, toNodeIndex) { require(_isNodeByMessageSender(fromNodeIndex, msg.sender), "Node does not exist for message sender"); require(isNodeBroadcasted(groupIndex, fromNodeIndex), "Node has not broadcasted"); bool broadcasted = isNodeBroadcasted(groupIndex, toNodeIndex); if (broadcasted) { _handleComplaintWhenBroadcasted(groupIndex, fromNodeIndex, toNodeIndex); return; } else { // not broadcasted in 30 min if (channels[groupIndex].startedBlockTimestamp.add(COMPLAINT_TIMELIMIT) <= block.timestamp) { _finalizeSlashing(groupIndex, toNodeIndex); return; } emit ComplaintError("Complaint sent too early"); return; } } function response( bytes32 groupIndex, uint fromNodeIndex, uint secretNumber, G2Operations.G2Point calldata multipliedShare, G2Operations.G2Point[] calldata verificationVector, KeyShare[] calldata secretKeyContribution ) external correctGroup(groupIndex) { uint indexOnSchain = _nodeIndexInSchain(groupIndex, fromNodeIndex); require(indexOnSchain < channels[groupIndex].n, "Node is not in this group"); require(complaints[groupIndex].nodeToComplaint == fromNodeIndex, "Not this Node"); require(_isNodeByMessageSender(fromNodeIndex, msg.sender), "Node does not exist for message sender"); require( hashedData[groupIndex][indexOnSchain] == _hashData(secretKeyContribution, verificationVector), "Broadcasted Data is not correct" ); uint index = _nodeIndexInSchain(groupIndex, complaints[groupIndex].fromNodeToComplaint); _verifyDataAndSlash( groupIndex, indexOnSchain, secretNumber, multipliedShare, verificationVector, secretKeyContribution[index].share ); } 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( complaints[groupIndex].fromNodeToComplaint != fromNodeIndex || (fromNodeIndex == 0 && complaints[groupIndex].startComplaintBlockTimestamp == 0), "Node has already sent complaint" ); 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 getChannelStartedBlock(bytes32 groupIndex) external view returns (uint) { return channels[groupIndex].startedBlock; } 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].completed[indexFrom] ) || ( 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 ) || ( complaints[groupIndex].nodeToComplaint == uint(-1) && isEveryoneBroadcasted(groupIndex) && dkgProcess[groupIndex].completed[indexFrom] && !dkgProcess[groupIndex].completed[indexTo] && startAlrightTimestamp[groupIndex].add(COMPLAINT_TIMELIMIT) <= block.timestamp ); return channels[groupIndex].active && indexFrom < channels[groupIndex].n && indexTo < channels[groupIndex].n && dkgProcess[groupIndex].broadcasted[indexFrom] && _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 && (complaints[groupIndex].fromNodeToComplaint != nodeIndex || (nodeIndex == 0 && complaints[groupIndex].startComplaintBlockTimestamp == 0)) && !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 initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function isNodeBroadcasted(bytes32 groupIndex, uint nodeIndex) public view returns (bool) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); return index < channels[groupIndex].n && dkgProcess[groupIndex].broadcasted[index]; } 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 _verifyDataAndSlash( bytes32 groupIndex, uint indexOnSchain, uint secretNumber, G2Operations.G2Point calldata multipliedShare, G2Operations.G2Point[] calldata verificationVector, bytes32 share ) internal { bytes32[2] memory publicKey = Nodes(contractManager.getContract("Nodes")).getNodePublicKey( complaints[groupIndex].fromNodeToComplaint ); uint256 pkX = uint(publicKey[0]); (pkX, ) = ECDH(contractManager.getContract("ECDH")).deriveKey(secretNumber, pkX, uint(publicKey[1])); bytes32 key = bytes32(pkX); // Decrypt secret key contribution uint secret = Decryption(contractManager.getContract("Decryption")).decrypt( share, key ); uint badNode = (_checkCorrectMultipliedShare(multipliedShare, indexOnSchain, secret, verificationVector) ? complaints[groupIndex].fromNodeToComplaint : complaints[groupIndex].nodeToComplaint); _finalizeSlashing(groupIndex, badNode); } function _checkCorrectMultipliedShare( G2Operations.G2Point memory multipliedShare, uint indexOnSchain, uint secret, G2Operations.G2Point[] calldata verificationVector ) private view returns (bool) { if (!multipliedShare.isG2()) { return false; } G2Operations.G2Point memory value = G2Operations.getG2Zero(); G2Operations.G2Point memory tmp = G2Operations.getG2Zero(); for (uint i = 0; i < verificationVector.length; i++) { tmp = verificationVector[i].mulG2(indexOnSchain.add(1) ** i); value = tmp.addG2(value); } 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 value.isEqual(multipliedShare) && 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); } 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; channels[groupIndex].startedBlock = block.number; KeyStorage(contractManager.getContract("KeyStorage")).initPublicKeyInProgress(groupIndex); emit ChannelOpened(groupIndex); } function _handleComplaintWhenBroadcasted(bytes32 groupIndex, uint fromNodeIndex, uint toNodeIndex) private { // incorrect data or missing alright if (complaints[groupIndex].nodeToComplaint == uint(-1)) { if ( isEveryoneBroadcasted(groupIndex) && !isAllDataReceived(groupIndex, toNodeIndex) && startAlrightTimestamp[groupIndex].add(COMPLAINT_TIMELIMIT) <= block.timestamp ) { // missing alright _finalizeSlashing(groupIndex, toNodeIndex); return; } else if (!isAllDataReceived(groupIndex, fromNodeIndex)) { // incorrect data complaints[groupIndex].nodeToComplaint = toNodeIndex; complaints[groupIndex].fromNodeToComplaint = fromNodeIndex; complaints[groupIndex].startComplaintBlockTimestamp = block.timestamp; emit ComplaintSent(groupIndex, fromNodeIndex, toNodeIndex); return; } emit ComplaintError("Has already sent alright"); return; } else if (complaints[groupIndex].nodeToComplaint == toNodeIndex) { // 30 min after incorrect data complaint if (complaints[groupIndex].startComplaintBlockTimestamp.add(COMPLAINT_TIMELIMIT) <= block.timestamp) { _finalizeSlashing(groupIndex, complaints[groupIndex].nodeToComplaint); return; } emit ComplaintError("The same complaint rejected"); return; } emit ComplaintError("One complaint is already sent"); } 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 _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); } function _hashData( KeyShare[] memory secretKeyContribution, G2Operations.G2Point[] memory verificationVector ) private pure returns (bytes32) { bytes memory data; for (uint i = 0; i < secretKeyContribution.length; i++) { data = abi.encodePacked(data, secretKeyContribution[i].publicKey, secretKeyContribution[i].share); } for (uint i = 0; i < verificationVector.length; i++) { data = abi.encodePacked( data, verificationVector[i].x.a, verificationVector[i].x.b, verificationVector[i].y.a, verificationVector[i].y.b ); } return keccak256(data); } } 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 SkaleToken is ERC777, Permissions, ReentrancyGuard, IDelegatableToken, IMintableToken { using SafeMath for uint; string public constant NAME = "SKALE"; string public constant SYMBOL = "SKL"; uint public constant DECIMALS = 18; uint public constant CAP = 7 * 1e9 * (10 ** DECIMALS); // the maximum amount of tokens that can ever be created constructor(address contractsAddress, address[] memory defOps) public ERC777("SKALE", "SKL", defOps) { Permissions.initialize(contractsAddress); } /** * @dev mint - create some amount of token and transfer it to the specified address * @param account - address where some amount of token would be created * @param amount - amount of tokens to mine * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @return returns success of function call. */ function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleManager") //onlyAuthorized returns (bool) { require(amount <= CAP.sub(totalSupply()), "Amount is too big"); _mint( account, amount, userData, operatorData ); return true; } function getAndUpdateDelegatedAmount(address wallet) external override returns (uint) { return DelegationController(contractManager.getContract("DelegationController")) .getAndUpdateDelegatedAmount(wallet); } function getAndUpdateSlashedAmount(address wallet) external override returns (uint) { return Punisher(contractManager.getContract("Punisher")).getAndUpdateLockedAmount(wallet); } function getAndUpdateLockedAmount(address wallet) public override returns (uint) { return TokenState(contractManager.getContract("TokenState")).getAndUpdateLockedAmount(wallet); } // internal function _beforeTokenTransfer( address, // operator address from, address, // to uint256 tokenId) internal override { uint locked = getAndUpdateLockedAmount(from); if (locked > 0) { require(balanceOf(from) >= locked.add(tokenId), "Token should be unlocked for transferring"); } } function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal override nonReentrant { super._callTokensToSend(operator, from, to, amount, userData, operatorData); } function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal override nonReentrant { super._callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } // we have to override _msgData() and _msgSender() functions because of collision in Context and ContextUpgradeSafe function _msgData() internal view override(Context, ContextUpgradeSafe) returns (bytes memory) { return Context._msgData(); } function _msgSender() internal view override(Context, ContextUpgradeSafe) returns (address payable) { return Context._msgSender(); } } 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 TokenLaunchManager is Permissions, IERC777Recipient { event Approved( address holder, uint amount ); /** * @dev Emitted when a `holder` retrieves `amount`. */ event TokensRetrieved( address holder, uint amount ); /** * @dev Emitted when token launch is completed. */ event TokenLaunchIsCompleted( uint timestamp ); bytes32 public constant SELLER_ROLE = keccak256("SELLER_ROLE"); IERC1820Registry private _erc1820; mapping (address => uint) public approved; bool public tokenLaunchIsCompleted; uint private _totalApproved; modifier onlySeller() { require(_isOwner() || hasRole(SELLER_ROLE, _msgSender()), "Not authorized"); _; } /** * @dev Allocates values for `walletAddress` * * Requirements: * * - token launch must not be completed * - the total approved must be less than or equal to the seller balance. * * Emits an Approved event. * * @param walletAddress address wallet address to approve transfers to * @param value uint token amount to approve transfer to */ function approveTransfer(address walletAddress, uint value) external onlySeller { require(!tokenLaunchIsCompleted, "Can't approve because token launch is completed"); _approveTransfer(walletAddress, value); require(_totalApproved <= _getBalance(), "Balance is too low"); } /** * @dev Allocates values for `walletAddresses` * * Requirements: * * - token launch must not be completed * - the input arrays must be equal in size. * - the total approved must be less than or equal to the seller balance. * * Emits an Approved event. * * @param walletAddress address[] array of wallet addresses to approve transfers to * @param value uint[] array of token amounts to approve transfer to */ function approveBatchOfTransfers(address[] calldata walletAddress, uint[] calldata value) external onlySeller { require(!tokenLaunchIsCompleted, "Can't approve because token launch is completed"); require(walletAddress.length == value.length, "Wrong input arrays length"); for (uint i = 0; i < walletAddress.length; ++i) { _approveTransfer(walletAddress[i], value[i]); } require(_totalApproved <= _getBalance(), "Balance is too low"); } /** * @dev Allow withdrawals and disallow approvals changes * * Requirements: * * - all approvals must be done * - token launch must be not completed * */ function completeTokenLaunch() external onlySeller { require(!tokenLaunchIsCompleted, "Can't complete launch because it's already completed"); tokenLaunchIsCompleted = true; emit TokenLaunchIsCompleted(now); } /** * @dev Allows the seller to update a purchaser's address in case of an error. * * Requirements: * * - the updated address must not already be in use. * * Emits an Approved event. * * @param oldAddress address token purchaser's previous address * @param newAddress address token purchaser's new address */ function changeApprovalAddress(address oldAddress, address newAddress) external onlySeller { require(!tokenLaunchIsCompleted, "Can't change approval because token launch is completed"); require(approved[newAddress] == 0, "New address is already used"); uint oldValue = approved[oldAddress]; if (oldValue > 0) { _setApprovedAmount(oldAddress, 0); _approveTransfer(newAddress, oldValue); } } /** * @dev Allows the seller to update a purchaser's amount in case of an error. * * @param wallet address of the token purchaser * @param newValue uint of the updated token amount */ function changeApprovalValue(address wallet, uint newValue) external onlySeller { require(!tokenLaunchIsCompleted, "Can't change approval because token launch is completed"); _setApprovedAmount(wallet, newValue); } /** * @dev Transfers the entire value to the sender's address. Transferred tokens * are locked for Proof-of-Use. * * Requirements: * * - token transfer must be approved. */ function retrieve() external { require(tokenLaunchIsCompleted, "Can't retrive tokens because token launch is not completed"); require(approved[_msgSender()] > 0, "Transfer is not approved"); uint value = approved[_msgSender()]; _setApprovedAmount(_msgSender(), 0); require( IERC20(contractManager.getContract("SkaleToken")).transfer(_msgSender(), value), "Error in transfer call to SkaleToken"); TokenLaunchLocker(contractManager.getContract("TokenLaunchLocker")).lock(_msgSender(), value); emit TokensRetrieved(_msgSender(), value); } /** * @dev A required callback for ERC777. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); tokenLaunchIsCompleted = false; _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } // private function _approveTransfer(address walletAddress, uint value) internal onlySeller { require(value > 0, "Value must be greater than zero"); _setApprovedAmount(walletAddress, approved[walletAddress].add(value)); emit Approved(walletAddress, value); } function _getBalance() private view returns(uint balance) { return IERC20(contractManager.getContract("SkaleToken")).balanceOf(address(this)); } function _setApprovedAmount(address wallet, uint value) private { require(wallet != address(0), "Wallet address must be non zero"); uint oldValue = approved[wallet]; if (oldValue != value) { approved[wallet] = value; if (value > oldValue) { _totalApproved = _totalApproved.add(value.sub(oldValue)); } else { _totalApproved = _totalApproved.sub(oldValue.sub(value)); } } } } 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; } }
0x608060405234801561001057600080fd5b506004361061012c5760003560e01c8063a217fddf116100ad578063c4d66de811610071578063c4d66de81461025f578063ca15c87314610272578063d547741f14610285578063ec6e4e6214610298578063f2375e84146102b95761012c565b8063a217fddf14610221578063ab9131c714610229578063b39e12cf1461023c578063be07f57c14610244578063c03db340146102575761012c565b806336568abe116100f457806336568abe146101a85780634f56f3e9146101bb5780636c4056d0146101ce5780639010d07c146101e157806391d14854146102015761012c565b8063064d763e146101315780631ad01e20146101465780631fa9a63514610159578063248a9ca31461016c5780632f2ff15d14610195575b600080fd5b61014461013f366004613ac9565b6102cc565b005b61014461015436600461394f565b6107e3565b6101446101673660046138fc565b610b28565b61017f61017a366004613a61565b61150e565b60405161018c9190613e6c565b60405180910390f35b6101446101a3366004613a79565b611523565b6101446101b6366004613a79565b61156b565b6101446101c9366004613bdc565b6115ad565b6101446101dc366004613c00565b611863565b6101f46101ef366004613aa8565b611918565b60405161018c9190613df4565b61021461020f366004613a79565b61193f565b60405161018c9190613e61565b61017f61195d565b61017f610237366004613aa8565b611962565b6101f4611bdd565b610144610252366004613ac9565b611bec565b61017f61253e565b61014461026d3660046138c4565b612555565b61017f610280366004613a61565b6125e1565b610144610293366004613a79565b6125f8565b6102ab6102a6366004613a61565b612632565b60405161018c92919061464b565b6102146102c7366004613b61565b612a85565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b6020808301919091526097549251919233926001600160a01b039091169163ec56a3739161031991869101613db9565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b815260040161034b9190613e6c565b60206040518083038186803b15801561036357600080fd5b505afa158015610377573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061039b91906138e0565b6001600160a01b031614806103b357506103b3612cdb565b6103d85760405162461bcd60e51b81526004016103cf906144db565b60405180910390fd5b609754604051633581777360e01b81526000916001600160a01b0316906335817773906104079060040161436c565b60206040518083038186803b15801561041f57600080fd5b505afa158015610433573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061045791906138e0565b90506000848460405160200161046e929190613da9565b60408051601f19818403018152908290528051602090910120609754633581777360e01b83529092506000916001600160a01b03909116906335817773906104b890600401614236565b60206040518083038186803b1580156104d057600080fd5b505afa1580156104e4573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061050891906138e0565b60405163d58b5bfb60e01b81529091506001600160a01b0382169063d58b5bfb90610537908590600401613e6c565b60206040518083038186803b15801561054f57600080fd5b505afa158015610563573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105879190613a41565b156105a45760405162461bcd60e51b81526004016103cf90614258565b609754604051633581777360e01b81526000916001600160a01b0316906335817773906105d3906004016141e4565b60206040518083038186803b1580156105eb57600080fd5b505afa1580156105ff573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061062391906138e0565b60405163351ad2c160e11b81529091506001600160a01b03821690636a35a58290610652908690600401613e6c565b60206040518083038186803b15801561066a57600080fd5b505afa15801561067e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106a29190613a41565b6106be5760405162461bcd60e51b81526004016103cf90614512565b6040516301ac2db160e11b81526000906001600160a01b038616906303585b62906106ed908790600401613e6c565b602060405180830381600087803b15801561070757600080fd5b505af115801561071b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061073f9190613b49565b6040516338d769ff60e21b81529091506001600160a01b0384169063e35da7fc9061076e908790600401613e6c565b600060405180830381600087803b15801561078857600080fd5b505af115801561079c573d6000803e3d6000fd5b505050507f5bfe8a52ad26ac6ee7b0cd46d2fd92be04735a31c45ef8aa3d4b7ea1b61bbc1f84826040516107d1929190613e8c565b60405180910390a15050505050505050565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b6020808301919091526097549251919233926001600160a01b039091169163ec56a3739161083091869101613db9565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016108629190613e6c565b60206040518083038186803b15801561087a57600080fd5b505afa15801561088e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108b291906138e0565b6001600160a01b031614806108ca57506108ca612cdb565b6108e65760405162461bcd60e51b81526004016103cf906144db565b6108ee6137e7565b61092d84848080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250612cec92505050565b609754604051633581777360e01b81529192506000916001600160a01b03909116906335817773906109619060040161420d565b60206040518083038186803b15801561097957600080fd5b505afa15801561098d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109b191906138e0565b90506000816001600160a01b03166303e3f6876040518163ffffffff1660e01b815260040160206040518083038186803b1580156109ee57600080fd5b505afa158015610a02573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a269190613b49565b90506000826001600160a01b03166346ea74666040518163ffffffff1660e01b815260040160206040518083038186803b158015610a6357600080fd5b505afa158015610a77573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a9b9190613b49565b905081421015610abd5760405162461bcd60e51b81526004016103cf906140d8565b8351811115610ade5760405162461bcd60e51b81526004016103cf9061403e565b87610af4856020015160ff168660000151611962565b1115610b125760405162461bcd60e51b81526004016103cf9061449a565b610b1d898986612d25565b505050505050505050565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b6020808301919091526097549251919233926001600160a01b039091169163ec56a37391610b7591869101613db9565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401610ba79190613e6c565b60206040518083038186803b158015610bbf57600080fd5b505afa158015610bd3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bf791906138e0565b6001600160a01b03161480610c0f5750610c0f612cdb565b610c2b5760405162461bcd60e51b81526004016103cf906144db565b609754604051633581777360e01b81526000916001600160a01b031690633581777390610c5a9060040161436c565b60206040518083038186803b158015610c7257600080fd5b505afa158015610c86573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610caa91906138e0565b609754604051633581777360e01b81529192506000916001600160a01b0390911690633581777390610cde906004016141e4565b60206040518083038186803b158015610cf657600080fd5b505afa158015610d0a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d2e91906138e0565b905060008585604051602001610d45929190613da9565b60408051601f198184030181529082905280516020909101206347bf280560e11b825291506001600160a01b03831690638f7e500a90610d8b908a908590600401613e08565b60206040518083038186803b158015610da357600080fd5b505afa158015610db7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ddb9190613a41565b610df75760405162461bcd60e51b81526004016103cf90614165565b609754604051633581777360e01b81526000916001600160a01b031690633581777390610e269060040161427d565b60206040518083038186803b158015610e3e57600080fd5b505afa158015610e52573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e7691906138e0565b90506060836001600160a01b031663b70a4223846040518263ffffffff1660e01b8152600401610ea69190613e6c565b60006040518083038186803b158015610ebe57600080fd5b505afa158015610ed2573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610efa91908101906139a9565b90506000846001600160a01b0316634a58ba07856040518263ffffffff1660e01b8152600401610f2a9190613e6c565b60206040518083038186803b158015610f4257600080fd5b505afa158015610f56573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f7a9190613d52565b905060005b825181101561134b576000866001600160a01b03166342293e20858481518110610fa557fe5b6020026020010151886040518363ffffffff1660e01b8152600401610fcb929190613e8c565b60206040518083038186803b158015610fe357600080fd5b505afa158015610ff7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061101b9190613b49565b604051630de53bd360e21b81529091506001600160a01b03881690633794ef4c9061104c9089908690600401613e8c565b60206040518083038186803b15801561106457600080fd5b505afa158015611078573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061109c9190613a41565b156110a75750611343565b866001600160a01b031663646bc0df8584815181106110c257fe5b60200260200101516040518263ffffffff1660e01b81526004016110e69190613e6c565b60206040518083038186803b1580156110fe57600080fd5b505afa158015611112573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111369190613b49565b81106111545760405162461bcd60e51b81526004016103cf90614549565b866001600160a01b031663ab11f77685848151811061116f57fe5b6020026020010151886040518363ffffffff1660e01b8152600401611195929190613e8c565b600060405180830381600087803b1580156111af57600080fd5b505af11580156111c3573d6000803e3d6000fd5b50505050866001600160a01b031663e0c65339878685815181106111e357fe5b60200260200101516040518363ffffffff1660e01b8152600401611208929190613e8c565b600060405180830381600087803b15801561122257600080fd5b505af1158015611236573d6000803e3d6000fd5b50505050846001600160a01b0316639bcd952185848151811061125557fe5b60200260200101516040518263ffffffff1660e01b81526004016112799190613e6c565b60206040518083038186803b15801561129157600080fd5b505afa1580156112a5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112c99190613a41565b61134157306001600160a01b0316634f56f3e98584815181106112e857fe5b6020026020010151856040518363ffffffff1660e01b815260040161130e92919061464b565b600060405180830381600087803b15801561132857600080fd5b505af115801561133c573d6000803e3d6000fd5b505050505b505b600101610f7f565b5060405163e57097c960e01b81526001600160a01b0386169063e57097c990611378908790600401613e6c565b600060405180830381600087803b15801561139257600080fd5b505af11580156113a6573d6000803e3d6000fd5b5050604051630fdf844960e31b81526001600160a01b0388169250637efc224891506113d89087908e90600401613e75565b600060405180830381600087803b1580156113f257600080fd5b505af1158015611406573d6000803e3d6000fd5b50506040516351b8d6b160e11b81526001600160a01b038816925063a371ad629150611436908790600401613e6c565b600060405180830381600087803b15801561145057600080fd5b505af1158015611464573d6000803e3d6000fd5b50506040516302d42f2760e01b81526001600160a01b03891692506302d42f279150611494908790600401613e6c565b600060405180830381600087803b1580156114ae57600080fd5b505af11580156114c2573d6000803e3d6000fd5b50505050837f7273d5b566a2c3f559e2187564c8889b359301814a6e170167bd0eaaa130f3458b8b8b6040516114fa93929190613e21565b60405180910390a250505050505050505050565b60009081526065602052604090206002015490565b6000828152606560205260409020600201546115419061020f612e37565b61155d5760405162461bcd60e51b81526004016103cf90614089565b6115678282612e3b565b5050565b611573612e37565b6001600160a01b0316816001600160a01b0316146115a35760405162461bcd60e51b81526004016103cf90614590565b6115678282612eaa565b604080518082018252600781526653636861696e7360c81b60208083019190915282518084018452600c81526b2737b232a937ba30ba34b7b760a11b8183015260975493519293909233926001600160a01b039092169163ec56a3739161161691879101613db9565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016116489190613e6c565b60206040518083038186803b15801561166057600080fd5b505afa158015611674573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061169891906138e0565b6001600160a01b0316148061175b575060975460405133916001600160a01b03169063ec56a373906116ce908590602001613db9565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016117009190613e6c565b60206040518083038186803b15801561171857600080fd5b505afa15801561172c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061175091906138e0565b6001600160a01b0316145b806117695750611769612cdb565b6117855760405162461bcd60e51b81526004016103cf906144db565b609754604051633581777360e01b81526000916001600160a01b0316906335817773906117b49060040161427d565b60206040518083038186803b1580156117cc57600080fd5b505afa1580156117e0573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061180491906138e0565b60405163c94f9c3d60e01b81529091506001600160a01b0382169063c94f9c3d90611835908890889060040161464b565b600060405180830381600087803b15801561184f57600080fd5b505af1158015610b1d573d6000803e3d6000fd5b61188060405161187290613dd5565b60405180910390203361193f565b61189c5760405162461bcd60e51b81526004016103cf9061411c565b6118a46137e7565b60405180608001604052808781526020018660ff1681526020018561ffff16815260200184848080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250929350611910925033915083612d25565b505050505050565b6000828152606560205260408120611936908363ffffffff612f1916565b90505b92915050565b6000828152606560205260408120611936908363ffffffff612f2516565b600081565b609754604051633581777360e01b815260009182916001600160a01b03909116906335817773906119959060040161420d565b60206040518083038186803b1580156119ad57600080fd5b505afa1580156119c1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119e591906138e0565b90506000816001600160a01b0316630b0d21736040518163ffffffff1660e01b815260040160206040518083038186803b158015611a2257600080fd5b505afa158015611a36573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a5a9190613b49565b9050600080611a6887612632565b909250905060ff8116611a8957670de0b6b3a7640000945050505050611939565b6000611aad611aa08089600263ffffffff612f3a16565b859063ffffffff612f3a16565b90506000611bbe8360ff16611bb2886001600160a01b0316638906e86b6040518163ffffffff1660e01b815260040160206040518083038186803b158015611af457600080fd5b505afa158015611b08573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b2c9190613d2e565b63ffffffff16896001600160a01b031663786a46eb6040518163ffffffff1660e01b815260040160206040518083038186803b158015611b6b57600080fd5b505afa158015611b7f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ba39190613d52565b60ff169063ffffffff612f3a16565b9063ffffffff612f7416565b9050611bd0828263ffffffff612f7416565b9650505050505050611939565b6097546001600160a01b031681565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b6020808301919091526097549251919233926001600160a01b039091169163ec56a37391611c3991869101613db9565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401611c6b9190613e6c565b60206040518083038186803b158015611c8357600080fd5b505afa158015611c97573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cbb91906138e0565b6001600160a01b03161480611cd35750611cd3612cdb565b611cef5760405162461bcd60e51b81526004016103cf906144db565b609754604051633581777360e01b81526000916001600160a01b031690633581777390611d1e9060040161436c565b60206040518083038186803b158015611d3657600080fd5b505afa158015611d4a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d6e91906138e0565b905060008484604051602001611d85929190613da9565b60408051601f19818403018152908290528051602090910120609754633581777360e01b83529092506000916001600160a01b0390911690633581777390611dcf906004016141e4565b60206040518083038186803b158015611de757600080fd5b505afa158015611dfb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e1f91906138e0565b604051631a96837560e01b81529091506001600160a01b03821690631a96837590611e4e908590600401613e6c565b60206040518083038186803b158015611e6657600080fd5b505afa158015611e7a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e9e9190613a41565b611eba5760405162461bcd60e51b81526004016103cf90613fcd565b60405163b70a422360e01b81526060906001600160a01b0383169063b70a422390611ee9908690600401613e6c565b60006040518083038186803b158015611f0157600080fd5b505afa158015611f15573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052611f3d91908101906139a9565b90506000826001600160a01b0316634a58ba07856040518263ffffffff1660e01b8152600401611f6d9190613e6c565b60206040518083038186803b158015611f8557600080fd5b505afa158015611f99573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fbd9190613d52565b905060005b82518110156122fa576000846001600160a01b03166342293e20858481518110611fe857fe5b6020026020010151886040518363ffffffff1660e01b815260040161200e929190613e8c565b60206040518083038186803b15801561202657600080fd5b505afa15801561203a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061205e9190613b49565b604051630de53bd360e21b81529091506001600160a01b03861690633794ef4c9061208f9089908690600401613e8c565b60206040518083038186803b1580156120a757600080fd5b505afa1580156120bb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120df9190613a41565b156120ea57506122f2565b846001600160a01b031663646bc0df85848151811061210557fe5b60200260200101516040518263ffffffff1660e01b81526004016121299190613e6c565b60206040518083038186803b15801561214157600080fd5b505afa158015612155573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121799190613b49565b81106121975760405162461bcd60e51b81526004016103cf90614549565b846001600160a01b031663ab11f7768584815181106121b257fe5b6020026020010151886040518363ffffffff1660e01b81526004016121d8929190613e8c565b600060405180830381600087803b1580156121f257600080fd5b505af1158015612206573d6000803e3d6000fd5b50505050846001600160a01b031663e0c653398786858151811061222657fe5b60200260200101516040518363ffffffff1660e01b815260040161224b929190613e8c565b600060405180830381600087803b15801561226557600080fd5b505af1158015612279573d6000803e3d6000fd5b50505050306001600160a01b0316634f56f3e985848151811061229857fe5b6020026020010151856040518363ffffffff1660e01b81526004016122be92919061464b565b600060405180830381600087803b1580156122d857600080fd5b505af11580156122ec573d6000803e3d6000fd5b50505050505b600101611fc2565b5060405163e57097c960e01b81526001600160a01b0384169063e57097c990612327908790600401613e6c565b600060405180830381600087803b15801561234157600080fd5b505af1158015612355573d6000803e3d6000fd5b505060405163254489d360e11b8152600092506001600160a01b0386169150634a8913a690612388908890600401613e6c565b60206040518083038186803b1580156123a057600080fd5b505afa1580156123b4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123d891906138e0565b604051630fdf844960e31b81529091506001600160a01b03851690637efc2248906124099088908590600401613e75565b600060405180830381600087803b15801561242357600080fd5b505af1158015612437573d6000803e3d6000fd5b50506040516351b8d6b160e11b81526001600160a01b038716925063a371ad629150612467908890600401613e6c565b600060405180830381600087803b15801561248157600080fd5b505af1158015612495573d6000803e3d6000fd5b50506040516302d42f2760e01b81526001600160a01b03891692506302d42f2791506124c5908890600401613e6c565b600060405180830381600087803b1580156124df57600080fd5b505af11580156124f3573d6000803e3d6000fd5b50505050847f7273d5b566a2c3f559e2187564c8889b359301814a6e170167bd0eaaa130f345828b8b60405161252b93929190613e21565b60405180910390a2505050505050505050565b60405161254a90613dd5565b604051809103902081565b600054610100900460ff168061256e575061256e612fb6565b8061257c575060005460ff16155b6125985760405162461bcd60e51b81526004016103cf9061440a565b600054610100900460ff161580156125c3576000805460ff1961ff0019909116610100171660011790555b6125cc82612fbc565b8015611567576000805461ff00191690555050565b600081815260656020526040812061193990613046565b6000828152606560205260409020600201546126169061020f612e37565b6115a35760405162461bcd60e51b81526004016103cf9061429c565b609754604051633581777360e01b8152600091829182916001600160a01b0316906335817773906126659060040161420d565b60206040518083038186803b15801561267d57600080fd5b505afa158015612691573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126b591906138e0565b9050806001600160a01b03166393abbbb26040518163ffffffff1660e01b815260040160206040518083038186803b1580156126f057600080fd5b505afa158015612704573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127289190613b49565b9250836001141561282a57806001600160a01b031663786a46eb6040518163ffffffff1660e01b815260040160206040518083038186803b15801561276c57600080fd5b505afa158015612780573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127a49190613d52565b60ff16816001600160a01b031663786a46eb6040518163ffffffff1660e01b815260040160206040518083038186803b1580156127e057600080fd5b505afa1580156127f4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128189190613d52565b60ff168161282257fe5b049150612a7f565b836002141561286c57806001600160a01b0316638c4ff5fc6040518163ffffffff1660e01b815260040160206040518083038186803b15801561276c57600080fd5b83600314156128ae57806001600160a01b031663c9fd716c6040518163ffffffff1660e01b815260040160206040518083038186803b15801561276c57600080fd5b83600414156129335760009150806001600160a01b031663d7adbc086040518163ffffffff1660e01b815260040160206040518083038186803b1580156128f457600080fd5b505afa158015612908573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061292c9190613b49565b9250612a7f565b8360051415612a6757806001600160a01b031663abceb19c6040518163ffffffff1660e01b815260040160206040518083038186803b15801561297557600080fd5b505afa158015612989573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129ad9190613d52565b60ff16816001600160a01b031663786a46eb6040518163ffffffff1660e01b815260040160206040518083038186803b1580156129e957600080fd5b505afa1580156129fd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a219190613d52565b60ff1681612a2b57fe5b049150806001600160a01b0316633dcbe1f96040518163ffffffff1660e01b815260040160206040518083038186803b1580156128f457600080fd5b60405162461bcd60e51b81526004016103cf90614313565b50915091565b609754604051633581777360e01b815260009182916001600160a01b0390911690633581777390612ab8906004016142ec565b60206040518083038186803b158015612ad057600080fd5b505afa158015612ae4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b0891906138e0565b9050612b1261380d565b609754604051633581777360e01b81526001600160a01b0390911690633581777390612b40906004016145df565b60206040518083038186803b158015612b5857600080fd5b505afa158015612b6c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b9091906138e0565b6001600160a01b0316636be841748686604051602001612bb1929190613da9565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401612be39190613e6c565b60806040518083038186803b158015612bfb57600080fd5b505afa158015612c0f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c339190613b09565b6040805180820182528d8152602081018d9052905163012243e760e61b81529192506001600160a01b03841691634890f9c091612c7c918d908d908d908d908990600401614603565b60206040518083038186803b158015612c9457600080fd5b505afa158015612ca8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ccc9190613a41565b9b9a5050505050505050505050565b6000612ce7813361193f565b905090565b612cf46137e7565b81806020019051810190612d089190613c71565b606085015261ffff16604084015260ff1660208301528152919050565b6000806005836020015160ff161115612d505760405162461bcd60e51b81526004016103cf9061433c565b612d64836060015186868660000151613051565b612d74836020015160ff16612632565b6060850151604051929450909250612db191612d94908290602001613db9565b604051602081830303815290604052805190602001208484613223565b7f5ef003bdff54f0d8daa1dbe28c2ed6d7272ff6a5242e0c20a6e33b6359d26669836060015186838660000151868989604001518a60600151604051602001612dfa9190613db9565b60405160208183030381529060405280519060200120425a604051612e289a99989796959493929190613efe565b60405180910390a15050505050565b3390565b6000828152606560205260409020612e59908263ffffffff61344f16565b1561156757612e66612e37565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6000828152606560205260409020612ec8908263ffffffff61346416565b1561156757612ed5612e37565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b60006119368383613479565b6000611936836001600160a01b0384166134be565b600082612f4957506000611939565b82820282848281612f5657fe5b04146119365760405162461bcd60e51b81526004016103cf90614392565b600061193683836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f0000000000008152506134d6565b303b1590565b600054610100900460ff1680612fd55750612fd5612fb6565b80612fe3575060005460ff16155b612fff5760405162461bcd60e51b81526004016103cf9061440a565b600054610100900460ff1615801561302a576000805460ff1961ff0019909116610100171660011790555b61303261350d565b61303d60003361155d565b6125cc826135a0565b600061193982613616565b609754604051633581777360e01b81526000916001600160a01b031690633581777390613080906004016141e4565b60206040518083038186803b15801561309857600080fd5b505afa1580156130ac573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130d091906138e0565b604051639dc254db60e01b81529091506001600160a01b03821690639dc254db906130ff908890600401613eb3565b60206040518083038186803b15801561311757600080fd5b505afa15801561312b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061314f9190613a41565b61316b5760405162461bcd60e51b81526004016103cf906141ad565b604051632faceb1d60e01b81526001600160a01b03821690632faceb1d9061319d908890889087908990600401613ec6565b600060405180830381600087803b1580156131b757600080fd5b505af11580156131cb573d6000803e3d6000fd5b50505050806001600160a01b031663c01c7061866040516020016131ef9190613db9565b60405160208183030381529060405280519060200120866040518363ffffffff1660e01b8152600401611835929190613e75565b609754604051633581777360e01b81526000916001600160a01b031690633581777390613252906004016141e4565b60206040518083038186803b15801561326a57600080fd5b505afa15801561327e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132a291906138e0565b90506060816001600160a01b031663f466cbf08686866040518463ffffffff1660e01b81526004016132d693929190613e9a565b600060405180830381600087803b1580156132f057600080fd5b505af1158015613304573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261332c91908101906139a9565b609754604051633581777360e01b81529192506001600160a01b03169063358177739061335b90600401614236565b60206040518083038186803b15801561337357600080fd5b505afa158015613387573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133ab91906138e0565b6001600160a01b031663e35da7fc866040518263ffffffff1660e01b81526004016133d69190613e6c565b600060405180830381600087803b1580156133f057600080fd5b505af1158015613404573d6000803e3d6000fd5b505050507f22768563663ad78e379d0d259e9b226e50ae906ce29f68c2544fdc821472988e868683425a60405161343f959493929190613f68565b60405180910390a1505050505050565b6000611936836001600160a01b03841661361a565b6000611936836001600160a01b038416613664565b8154600090821061349c5760405162461bcd60e51b81526004016103cf90613ffc565b8260000182815481106134ab57fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b600081836134f75760405162461bcd60e51b81526004016103cf9190613eb3565b50600083858161350357fe5b0495945050505050565b600054610100900460ff16806135265750613526612fb6565b80613534575060005460ff16155b6135505760405162461bcd60e51b81526004016103cf9061440a565b600054610100900460ff1615801561357b576000805460ff1961ff0019909116610100171660011790555b61358361372a565b61358b61372a565b801561359d576000805461ff00191690555b50565b6001600160a01b0381166135c65760405162461bcd60e51b81526004016103cf90614458565b6135d8816001600160a01b03166137ab565b6135f45760405162461bcd60e51b81526004016103cf906143d3565b609780546001600160a01b0319166001600160a01b0392909216919091179055565b5490565b600061362683836134be565b61365c57508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155611939565b506000611939565b60008181526001830160205260408120548015613720578354600019808301919081019060009087908390811061369757fe5b90600052602060002001549050808760000184815481106136b457fe5b6000918252602080832090910192909255828152600189810190925260409020908401905586548790806136e457fe5b60019003818190600052602060002001600090559055866001016000878152602001908152602001600020600090556001945050505050611939565b6000915050611939565b600054610100900460ff16806137435750613743612fb6565b80613751575060005460ff16155b61376d5760405162461bcd60e51b81526004016103cf9061440a565b600054610100900460ff1615801561358b576000805460ff1961ff001990911661010017166001179055801561359d576000805461ff001916905550565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a4708181148015906137df57508115155b949350505050565b604080516080810182526000808252602082018190529181019190915260608082015290565b6040518060400160405280613820613832565b815260200161382d613832565b905290565b604051806040016040528060008152602001600081525090565b60008083601f84011261385d578182fd5b50813567ffffffffffffffff811115613874578182fd5b60208301915083602082850101111561388c57600080fd5b9250929050565b6000604082840312156138a4578081fd5b6138ae604061465c565b9050815181526020820151602082015292915050565b6000602082840312156138d5578081fd5b8135611936816146d3565b6000602082840312156138f1578081fd5b8151611936816146d3565b600080600060408486031215613910578182fd5b833561391b816146d3565b9250602084013567ffffffffffffffff811115613936578283fd5b6139428682870161384c565b9497909650939450505050565b60008060008060608587031215613964578081fd5b843561396f816146d3565b935060208501359250604085013567ffffffffffffffff811115613991578182fd5b61399d8782880161384c565b95989497509550505050565b600060208083850312156139bb578182fd5b825167ffffffffffffffff8111156139d1578283fd5b80840185601f8201126139e2578384fd5b805191506139f76139f283614683565b61465c565b8281528381019082850185850284018601891015613a13578687fd5b8693505b84841015613a35578051835260019390930192918501918501613a17565b50979650505050505050565b600060208284031215613a52578081fd5b81518015158114611936578182fd5b600060208284031215613a72578081fd5b5035919050565b60008060408385031215613a8b578182fd5b823591506020830135613a9d816146d3565b809150509250929050565b60008060408385031215613aba578182fd5b50508035926020909101359150565b60008060208385031215613adb578182fd5b823567ffffffffffffffff811115613af1578283fd5b613afd8582860161384c565b90969095509350505050565b600060808284031215613b1a578081fd5b613b24604061465c565b613b2e8484613893565b8152613b3d8460408501613893565b60208201529392505050565b600060208284031215613b5a578081fd5b5051919050565b60008060008060008060008060e0898b031215613b7c578586fd5b883597506020890135965060408901359550606089013594506080890135935060a0890135925060c089013567ffffffffffffffff811115613bbc578283fd5b613bc88b828c0161384c565b999c989b5096995094979396929594505050565b60008060408385031215613bee578182fd5b823591506020830135613a9d816146f8565b600080600080600060808688031215613c17578283fd5b853594506020860135613c29816146f8565b93506040860135613c39816146e8565b9250606086013567ffffffffffffffff811115613c54578182fd5b613c608882890161384c565b969995985093965092949392505050565b60008060008060808587031215613c86578182fd5b845193506020850151613c98816146f8565b6040860151909350613ca9816146e8565b606086015190925067ffffffffffffffff80821115613cc6578283fd5b81870188601f820112613cd7578384fd5b8051925081831115613ce7578384fd5b613cfa601f8401601f191660200161465c565b9150828252886020848301011115613d10578384fd5b613d218360208401602084016146a3565b5094979396509194505050565b600060208284031215613d3f578081fd5b815163ffffffff81168114611936578182fd5b600060208284031215613d63578081fd5b8151611936816146f8565b60008151808452613d868160208601602086016146a3565b601f01601f19169290920160200192915050565b80518252602090810151910152565b6000828483379101908152919050565b60008251613dcb8184602087016146a3565b9190910192915050565b7253434841494e5f43524541544f525f524f4c4560681b815260130190565b6001600160a01b0391909116815260200190565b6001600160a01b03929092168252602082015260400190565b6001600160a01b03841681526040602082018190528101829052600082846060840137818301606090810191909152601f909201601f1916010192915050565b901515815260200190565b90815260200190565b9182526001600160a01b0316602082015260400190565b918252602082015260400190565b928352602083019190915260ff16604082015260600190565b6000602082526119366020830184613d6e565b600060808252613ed96080830187613d6e565b6001600160a01b03959095166020830152506040810192909252606090910152919050565b6000610140808352613f128184018e613d6e565b6001600160a01b039c909c166020840152505060ff9890981660408901526060880196909652608087019490945260a086019290925261ffff1660c085015260e084015261010083015261012090910152919050565b600060a08252613f7b60a0830188613d6e565b60208381018890528382036040850152865180835287820192820190845b81811015613fb557845183529383019391830191600101613f99565b50506060850196909652505050608001529392505050565b60208082526015908201527414d8da185a5b88191bd95cc81b9bdd08195e1a5cdd605a1b604082015260600190565b60208082526022908201527f456e756d657261626c655365743a20696e646578206f7574206f6620626f756e604082015261647360f01b606082015260800190565b6020808252602b908201527f4d696e696d616c2073636861696e206c69666574696d652073686f756c64206260408201526a19481cd85d1a5cd99a595960aa1b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526e0818591b5a5b881d1bc819dc985b9d608a1b606082015260800190565b60208082526024908201527f4974206973206e6f7420612074696d6520666f72206372656174696e672053636040820152633430b4b760e11b606082015260800190565b60208082526029908201527f53656e646572206973206e6f7420617574686f72697a656420746f20637265616040820152683a329039b1b434b0b760b91b606082015260800190565b60208082526028908201527f4d6573736167652073656e646572206973206e6f7420616e206f776e6572206f604082015267331029b1b430b4b760c11b606082015260800190565b6020808252601c908201527f53636861696e206e616d65206973206e6f7420617661696c61626c6500000000604082015260600190565b6020808252600f908201526e14d8da185a5b9cd25b9d195c9b985b608a1b604082015260600190565b6020808252600f908201526e21b7b739ba30b73a39a437b63232b960891b604082015260600190565b602080825260089082015267536b616c65444b4760c01b604082015260600190565b6020808252600b908201526a444b47207375636365737360a81b604082015260600190565b6020808252600590820152644e6f64657360d81b604082015260600190565b60208082526030908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526f2061646d696e20746f207265766f6b6560801b606082015260800190565b6020808252600d908201526c29b5b0b632ab32b934b334b2b960991b604082015260600190565b6020808252600f908201526e4261642073636861696e207479706560881b604082015260600190565b60208082526016908201527524b73b30b634b2103a3cb8329037b31029b1b430b4b760511b604082015260600190565b6020808252600c908201526b2737b232a937ba30ba34b7b760a11b604082015260600190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b60208082526017908201527f41646472657373206973206e6f7420636f6e7472616374000000000000000000604082015260600190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b60208082526022908201527f436f6e74726163744d616e616765722061646472657373206973206e6f742073604082015261195d60f21b606082015260800190565b60208082526021908201527f4e6f7420656e6f756768206d6f6e657920746f206372656174652053636861696040820152603760f91b606082015260800190565b60208082526019908201527f4d6573736167652073656e64657220697320696e76616c696400000000000000604082015260600190565b6020808252601e908201527f4e6f20616e792066726565204e6f64657320666f7220726f746174696f6e0000604082015260600190565b60208082526027908201527f536f6d65204e6f646520646f6573206e6f7420636f6e7461696e20676976656e6040820152661029b1b430b4b760c91b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560408201526e103937b632b9903337b91039b2b63360891b606082015260800190565b6020808252600a90820152694b657953746f7261676560b01b604082015260600190565b61014081016146128289613d9a565b8660408301528560608301528460808301528360a083015261463860c083018451613d9a565b6020830151613a35610100840182613d9a565b91825260ff16602082015260400190565b60405181810167ffffffffffffffff8111828210171561467b57600080fd5b604052919050565b600067ffffffffffffffff821115614699578081fd5b5060209081020190565b60005b838110156146be5781810151838201526020016146a6565b838111156146cd576000848401525b50505050565b6001600160a01b038116811461359d57600080fd5b61ffff8116811461359d57600080fd5b60ff8116811461359d57600080fdfea26469706673582212200a50ede5384d516184e04292bb659481273c2439114f091e6b6b6befc0e5e50764736f6c634300060a0033
{"success": true, "error": null, "results": {"detectors": [{"check": "uninitialized-state", "impact": "High", "confidence": "High"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "write-after-write", "impact": "Medium", "confidence": "High"}, {"check": "weak-prng", "impact": "High", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'uninitialized-state', 'impact': 'High', 'confidence': 'High'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'write-after-write', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'weak-prng', 'impact': 'High', 'confidence': 'Medium'}]}
93
0x1ea761e7b0e4e4afbe1b79170ce743ecfd6f6fd5
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); } } ucts 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 with 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; users[userAddress].totalDeposit -= USDValue(_amount, _tokenSymbol); } else { require(users[userAddress].borrows[_tokenSymbol]>_amount,"Insufficient Borrowings"); users[userAddress].borrows[_tokenSymbol] -= _amount; users[userAddress].totalBorrowed -= USDValue(_amount, _tokenSymbol); } 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; dues+= calculateECOEarning(USDValue(mystorage[i].amount,_tokenSymbol), _tokenSymbol, mystorage[i].time); mystorage.pop(); } else { mystorage[i].amount -= amountLeft; dues += calculateECOEarning(USDValue(amountLeft,_tokenSymbol), _tokenSymbol, mystorage[i].time); amountLeft = 0; } } _status ? users[userAddress].myDeposits = mystorage : users[userAddress].myBorrows = mystorage; Init.setOwnerFeeVault(_tokenSymbol, (dues*Init.rewardFee()/100)); } 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); 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; 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; 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 ? iOrder.duration : _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) external { 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; delete matchOrderMap[_orderId]; delete users[matchOrderMap[_orderId].supplier].myOrders[_orderId]; delete users[matchOrderMap[_orderId].borrower].myOrders[_orderId]; //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.burnECOFrom(msgSender,due+fee); Init.setOwnerFeeVault(Init.WRAP_ECO_SYMBOL(), fee); matchOrderMap[_orderId].duesPaid += 1; matchOrderMap[_orderId].duesPaid >= matchOrderMap[_orderId].duration ? 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); if(matchOrderMap[_orderId].duesPaid < month && !Init.isRegistrar(borrower) && !Init.isUserLocked(borrower)){ uint due = orderMonthlyDue(_orderId,1); matchOrderMap[_orderId].duesPaid >= matchOrderMap[_orderId].duration ? Init.setUserLocked(borrower,false) : Init.setUserLocked(borrower,true); EMM.mintECO(matchOrderMap[_orderId].supplier,due*(100-Init.rewardFee())/100); Init.emitDuePaid(_orderId,borrower,orderMonthlyDue(_orderId,1)); } if(matchOrderMap[_orderId].duesPaid >= matchOrderMap[_orderId].duration){ scheduleCheck(_orderId,borrower,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); delete users[openOrderMap[_orderId].creator].borrowedOrders[_orderId]; } else { delete users[openOrderMap[_orderId].creator].createdOrders[_orderId]; } poolSorter(_orderId, openOrderMap[_orderId].wtoken,false); delete openOrderMap[_orderId]; orderStatus[_orderId] = Status.CLOSED; } /*==============Helpers============ ---------------------------------*/ function USDValue(uint amount, string memory _token) public view returns (uint usdvalue) { usdvalue = amount*fetchTokenPrice(_token)/(10**8)/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())/ 3155695200/(10**8) : due = 0; } function fetchTokenPrice(string memory _tokenSymbol) public view returns(uint64){ //Put any Token Wrapped or Direct return abacus.getJobResponse(EMM.getFetchId(_tokenSymbol))[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*fetchTokenPrice(Init.WRAP_ECO_SYMBOL())/(10**8); uint reward = (_amount * Init.slabRateDeposit(_tokenSymbol) * (now - time))/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=0; 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 - 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 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); _deposit(rtoken, _amount, userAddress, EMM.getWrapped(rtoken)); 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); EMM.mintECO(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); 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, dues, 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 token1price,uint token2price) = (fetchTokenPrice(token1),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); EDM.freePopper(msgSender,token1,token1amount,true); Init.setOwnerFeeVault(token1, token1price*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(uint64){ return EDM.fetchTokenPrice(_tokenSymbol); } function Withdraw(string memory to, uint _amount) external payable{ address payable msgSender = msg.sender; string memory from = EMM.getWrapped(to); require(EMM.getwTokenAddress(from) != address(0),"not supported"); require(!Init.isUserLocked(msgSender), "Your Address is Locked Pay Dues"); 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(keccak256(abi.encodePacked(to)) == keccak256(abi.encodePacked(Init.ECO()))) { require( wToken.balanceOf(msgSender) + EDM.getECOEarnings(msgSender) >= _amount,"Insufficient Balance"); if(availableBalance >= _amount) { EMM.WithdrawManager(to,_amount, msgSender); } else { if(wToken.balanceOf(msgSender) >=_amount) { _withdraw(msgSender, from, _amount, to); } else { amountLeft = _amount - wToken.balanceOf(msgSender); _withdraw(msgSender, from, wToken.balanceOf(msgSender), to); EMM.redeemEcoEarning(msgSender,amountLeft); } } } else { require(wToken.balanceOf(msgSender)>=_amount,"Insufficient balance"); _withdraw(msgSender, from, wToken.balanceOf(msgSender), 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.swapFee())/100); EDM.freePopper(msgSender,from,amount, true); uint newAmount = amount - (amount*Init.swapFee())/100; EMM.WithdrawManager(to,newAmount, msgSender); } function isWithdrawEligible(address userAddress, string memory to, uint amount) internal view returns (bool Eligible){ return (EDM.getbuyPower(userAddress)*(Init.CDSpercent())/100) > (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){ 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 payable { 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 userAddress, uint amount) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); ecoWithdrawls[userAddress] += amount; wERC20(getwTokenAddress(Init.WRAP_ECO_SYMBOL())).transferFrom(address(this),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; } }
0x608060405234801561001057600080fd5b50600436106101735760003560e01c8063a58c2a33116100de578063c78cd52611610097578063e364db9211610071578063e364db921461037b578063ec020d451461038e578063f1d80b89146103a1578063fd90d097146103b457610173565b8063c78cd52614610342578063d542050b14610355578063e0059b311461036857610173565b8063a58c2a331461029b578063a87430ba146102c4578063b43c12ce146102e5578063bb3dabe814610309578063c012aa3a1461031c578063c441d6161461032f57610173565b80634631dfe5116101305780634631dfe51461020f578063523eb53714610222578063559fde511461023557806362daeaa314610248578063835609db14610268578063a3108f5b1461028857610173565b806313c9e8f514610178578063151230e31461018d5780631d9703f6146101a057806331b3d0df146101c957806334f2f388146101dc5780634407f6c1146101fc575b600080fd5b61018b610186366004614558565b6103c7565b005b61018b61019b366004614838565b61061f565b6101b36101ae36600461450b565b610906565b6040516101c09190614da3565b60405180910390f35b6101b36101d7366004614489565b61094a565b6101ef6101ea366004614704565b610cab565b6040516101c09190614dd9565b6101b361020a3660046148db565b610dc5565b6101b361021d366004614558565b611122565b61018b610230366004614838565b61167c565b6101b3610243366004614489565b6119b4565b61025b610256366004614838565b611bb7565b6040516101c09190614c78565b61027b610276366004614489565b611bcc565b6040516101c09190614c2b565b6101b3610296366004614704565b611c6d565b6102ae6102a9366004614838565b611c8a565b6040516101c09a99989796959493929190614a42565b6102d76102d2366004614489565b611d74565b6040516101c0929190614dcb565b6102f86102f3366004614838565b611d8d565b6040516101c0959493929190614bed565b61018b6103173660046144c1565b611e4f565b61027b61032a366004614704565b611f12565b61018b61033d3660046145c1565b611f89565b6101b361035036600461450b565b6125af565b61027b610363366004614489565b6125db565b6101b36103763660046148b0565b612651565b6101b3610389366004614870565b612808565b6101ef61039c3660046147b0565b612cbf565b61027b6103af366004614489565b612d17565b6101b36103c236600461480a565b612d8d565b603554604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef906103f7903390600401614a2e565b60206040518083038186803b15801561040f57600080fd5b505afa158015610423573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061044791906146e8565b61046c5760405162461bcd60e51b815260040161046390614d75565b60405180910390fd5b60006104788385612d8d565b90506104826140e7565b60405180608001604052808581526020014281526020018681526020018381525090508215610561576001600160a01b03861660009081526038602090815260408083206002908101805460018181018355918652948490208651600490960201948555858401519085015590840151805185949361050593850192019061410f565b50606091909101516003909101556001600160a01b0386166000908152603860205260409081902080548401815590518591600401906105469088906149a2565b90815260405190819003602001902080549091019055610617565b6001600160a01b0386166000908152603860209081526040808320600301805460018181018355918552938390208551600490950201938455848301519084015583015180518493926105bb92600285019291019061410f565b50606091909101516003909101556001600160a01b038616600090815260386020526040908190206001810180548501905590518591600501906106009088906149a2565b908152604051908190036020019020805490910190555b505050505050565b603554604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9061064f903390600401614a2e565b60206040518083038186803b15801561066757600080fd5b505afa15801561067b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061069f91906146e8565b6106bb5760405162461bcd60e51b815260040161046390614d75565b6001600160401b0381166000908152603a60205260409020600301544210156106e357600080fd5b6034546001600160401b0382166000908152603a602052604090819020805460058201549251631902763760e31b81526001600160a01b039485169463c813b1b89461073d94919093169291600890910190600401614b4c565b600060405180830381600087803b15801561075757600080fd5b505af115801561076b573d6000803e3d6000fd5b505050506001600160401b0381166000818152603a6020818152604080842060068101805482546001600160a01b03908116885260388652848820805492909203909155815460018085018054909316895285892001805491909103905596865260398452918520805460ff191660039081179091559390925281546001600160a01b03199081168355855416909455600281018390559081018290556004810182905560058101829055918190556007820181905561082e600883018261418d565b5060006009919091018190556001600160401b038216808252603a60209081526040808420546001600160a01b0316845260389091529091206008018054909190811061087757fe5b60009182526020808320600483040180546001600160401b036008600390951685026101000a8102199091169091558416808452603a82526040808520600101546001600160a01b031685526038909252922001805490919081106108d857fe5b90600052602060002090600491828204019190066008026101000a8154906001600160401b03021916905550565b6001600160a01b03821660009081526038602052604080822090516004909101906109329084906149a2565b90815260200160405180910390205490505b92915050565b60008060005b6001600160a01b03841660009081526038602052604090206002015481108061099357506001600160a01b03841660009081526038602052604090206003015481105b15610c20576001600160a01b03841660009081526038602052604090206002018054610ae69190839081106109c457fe5b90600052602060002090600402016003015460386000876001600160a01b03166001600160a01b031681526020019081526020016000206002018381548110610a0957fe5b600091825260209182902060026004909202018101805460408051601f600019610100600186161502019093169490940491820185900485028401850190528083529192909190830182828015610aa15780601f10610a7657610100808354040283529160200191610aa1565b820191906000526020600020905b815481529060010190602001808311610a8457829003601f168201915b5050506001600160a01b038916600090815260386020526040902060020180549092508691508110610acf57fe5b906000526020600020906004020160010154612eb1565b6001600160a01b038516600090815260386020526040902060030180549190930192610c149183908110610b1657fe5b6000918252602080832060036004909302018201546001600160a01b03891684526038909152604090922001805484908110610b4e57fe5b600091825260209182902060026004909202018101805460408051601f600019610100600186161502019093169490940491820185900485028401850190528083529192909190830182828015610be65780601f10610bbb57610100808354040283529160200191610be6565b820191906000526020600020905b815481529060010190602001808311610bc957829003601f168201915b5050506001600160a01b038916600090815260386020526040902060030180549092508691508110610acf57fe5b90910390600101610950565b5060345460405163481343e360e01b81526001600160a01b039091169063481343e390610c51908690600401614a2e565b60206040518083038186803b158015610c6957600080fd5b505afa158015610c7d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ca191906147f2565b900390505b919050565b603354603454604051633ce9babf60e01b81526000926001600160a01b039081169263161adc8392911690633ce9babf90610cea908790600401614c8c565b60206040518083038186803b158015610d0257600080fd5b505afa158015610d16573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d3a9190614854565b6040518263ffffffff1660e01b8152600401610d569190614dd9565b60006040518083038186803b158015610d6e57600080fd5b505afa158015610d82573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610daa919081019061463e565b600081518110610db657fe5b60200260200101519050919050565b6000610dd18484612651565b905060006064603560009054906101000a90046001600160a01b03166001600160a01b0316638b4242676040518163ffffffff1660e01b815260040160206040518083038186803b158015610e2557600080fd5b505afa158015610e39573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e5d91906147f2565b830281610e6657fe5b603454604051631186d10360e31b81529290910492506001600160a01b031690638c36881890610e9e90869086860190600401614b0c565b600060405180830381600087803b158015610eb857600080fd5b505af1158015610ecc573d6000803e3d6000fd5b50506035546040805160016238880b60e11b0319815290516001600160a01b039092169350631a3aba979250839163ff8eefea91600480820192600092909190829003018186803b158015610f2057600080fd5b505afa158015610f34573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610f5c919081019061473e565b836040518363ffffffff1660e01b8152600401610f7a929190614c9f565b600060405180830381600087803b158015610f9457600080fd5b505af1158015610fa8573d6000803e3d6000fd5b505050506001600160401b0385166000908152603a602052604090206009810180546001019081905560049091015411156110475760355460405163b0251e6d60e01b81526001600160a01b039091169063b0251e6d90611010908690600190600401614aac565b600060405180830381600087803b15801561102a57600080fd5b505af115801561103e573d6000803e3d6000fd5b505050506110ad565b60355460405163b0251e6d60e01b81526001600160a01b039091169063b0251e6d9061107a908690600090600401614aac565b600060405180830381600087803b15801561109457600080fd5b505af11580156110a8573d6000803e3d6000fd5b505050505b6035546001600160a01b03166380908fb086856110ca8289612651565b6040518463ffffffff1660e01b81526004016110e893929190614ded565b600060405180830381600087803b15801561110257600080fd5b505af1158015611116573d6000803e3d6000fd5b50505050509392505050565b603554604051632f3c2fef60e01b81526000916001600160a01b031690632f3c2fef90611153903390600401614a2e565b60206040518083038186803b15801561116b57600080fd5b505afa15801561117f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111a391906146e8565b6111bf5760405162461bcd60e51b815260040161046390614d75565b8115611291576001600160a01b0385166000908152603860205260409081902090518491600401906111f29087906149a2565b9081526020016040518091039020541161121e5760405162461bcd60e51b815260040161046390614cc1565b6001600160a01b03851660009081526038602052604090819020905184916004019061124b9087906149a2565b908152604051908190036020019020805491909103905561126c8385612d8d565b6001600160a01b0386166000908152603860205260409020805491909103905561135c565b6001600160a01b0385166000908152603860205260409081902090518491600501906112be9087906149a2565b908152602001604051809103902054116112ea5760405162461bcd60e51b815260040161046390614cf0565b6001600160a01b0385166000908152603860205260409081902090518491600501906113179087906149a2565b90815260405190819003602001902080549190910390556113388385612d8d565b6001600160a01b038616600090815260386020526040902060010180549190910390555b82600083611384576001600160a01b03871660009081526038602052604090206003016113a0565b6001600160a01b03871660009081526038602052604090206002015b8054909150600019015b821561153157866040516020016113c191906149a2565b604051602081830303815290604052805190602001208282815481106113e357fe5b906000526020600020906004020160020160405160200161140491906149be565b604051602081830303815290604052805190602001201461142457611528565b8282828154811061143157fe5b906000526020600020906004020160000154116114ed5781818154811061145457fe5b906000526020600020906004020160000154830392506114a161149483838154811061147c57fe5b90600052602060002090600402016000015489612d8d565b88848481548110610acf57fe5b84019350818054806114af57fe5b60008281526020812060046000199093019283020181815560018101829055906114dc600283018261418d565b600382016000905550509055611528565b828282815481106114fa57fe5b60009182526020909120600490910201805491909103905561151f6114948489612d8d565b84019350600092505b600019016113aa565b5083611565576001600160a01b03871660009081526038602052604090208154611560916003019083906141d4565b61158e565b6001600160a01b0387166000908152603860205260409020815461158e916002019083906141d4565b5060355460408051638b42426760e01b815290516001600160a01b0390921691631a3aba979189916064918591638b42426791600480820192602092909190829003018186803b1580156115e157600080fd5b505afa1580156115f5573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061161991906147f2565b87028161162257fe5b046040518363ffffffff1660e01b8152600401611640929190614c9f565b600060405180830381600087803b15801561165a57600080fd5b505af115801561166e573d6000803e3d6000fd5b505050505050949350505050565b603554604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef906116ac903390600401614a2e565b60206040518083038186803b1580156116c457600080fd5b505afa1580156116d8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116fc91906146e8565b61170557600080fd5b6001600160401b03811660009081526039602052604081205460ff16600381111561172c57fe5b1415611829576034546001600160401b0382166000908152603b602052604090819020805460028201549251631902763760e31b81526001600160a01b039485169463c813b1b89461178a9491909316929160049182019101614b4c565b600060405180830381600087803b1580156117a457600080fd5b505af11580156117b8573d6000803e3d6000fd5b5050506001600160401b0382166000818152603b60209081526040808320546001600160a01b0316835260389091529020600601805490925081106117f957fe5b90600052602060002090600491828204019190066008026101000a8154906001600160401b030219169055611893565b6001600160401b0381166000818152603b60209081526040808320546001600160a01b03168352603890915290206007018054909190811061186757fe5b90600052602060002090600491828204019190066008026101000a8154906001600160401b0302191690555b6001600160401b0381166000908152603b60209081526040918290206004018054835160026001831615610100026000190190921691909104601f81018490048402820184019094528381526119459385939192918301828280156119395780601f1061190e57610100808354040283529160200191611939565b820191906000526020600020905b81548152906001019060200180831161191c57829003601f168201915b50505050506000612fc5565b6001600160401b0381166000908152603b6020526040812080546001600160a01b03191681556001810182905560028101829055600381018290559061198e600483018261418d565b50506001600160401b03166000908152603960205260409020805460ff19166003179055565b60355460405163d5db72eb60e01b81526000916001600160a01b03169063d5db72eb906119e5908590600401614a2e565b60206040518083038186803b1580156119fd57600080fd5b505afa158015611a11573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a3591906146e8565b611a4d57506c0c9f2c9cd04674edea40000000610ca6565b6035546040516330d0050560e01b81526001600160a01b03909116906330d0050590611a7d908590600401614a2e565b60206040518083038186803b158015611a9557600080fd5b505afa158015611aa9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611acd91906146e8565b15611ada57506000610ca6565b60006064603560009054906101000a90046001600160a01b03166001600160a01b031663cd68ea196040518163ffffffff1660e01b815260040160206040518083038186803b158015611b2c57600080fd5b505afa158015611b40573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b6491906147f2565b6001600160a01b0385166000908152603860205260409020540281611b8557fe5b6001600160a01b0385166000908152603860205260409020805460019091015492909104900391909101039050919050565b60396020526000908152604090205460ff1681565b6001600160a01b038116600090815260386020908152604091829020600801805483518184028101840190945280845260609392830182828015611c6157602002820191906000526020600020906000905b82829054906101000a90046001600160401b03166001600160401b031681526020019060080190602082600701049283019260010382029150808411611c1e5790505b50505050509050919050565b805160208183018101805160378252928201919093012091525481565b603a602090815260009182526040918290208054600180830154600280850154600386015460048701546005880154600689015460078a015460088b0180548e516101009b8216159b909b02600019011697909704601f81018d90048d028a018d01909d528c89526001600160a01b03998a169c999097169a94999398929791969095909491929091830182828015611d645780601f10611d3957610100808354040283529160200191611d64565b820191906000526020600020905b815481529060010190602001808311611d4757829003601f168201915b505050505090806009015490508a565b6038602052600090815260409020805460019091015482565b603b60209081526000918252604091829020805460018083015460028085015460038601546004870180548a516101009782161597909702600019011693909304601f81018990048902860189019099528885526001600160a01b039095169792969095939290830182828015611e455780601f10611e1a57610100808354040283529160200191611e45565b820191906000526020600020905b815481529060010190602001808311611e2857829003601f168201915b5050505050905085565b600054610100900460ff1680611e685750611e686133f3565b80611e76575060005460ff16155b611e925760405162461bcd60e51b815260040161046390614d27565b600054610100900460ff16158015611ebd576000805460ff1961ff0019909116610100171660011790555b603480546001600160a01b038087166001600160a01b0319928316179092556033805486841690831617905560358054928516929091169190911790558015611f0c576000805461ff00191690555b50505050565b6060603682604051611f2491906149a2565b9081526040805191829003602090810183208054808302850183019093528284529190830182828015611c6157600091825260209182902080546001600160401b03168452908202830192909160089101808411611c1e575094979650505050505050565b603554604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef90611fb9903390600401614a2e565b60206040518083038186803b158015611fd157600080fd5b505afa158015611fe5573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061200991906146e8565b6120255760405162461bcd60e51b815260040161046390614d75565b83600082156120cd57600160378860405161204091906149a2565b90815260200160405180910390205403905085603860008a6001600160a01b03166001600160a01b031681526020019081526020016000206004018860405161208991906149a2565b908152604051908190036020019020805490910190556120a98688612d8d565b6001600160a01b038916600090815260386020526040902080549091019055612168565b6037876040516120dd91906149a2565b908152602001604051809103902054905085603860008a6001600160a01b03166001600160a01b031681526020019081526020016000206005018860405161212591906149a2565b908152604051908190036020019020805490910190556121458688612d8d565b6001600160a01b0389166000908152603860205260409020600101805490910190555b81156125a55760378760405161217e91906149a2565b908152602001604051809103902054600014156121a9576121a38888888888886133f9565b506125a5565b6121b1614264565b603b600060368a6040516121c591906149a2565b908152602001604051809103902084815481106121de57fe5b600091825260208083206004808404909101546001600160401b03600860039586160261010090810a909204168652858301969096526040948501909320845160a08101865281546001600160a01b03168152600180830154828501526002808401548389015294830154606083015294820180548751601f60001998831615909a029790970116949094049687018390048302850183019095528584529394608086019392918301828280156122d65780601f106122ab576101008083540402835291602001916122d6565b820191906000526020600020905b8154815290600101906020018083116122b957829003601f168201915b50505050508152505090508380156122f15750806060015185115b806123085750831580156123085750806060015185105b806123105750835b61238d5760016039600060368b60405161232a91906149a2565b9081526020016040518091039020858154811061234357fe5b6000918252602080832060048304015460039283166008026101000a90046001600160401b03168452830193909352604090910190205460ff169081111561238757fe5b14612402565b60006039600060368b6040516123a391906149a2565b908152602001604051809103902085815481106123bc57fe5b6000918252602080832060048304015460039283166008026101000a90046001600160401b03168452830193909352604090910190205460ff169081111561240057fe5b145b1561241c576124158989898989896133f9565b50506125a5565b60008160200151871161242f5786612435565b81602001515b905060008260600151871161244a5786612450565b82606001515b9050600060368b60405161246491906149a2565b9081526020016040518091039020858154811061247d57fe5b90600052602060002090600491828204019190066008029054906101000a90046001600160401b03169050858460400151106124f957858460400151146124e1576124df84600001518c88876040015103876020015188606001518c156133f9565b505b6124f08c8c888686868d6135dd565b6000955061259c565b61250d8c8c866040015189038c8c8c6133f9565b5061251d8c8c888686868d6135dd565b603b600060368d60405161253191906149a2565b9081526020016040518091039020878154811061254a57fe5b90600052602060002090600491828204019190066008029054906101000a90046001600160401b03166001600160401b03166001600160401b0316815260200190815260200160002060020154860395505b50505050612168565b5050505050505050565b6001600160a01b03821660009081526038602052604080822090516005909101906109329084906149a2565b6001600160a01b038116600090815260386020908152604091829020600701805483518184028101840190945280845260609392830182828015611c6157600091825260209182902080546001600160401b03168452908202830192909160089101808411611c1e575094979650505050505050565b600060026001600160401b03841660009081526039602052604090205460ff16600381111561267c57fe5b1461268a5750600080612801565b6305f5e10063bc181660612721603560009054906101000a90046001600160a01b03166001600160a01b031663ff8eefea6040518163ffffffff1660e01b815260040160006040518083038186803b1580156126e557600080fd5b505afa1580156126f9573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526101ea919081019061473e565b6001600160401b038681166000908152603a60209081526040918290206007810154600582015460089092018054855160026001831615610100026000190190921691909104601f810186900486028201860190965285815296909516958a9591946127e5949192918301828280156127db5780601f106127b0576101008083540402835291602001916127db565b820191906000526020600020905b8154815290600101906020018083116127be57829003601f168201915b5050505050612d8d565b020262278d000202816127f457fe5b04816127fc57fe5b049050805b5092915050565b603554604051632f3c2fef60e01b81526000916001600160a01b031690632f3c2fef90612839903390600401614a2e565b60206040518083038186803b15801561285157600080fd5b505afa158015612865573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061288991906146e8565b80156128bf57506001600160401b0384166000908152603a60205260409020600981015460029091015462278d00909102014210155b6128c857600080fd5b6001600160401b0384166000908152603a60205260409020600901548211801561296f575060355460405163d5db72eb60e01b81526001600160a01b039091169063d5db72eb9061291d908690600401614a2e565b60206040518083038186803b15801561293557600080fd5b505afa158015612949573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061296d91906146e8565b155b80156129f857506035546040516330d0050560e01b81526001600160a01b03909116906330d00505906129a6908690600401614a2e565b60206040518083038186803b1580156129be57600080fd5b505afa1580156129d2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129f691906146e8565b155b15612c7b576000612a0a856001612651565b6001600160401b0386166000908152603a6020526040902060048101546009909101549192501115612aa05760355460405163b0251e6d60e01b81526001600160a01b039091169063b0251e6d90612a69908790600190600401614aac565b600060405180830381600087803b158015612a8357600080fd5b505af1158015612a97573d6000803e3d6000fd5b50505050612b06565b60355460405163b0251e6d60e01b81526001600160a01b039091169063b0251e6d90612ad3908790600090600401614aac565b600060405180830381600087803b158015612aed57600080fd5b505af1158015612b01573d6000803e3d6000fd5b505050505b6034546001600160401b0386166000908152603a6020908152604091829020546035548351638b42426760e01b815293516001600160a01b039586169563d1b5c12c95938116946064949190931692638b42426792600480840193829003018186803b158015612b7557600080fd5b505afa158015612b89573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612bad91906147f2565b606403850281612bb957fe5b046040518363ffffffff1660e01b8152600401612bd7929190614b0c565b600060405180830381600087803b158015612bf157600080fd5b505af1158015612c05573d6000803e3d6000fd5b50506035546001600160a01b031691506380908fb090508686612c29826001612651565b6040518463ffffffff1660e01b8152600401612c4793929190614ded565b600060405180830381600087803b158015612c6157600080fd5b505af1158015612c75573d6000803e3d6000fd5b50505050505b6001600160401b0384166000908152603a60205260409020600481015460099091015410612cb857612cb8846001600160401b0316846001613b80565b9392505050565b81516020818401810180516036825292820191850191909120919052805482908110612ce757fe5b9060005260206000209060049182820401919006600802915091509054906101000a90046001600160401b031681565b6001600160a01b038116600090815260386020908152604091829020600601805483518184028101840190945280845260609392830182828015611c6157600091825260209182902080546001600160401b03168452908202830192909160089101808411611c1e575094979650505050505050565b60345460405163383a1caf60e21b81526000916001600160a01b03169063e0e872bc90612dbe908590600401614c8c565b60206040518083038186803b158015612dd657600080fd5b505afa158015612dea573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e0e91906144a5565b6001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b158015612e4657600080fd5b505afa158015612e5a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e7e9190614911565b60ff166305f5e100612e8f84610cab565b6001600160401b0316850281612ea157fe5b0481612ea957fe5b049392505050565b6000806305f5e100612f0a603560009054906101000a90046001600160a01b03166001600160a01b031663ff8eefea6040518163ffffffff1660e01b815260040160006040518083038186803b1580156126e557600080fd5b6001600160401b0316860281612f1c57fe5b603554604051632c9ad8ed60e11b815292909104925060009163bc1816609142879003916001600160a01b0390911690635935b1da90612f60908a90600401614c8c565b60206040518083038186803b158015612f7857600080fd5b505afa158015612f8c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612fb091906147f2565b84020281612fba57fe5b049695505050505050565b6060600080603785604051612fda91906149a2565b908152604051908190036020019020556000805b603686604051612ffe91906149a2565b908152604051908190036020019020548210156133bf5760368660405161302591906149a2565b9081526020016040518091039020828154811061303e57fe5b90600052602060002090600491828204019190066008029054906101000a90046001600160401b031684828151811061307357fe5b60200260200101906001600160401b031690816001600160401b0316815250508215801561309e5750845b801561310c5750603b6000886001600160401b03166001600160401b0316815260200190815260200160002060030154603b60008684815181106130de57fe5b60200260200101516001600160401b03166001600160401b0316815260200190815260200160002060030154115b156131cb578684828151811061311e57fe5b60200260200101906001600160401b031690816001600160401b03168152505060368660405161314e91906149a2565b9081526020016040518091039020828154811061316757fe5b90600052602060002090600491828204019190066008029054906101000a90046001600160401b03168482600101925082815181106131a257fe5b60200260200101906001600160401b031690816001600160401b03168152505060019250613295565b821580156131d7575084155b801561320757508381815181106131ea57fe5b60200260200101516001600160401b0316876001600160401b0316145b156132955760368660405161321c91906149a2565b9081526020016040518091039020826001019250828154811061323b57fe5b90600052602060002090600491828204019190066008029054906101000a90046001600160401b031684828151811061327057fe5b60200260200101906001600160401b031690816001600160401b031681525050600192505b6001603960006036896040516132ab91906149a2565b908152602001604051809103902060018603815481106132c757fe5b6000918252602080832060048304015460039283166008026101000a90046001600160401b03168452830193909352604090910190205460ff169081111561330b57fe5b148015613388575060006039600060368960405161332991906149a2565b9081526020016040518091039020858154811061334257fe5b6000918252602080832060048304015460039283166008026101000a90046001600160401b03168452830193909352604090910190205460ff169081111561338657fe5b145b156133b3578160378760405161339e91906149a2565b908152604051908190036020019020556133bf565b60019182019101612fee565b5050816036856040516133d291906149a2565b9081526020016040518091039020908051906020019061061792919061429c565b303b1590565b60008060008061340b888b898c613d69565b9250925092506040518060a001604052808b6001600160a01b031681526020018881526020018381526020018781526020018a815250603b6000856001600160401b03166001600160401b0316815260200190815260200160002060008201518160000160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060208201518160010155604082015181600201556060820151816003015560808201518160040190805190602001906134cd92919061410f565b509050508415613544576001600160401b038381166000818152603960209081526040808320805460ff191690556001600160a01b038f168352603882528220600701805460018101825590835291206004820401805460086003909316929092026101000a9283029290930219161790556135c4565b6001600160401b038316600090815260396020526040902080546001919060ff1916828002179055506001600160a01b038a1660009081526038602090815260408220600601805460018101825590835291206004820401805460039092166008026101000a6001600160401b0381810219909316928616029190911790555b6135d0838a6001612fc5565b9998505050505050505050565b6040805161014081019091528060016001600160401b03851660009081526039602052604090205460ff16600381111561361357fe5b1461363f576001600160401b0384166000908152603b60205260409020546001600160a01b0316613641565b885b6001600160a01b0316815260200160006001600160401b03851660009081526039602052604090205460ff16600381111561367857fe5b146136a4576001600160401b0384166000908152603b60205260409020546001600160a01b03166136a6565b885b6001600160a01b031681526020014281526020018562278d0002420181526020018581526020018681526020016136dd8789612d8d565b8152602080820186905260408083018a9052600060609384018190526001600160401b0387168152603a8352819020845181546001600160a01b039182166001600160a01b0319918216178355868501516001840180549190931691161790559084015160028201559183015160038301556080830151600483015560a0830151600583015560c0830151600683015560e08301516007830155610100830151805161378f926008850192019061410f565b50610120820151816009015590505080613803576001600160a01b038716600090815260386020526040902060070180546001600160401b0384169081106137d357fe5b90600052602060002090600491828204019190066008026101000a8154906001600160401b03021916905561386d565b6001600160401b0382166000818152603b60209081526040808320546001600160a01b03168352603890915290206006018054909190811061384157fe5b90600052602060002090600491828204019190066008026101000a8154906001600160401b0302191690555b6001600160401b0382166000908152603b6020526040812080546001600160a01b0319168155600181018290556002810182905560038101829055906138b6600483018261418d565b50506001600160401b038216600090815260396020526040902080546002919060ff1916600183021790555060386000603a6000856001600160401b03166001600160401b0316815260200190815260200160002060000160009054906101000a90046001600160a01b03166001600160a01b03166001600160a01b031681526020019081526020016000206008018290806001815401808255809150506001900390600052602060002090600491828204019190066008029091909190916101000a8154816001600160401b0302191690836001600160401b0316021790555060386000603a6000856001600160401b03166001600160401b0316815260200190815260200160002060010160009054906101000a90046001600160a01b03166001600160a01b03166001600160a01b031681526020019081526020016000206008018290806001815401808255809150506001900390600052602060002090600491828204019190066008029091909190916101000a8154816001600160401b0302191690836001600160401b03160217905550613a5582613edd565b6001600160401b0382166000818152603a60205260409020600190810154613a8992916001600160a01b0390911690613b80565b6034546001600160401b0383166000908152603a60205260409081902060010154905163010b3f4560e11b81526001600160a01b03928316926302167e8a92613adb9291169089908b90600401614b25565b600060405180830381600087803b158015613af557600080fd5b505af1158015613b09573d6000803e3d6000fd5b5050603554604051637199812760e11b81526001600160a01b03909116925063e333024e9150613b45908a90889088908b908d90600401614bed565b600060405180830381600087803b158015613b5f57600080fd5b505af1158015613b73573d6000803e3d6000fd5b5050505050505050505050565b60607fe8a0d10254a080ce4a2461fadc237f17f7c822cb1f715ac1ddcb9c4e21ede583848484604051602401613bb893929190614dac565b60408051601f19818403018152918152602080830180516001600160e01b03166001600160e01b03199095169490941790935260335481516348190f0d60e11b815291519294506000936001600160a01b03909116926390321e1a926004808201939291829003018186803b158015613c3057600080fd5b505afa158015613c44573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613c6891906147f2565b603354604080516348190f0d60e11b81529051660110d9316ec0009390930193506001600160a01b03909116916326bdbac9918491309162278d0091889187916390321e1a91600480820192602092909190829003018186803b158015613cce57600080fd5b505afa158015613ce2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613d0691906147f2565b620493e0633b9aca006040518863ffffffff1660e01b8152600401613d3096959493929190614ac7565b6000604051808303818588803b158015613d4957600080fd5b505af1158015613d5d573d6000803e3d6000fd5b50505050505050505050565b6000806000806064603560009054906101000a90046001600160a01b03166001600160a01b03166324bcdfbd6040518163ffffffff1660e01b815260040160206040518083038186803b158015613dbf57600080fd5b505afa158015613dd3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613df791906147f2565b890281613e0057fe5b048803905060006064603560009054906101000a90046001600160a01b03166001600160a01b03166324bcdfbd6040518163ffffffff1660e01b815260040160206040518083038186803b158015613e5757600080fd5b505afa158015613e6b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613e8f91906147f2565b8a0281613e9857fe5b049050600088878942604051602001613eb4949392919061495e565b60408051808303601f1901815291905280516020909101209a9299509097509095505050505050565b6001600160401b0381166000908152603a602052604090819020600281015460039091015491519103906060907f56c61527de4f31a967bf6467f57f70796b043e5585a4ff9d8ff9bfdbf662957190613f3a908590602401614dd9565b60408051601f19818403018152918152602080830180516001600160e01b03166001600160e01b03199095169490941790935260335481516348190f0d60e11b815291519294506000936001600160a01b03909116926390321e1a926004808201939291829003018186803b158015613fb257600080fd5b505afa158015613fc6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613fea91906147f2565b603354604080516348190f0d60e11b81529051660110d9316ec0009390930193506001600160a01b03909116916326bdbac991849130918891889187916390321e1a91600480820192602092909190829003018186803b15801561404d57600080fd5b505afa158015614061573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061408591906147f2565b620493e0633b9aca006040518863ffffffff1660e01b81526004016140af96959493929190614ac7565b6000604051808303818588803b1580156140c857600080fd5b505af11580156140dc573d6000803e3d6000fd5b505050505050505050565b6040518060800160405280600081526020016000815260200160608152602001600081525090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061415057805160ff191683800117855561417d565b8280016001018555821561417d579182015b8281111561417d578251825591602001919060010190614162565b50614189929150614350565b5090565b50805460018160011615610100020316600290046000825580601f106141b357506141d1565b601f0160209004906000526020600020908101906141d19190614350565b50565b8280548282559060005260206000209060040281019282156142585760005260206000209160040282015b82811115614258578254825560018084015481840155600280850180548693869361423c9381860193909281161561010002600019011604614365565b50600382015481600301555050916004019190600401906141ff565b506141899291506143da565b6040518060a0016040528060006001600160a01b03168152602001600081526020016000815260200160008152602001606081525090565b828054828255906000526020600020906003016004900481019282156143445791602002820160005b8382111561430f57835183826101000a8154816001600160401b0302191690836001600160401b0316021790555092602001926008016020816007010492830192600103026142c5565b80156143425782816101000a8154906001600160401b03021916905560080160208160070104928301926001030261430f565b505b5061418992915061440b565b5b808211156141895760008155600101614351565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061439e578054855561417d565b8280016001018555821561417d57600052602060002091601f016020900482015b8281111561417d5782548255916001019190600101906143bf565b80821115614189576000808255600182018190556143fb600283018261418d565b50600060038201556004016143da565b5b8082111561418957805467ffffffffffffffff1916815560010161440c565b600082601f83011261443b578081fd5b813561444e61444982614e3d565b614e17565b915080825283602082850101111561446557600080fd5b8060208401602084013760009082016020015292915050565b805161094481614ebb565b60006020828403121561449a578081fd5b8135612cb881614e98565b6000602082840312156144b6578081fd5b8151612cb881614e98565b6000806000606084860312156144d5578182fd5b83356144e081614e98565b925060208401356144f081614e98565b9150604084013561450081614e98565b809150509250925092565b6000806040838503121561451d578182fd5b823561452881614e98565b915060208301356001600160401b03811115614542578182fd5b61454e8582860161442b565b9150509250929050565b6000806000806080858703121561456d578081fd5b843561457881614e98565b935060208501356001600160401b03811115614592578182fd5b61459e8782880161442b565b9350506040850135915060608501356145b681614ead565b939692955090935050565b60008060008060008060c087890312156145d9578182fd5b86356145e481614e98565b955060208701356001600160401b038111156145fe578283fd5b61460a89828a0161442b565b95505060408701359350606087013592506080870135915060a087013561463081614ead565b809150509295509295509295565b60006020808385031215614650578182fd5b82516001600160401b0380821115614666578384fd5b818501915085601f830112614679578384fd5b815181811115614687578485fd5b8381029150614697848301614e17565b8181528481019084860184860187018a10156146b1578788fd5b8795505b838610156146db576146c78a8261447e565b8352600195909501949186019186016146b5565b5098975050505050505050565b6000602082840312156146f9578081fd5b8151612cb881614ead565b600060208284031215614715578081fd5b81356001600160401b0381111561472a578182fd5b6147368482850161442b565b949350505050565b60006020828403121561474f578081fd5b81516001600160401b03811115614764578182fd5b8201601f81018413614774578182fd5b805161478261444982614e3d565b818152856020838501011115614796578384fd5b6147a7826020830160208601614e6c565b95945050505050565b600080604083850312156147c2578182fd5b82356001600160401b038111156147d7578283fd5b6147e38582860161442b565b95602094909401359450505050565b600060208284031215614803578081fd5b5051919050565b6000806040838503121561481c578182fd5b8235915060208301356001600160401b03811115614542578182fd5b600060208284031215614849578081fd5b8135612cb881614ebb565b600060208284031215614865578081fd5b8151612cb881614ebb565b600080600060608486031215614884578081fd5b833561488f81614ebb565b9250602084013561489f81614e98565b929592945050506040919091013590565b600080604083850312156148c2578182fd5b82356148cd81614ebb565b946020939093013593505050565b6000806000606084860312156148ef578081fd5b83356148fa81614ebb565b925060208401359150604084013561450081614e98565b600060208284031215614922578081fd5b815160ff81168114612cb8578182fd5b6000815180845261494a816020860160208601614e6c565b601f01601f19169290920160200192915050565b60006bffffffffffffffffffffffff198660601b1682528451614988816014850160208901614e6c565b909101601481019390935250603482015260540192915050565b600082516149b4818460208701614e6c565b9190910192915050565b60008083546001808216600081146149dd57600181146149f457614a23565b60ff198316865260028304607f1686019350614a23565b600283048786526020808720875b83811015614a1b5781548a820152908501908201614a02565b505050860193505b509195945050505050565b6001600160a01b0391909116815260200190565b600061014060018060a01b03808e168452808d166020850152508a60408401528960608401528860808401528760a08401528660c08401528560e084015280610100840152614a9381840186614932565b915050826101208301529b9a5050505050505050505050565b6001600160a01b039290921682521515602082015260400190565b600060018060a01b038816825286602083015260c06040830152614aee60c0830187614932565b606083019590955250608081019290925260a0909101529392505050565b6001600160a01b03929092168252602082015260400190565b600060018060a01b0385168252836020830152606060408301526147a76060830184614932565b60006060820160018060a01b03861683526020858185015260606040850152828554600180821660008114614b885760018114614ba657614bde565b60028304607f16865260ff198316608089015260a088019350614bde565b60028304808752614bb68a614e60565b885b82811015614bd45781548b820160800152908401908701614bb8565b8a01608001955050505b50919998505050505050505050565b600060018060a01b038716825285602083015284604083015283606083015260a06080830152614c2060a0830184614932565b979650505050505050565b6020808252825182820181905260009190848201906040850190845b81811015614c6c5783516001600160401b031683529284019291840191600101614c47565b50909695505050505050565b6020810160048310614c8657fe5b91905290565b600060208252612cb86020830184614932565b600060408252614cb26040830185614932565b90508260208301529392505050565b602080825260159082015274496e73756666696369656e74204465706f7369747360581b604082015260600190565b60208082526017908201527f496e73756666696369656e7420426f72726f77696e6773000000000000000000604082015260600190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b6020808252601490820152734e6f7420467269656e646c79204164647265737360601b604082015260600190565b90815260200190565b9283526001600160a01b03919091166020830152604082015260600190565b918252602082015260400190565b6001600160401b0391909116815260200190565b6001600160401b039390931683526001600160a01b03919091166020830152604082015260600190565b6040518181016001600160401b0381118282101715614e3557600080fd5b604052919050565b60006001600160401b03821115614e52578081fd5b50601f01601f191660200190565b60009081526020902090565b60005b83811015614e87578181015183820152602001614e6f565b83811115611f0c5750506000910152565b6001600160a01b03811681146141d157600080fd5b80151581146141d157600080fd5b6001600160401b03811681146141d157600080fdfea2646970667358221220dc0c9c617eca6a2b3e2ffbfc1d6d998964648381d6099afd6796471ecae0369d64736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-eth", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-eth', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
94
0x1ec014c9f133B58587CeB28b671c481A9047511c
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 = 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(); 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); } /// @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); 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); 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] && _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; } 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; } } 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, 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 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 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; } 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) * (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 = 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); 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 = 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 = 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 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(swapedTokens >= 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)); 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(DAI_JOIN_ADDRESS); 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 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(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); 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(); (,,,,,,,,,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); 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 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 = 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) { (, 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 = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB; /// @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])); } } }
0x6080604052600436106102465760003560e01c8063526d646111610139578063a8c90323116100b6578063d98bb5b11161007a578063d98bb5b1146105f5578063deca5f8814610615578063e3bbb4f114610635578063f05def811461064a578063f24ccbfe1461066a578063f851a4401461067f57610246565b8063a8c9032314610576578063b20b720914610596578063bfc36172146105ab578063bfe142a3146105cb578063c91d59fe146105e057610246565b80637f9ad5d6116100fd5780637f9ad5d614610504578063870e44d9146105175780638da5cb5b1461052c578063a56f971814610541578063a7304bf71461055657610246565b8063526d64611461049b578063696806c0146104b05780637753f47b146104c557806379521f02146104da5780637b925ab1146104ef57610246565b806336fc603f116101c7578063441697521161018b578063441697521461041157806349a3d737146104265780634d2ab9dc146104465780634d3f199e1461045b57806351c4a6311461047b57610246565b806336fc603f146103925780633816377e146103a757806339df1878146103c75780633a128322146103dc57806341c0e1b5146103fc57610246565b80631e48907b1161020e5780631e48907b146102f05780631ec18ec0146103105780632a56f602146103305780632b6e6581146103505780632b8f40071461037057610246565b806304c9805c1461024b57806305a363de1461027657806306d5e37e14610298578063087b0286146102c657806318bf60e1146102db575b600080fd5b34801561025757600080fd5b50610260610694565b60405161026d91906127fa565b60405180910390f35b34801561028257600080fd5b5061028b61069a565b60405161026d91906127eb565b3480156102a457600080fd5b506102b86102b3366004612218565b61069f565b60405161026d929190612687565b6102d96102d43660046122c6565b61086d565b005b3480156102e757600080fd5b50610260610bbf565b3480156102fc57600080fd5b506102d961030b36600461211a565b610bc5565b34801561031c57600080fd5b5061026061032b366004612159565b610bfe565b34801561033c57600080fd5b5061026061034b3660046123ba565b610e58565b34801561035c57600080fd5b5061026061036b366004612159565b610e84565b34801561037c57600080fd5b50610385611382565b60405161026d9190612568565b34801561039e57600080fd5b50610260611391565b3480156103b357600080fd5b506102d96103c23660046123ba565b611397565b3480156103d357600080fd5b506103856113c4565b3480156103e857600080fd5b506102d96103f73660046121d1565b6113dc565b34801561040857600080fd5b506102d961147b565b34801561041d57600080fd5b506103856114a0565b34801561043257600080fd5b506102d9610441366004612159565b6114b8565b34801561045257600080fd5b5061026061156e565b34801561046757600080fd5b506102d96104763660046123ba565b611574565b34801561048757600080fd5b506102d9610496366004612191565b61159f565b3480156104a757600080fd5b50610385611629565b3480156104bc57600080fd5b50610260611641565b3480156104d157600080fd5b50610385611647565b3480156104e657600080fd5b5061038561165f565b3480156104fb57600080fd5b5061038561166e565b6102d96105123660046122c6565b611686565b34801561052357600080fd5b50610260611993565b34801561053857600080fd5b5061038561199f565b34801561054d57600080fd5b506102606119ae565b34801561056257600080fd5b506102d961057136600461211a565b6119b4565b34801561058257600080fd5b506102d96105913660046123ba565b6119ed565b3480156105a257600080fd5b50610385611a18565b3480156105b757600080fd5b506102b86105c6366004612218565b611a27565b3480156105d757600080fd5b50610385611b26565b3480156105ec57600080fd5b50610385611b3e565b34801561060157600080fd5b5061026061061036600461211a565b611b51565b34801561062157600080fd5b506102d961063036600461211a565b611c81565b34801561064157600080fd5b50610260611cae565b34801561065657600080fd5b506102d96106653660046123ea565b611cb4565b34801561067657600080fd5b50610385611ce1565b34801561068b57600080fd5b50610385611cf0565b61014d81565b604081565b600854604051632e4aba1f60e21b8152600091829182916001600160a01b03169063b92ae87c906106d4908790600401612568565b60206040518083038186803b1580156106ec57600080fd5b505afa158015610700573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061072491906121fc565b905061072e612071565b60085460405163335d71f560e21b81526001600160a01b039091169063cd75c7d49061075e908890600401612568565b60c06040518083038186803b15801561077657600080fd5b505afa15801561078a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107ae9190612238565b9050816107c45750600092508291506108669050565b60008660018111156107d257fe5b1480156107e157508060a00151155b156107f55750600092508291506108669050565b600061080086611b51565b9050600187600181111561081057fe5b1415610832576020909101516001600160801b03168110935091506108669050565b600087600181111561084057fe5b1415610862576040909101516001600160801b03168111935091506108669050565b5050505b9250929050565b6040516320eb73ed60e11b815273637726f8b08a7abe3ae3acab01a80e2d8ddef77b906341d6e7da906108a4903390600401612568565b60206040518083038186803b1580156108bc57600080fd5b505afa1580156108d0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108f491906121fc565b6109195760405162461bcd60e51b8152600401610910906126e1565b60405180910390fd5b6003546040516370a0823160e01b815281906eb3f879cb30fe243b4dfee438691c04906370a0823190610950903090600401612568565b60206040518083038186803b15801561096857600080fd5b505afa15801561097c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109a091906123d2565b10610a2b5760405163d8ccd0f360e01b81526eb3f879cb30fe243b4dfee438691c049063d8ccd0f3906109d79084906004016127fa565b602060405180830381600087803b1580156109f157600080fd5b505af1158015610a05573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a2991906121fc565b505b600080610a3960008561069f565b9150915081610a4757600080fd5b6000610a54600654610e58565b6007546009546040519293506001600160a01b0391821692638a0e833f9234928a92911690610a89908c908890602401612751565b60408051601f198184030181529181526020820180516001600160e01b03166378e810b160e11b1790525160e086901b6001600160e01b0319168152610ad493929190600401612596565b6000604051808303818588803b158015610aed57600080fd5b505af1158015610b01573d6000803e3d6000fd5b5050505050600080610b14600088611a27565b9150915081610b2257600080fd5b610b2a611cff565b600a546040516001600160a01b039091169063d061ce509030908a90610b569089908790602001612803565b6040516020818303038152906040526040518463ffffffff1660e01b8152600401610b8393929190612618565b600060405180830381600087803b158015610b9d57600080fd5b505af1158015610bb1573d6000803e3d6000fd5b505050505050505050505050565b60065481565b6001546001600160a01b03163314610bdc57600080fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015610c4e57600080fd5b505afa158015610c62573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c86919061213d565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b158015610cd757600080fd5b505afa158015610ceb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d0f919061213d565b90506000826001600160a01b031663bf92857c866040518263ffffffff1660e01b8152600401610d3f9190612568565b6101006040518083038186803b158015610d5857600080fd5b505afa158015610d6c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d9091906124b7565b5050509450505050506000826001600160a01b031663b3596f07886040518263ffffffff1660e01b8152600401610dc79190612568565b60206040518083038186803b158015610ddf57600080fd5b505afa158015610df3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e1791906123d2565b9050610e4b610e2588611d35565b601203600a0a610e358484611dd5565b81610e3c57fe5b04670de05bc096e9c000611e06565b9450505050505b92915050565b6000806004543a1115610e6d57600454610e6f565b3a5b9050610e7b8184611e2e565b9150505b919050565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316632f58b80d6040518163ffffffff1660e01b815260040160206040518083038186803b158015610ed457600080fd5b505afa158015610ee8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f0c919061213d565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b158015610f5d57600080fd5b505afa158015610f71573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f95919061213d565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b158015610fe657600080fd5b505afa158015610ffa573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061101e919061213d565b9050600061102b87611d35565b601203600a0a90506000806000866001600160a01b0316632c6d0e9b8a6040518263ffffffff1660e01b81526004016110649190612568565b6101006040518083038186803b15801561107d57600080fd5b505afa158015611091573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110b5919061244e565b50505094505093509350506000866001600160a01b0316635fc526ff8c6040518263ffffffff1660e01b81526004016110ee9190612568565b60806040518083038186803b15801561110657600080fd5b505afa15801561111a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061113e919061240e565b50509150506000866001600160a01b031663b3596f078d6040518263ffffffff1660e01b81526004016111719190612568565b60206040518083038186803b15801561118957600080fd5b505afa15801561119d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111c191906123d2565b90506000886001600160a01b03166318a4dbca8e8e6040518363ffffffff1660e01b81526004016111f392919061257c565b60206040518083038186803b15801561120b57600080fd5b505afa15801561121f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061124391906123d2565b9050600061125388830284611e06565b90508561126c57509950610e5298505050505050505050565b600061129461128e61127e888b611e2e565b6112898a6064611e2e565b611e52565b87611e62565b90508181116112a357806112a5565b815b90508781106112d457886112b98986611dd5565b816112c057fe5b049c50505050505050505050505050610e52565b60006112ed6112e3888b611e06565b6112898886611e06565b9050600061131f6113108361130b6113058888611e52565b8b611e06565b611e6d565b61131a8c86611e52565b611dd5565b90508781101561135e5761134a611344611339838d611e2e565b6112898c6064611e2e565b82611e62565b9250838311611359578261135b565b835b92505b61136c8b610e358589611dd5565b9e50505050505050505050505050505092915050565b6009546001600160a01b031681565b60055481565b6000546001600160a01b031633146113ae57600080fd5b64746a52880081106113bf57600080fd5b600455565b735c55b921f590a89c1ebe84df170e655a82b6212681565b6000546001600160a01b031633146113f357600080fd5b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6001600160a01b038316141561145757600080546040516001600160a01b039091169183156108fc02918491818181858888f19350505050158015611451573d6000803e3d6000fd5b50611477565b600054611477906001600160a01b0384811691168363ffffffff611e7d16565b5050565b6000546001600160a01b0316331461149257600080fd5b6000546001600160a01b0316ff5b73322d58b9e75a6918f7e7849aee0ff09369977e0881565b6001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14156114ed576114e882824761159f565b611477565b6114778282846001600160a01b03166370a08231306040518263ffffffff1660e01b815260040161151e9190612568565b60206040518083038186803b15801561153657600080fd5b505afa15801561154a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061049691906123d2565b61019081565b6000546001600160a01b0316331461158b57600080fd5b622dc6c0811061159a57600080fd5b600555565b806115a957611624565b6001600160a01b03831673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee141561160a576040516001600160a01b0383169082156108fc029083906000818181858888f19350505050158015611604573d6000803e3d6000fd5b50611624565b6116246001600160a01b038416838363ffffffff611e7d16565b505050565b73637726f8b08a7abe3ae3acab01a80e2d8ddef77b81565b60035481565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b6008546001600160a01b031681565b731b14e8d511c9a4395425314f849bd737baf8208f81565b6040516320eb73ed60e11b815273637726f8b08a7abe3ae3acab01a80e2d8ddef77b906341d6e7da906116bd903390600401612568565b60206040518083038186803b1580156116d557600080fd5b505afa1580156116e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061170d91906121fc565b6117295760405162461bcd60e51b8152600401610910906126e1565b6002546040516370a0823160e01b815281906eb3f879cb30fe243b4dfee438691c04906370a0823190611760903090600401612568565b60206040518083038186803b15801561177857600080fd5b505afa15801561178c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117b091906123d2565b1061183b5760405163d8ccd0f360e01b81526eb3f879cb30fe243b4dfee438691c049063d8ccd0f3906117e79084906004016127fa565b602060405180830381600087803b15801561180157600080fd5b505af1158015611815573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061183991906121fc565b505b60008061184960018561069f565b915091508161185757600080fd5b6000611864600554610e58565b6007546009546040519293506001600160a01b0391821692638a0e833f9234928a92911690611899908c908890602401612751565b60408051601f198184030181529181526020820180516001600160e01b0316633a84827360e11b1790525160e086901b6001600160e01b03191681526118e493929190600401612596565b6000604051808303818588803b1580156118fd57600080fd5b505af1158015611911573d6000803e3d6000fd5b5050505050600080611924600188611a27565b915091508161193257600080fd5b61193a611cff565b600a546040516001600160a01b039091169063d061ce509030908a906119669089908790602001612803565b6040516020818303038152906040526040518463ffffffff1660e01b8152600401610b83939291906125c2565b670de05bc096e9c00081565b6000546001600160a01b031681565b60025481565b6001546001600160a01b031633146119cb57600080fd5b600180546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b03163314611a0457600080fd5b622dc6c08110611a1357600080fd5b600655565b6007546001600160a01b031681565b600080611a32612071565b60085460405163335d71f560e21b81526001600160a01b039091169063cd75c7d490611a62908790600401612568565b60c06040518083038186803b158015611a7a57600080fd5b505afa158015611a8e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ab29190612238565b90506000611abf85611b51565b90506001866001811115611acf57fe5b1415611aef576040909101516001600160801b0316811092509050610866565b6000866001811115611afd57fe5b1415611b1d576020909101516001600160801b0316811192509050610866565b50509250929050565b7324a42fd28c976a61df5d00d0599c34c4f90748c881565b6eb3f879cb30fe243b4dfee438691c0481565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015611ba157600080fd5b505afa158015611bb5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bd9919061213d565b9050600080826001600160a01b031663bf92857c866040518263ffffffff1660e01b8152600401611c0a9190612568565b6101006040518083038186803b158015611c2357600080fd5b505afa158015611c37573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c5b91906124b7565b50505094505093505050611c78611c728383611e6d565b83611dd5565b95945050505050565b6000546001600160a01b03163314611c9857600080fd5b6001546001600160a01b0316156119cb57600080fd5b60045481565b6000546001600160a01b03163314611ccb57600080fd5b8015611cdb576002829055611477565b50600355565b600a546001600160a01b031681565b6001546001600160a01b031681565b4715611d335760405133904780156108fc02916000818181858888f19350505050158015611d31573d6000803e3d6000fd5b505b565b60006001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1415611d6457506012610e7f565b816001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b158015611d9d57600080fd5b505afa158015611db1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e5291906123d2565b600081611df7611ded85670de0b6b3a7640000611e2e565b6002855b04611e6d565b81611dfe57fe5b049392505050565b6000670de0b6b3a7640000611df7611e1e8585611e2e565b6002670de0b6b3a7640000611df1565b6000811580611e4957505080820282828281611e4657fe5b04145b610e5257600080fd5b80820382811115610e5257600080fd5b6000818381611dfe57fe5b80820182811015610e5257600080fd5b6116248363a9059cbb60e01b8484604051602401611e9c92919061266e565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526060611f23826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611f5d9092919063ffffffff16565b8051909150156116245780806020019051810190611f4191906121fc565b6116245760405162461bcd60e51b815260040161091090612707565b6060611f6c8484600085611f74565b949350505050565b6060611f7f85612038565b611f9b5760405162461bcd60e51b8152600401610910906126aa565b60006060866001600160a01b03168587604051611fb8919061254c565b60006040518083038185875af1925050503d8060008114611ff5576040519150601f19603f3d011682016040523d82523d6000602084013e611ffa565b606091505b5091509150811561200e579150611f6c9050565b80511561201e5780518082602001fd5b8360405162461bcd60e51b81526004016109109190612697565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590611f6c575050151592915050565b6040805160c081018252600080825260208201819052918101829052606081018290526080810182905260a081019190915290565b8035610e5281612868565b600082601f8301126120c1578081fd5b813567ffffffffffffffff8111156120d7578182fd5b6120ea601f8201601f1916602001612811565b915080825283602082850101111561210157600080fd5b8060208401602084013760009082016020015292915050565b60006020828403121561212b578081fd5b813561213681612868565b9392505050565b60006020828403121561214e578081fd5b815161213681612868565b6000806040838503121561216b578081fd5b823561217681612868565b9150602083013561218681612868565b809150509250929050565b6000806000606084860312156121a5578081fd5b83356121b081612868565b925060208401356121c081612868565b929592945050506040919091013590565b600080604083850312156121e3578182fd5b82356121ee81612868565b946020939093013593505050565b60006020828403121561220d578081fd5b81516121368161287d565b6000806040838503121561222a578182fd5b823560028110612176578283fd5b600060c08284031215612249578081fd5b61225360c0612811565b825161225e81612868565b8152602083015161226e8161288b565b602082015260408301516122818161288b565b604082015260608301516122948161288b565b606082015260808301516122a78161288b565b608082015260a08301516122ba8161287d565b60a08201529392505050565b600080604083850312156122d8578182fd5b823567ffffffffffffffff808211156122ef578384fd5b610120918501808703831315612303578485fd5b61230c83612811565b61231688836120a6565b815261232588602084016120a6565b60208201526040820135604082015260608201356060820152608082013560808201526123558860a084016120a6565b60a08201526123678860c084016120a6565b60c082015260e082013593508284111561237f578586fd5b61238b888584016120b1565b60e082015261010093508382013584820152809550505050506123b184602085016120a6565b90509250929050565b6000602082840312156123cb578081fd5b5035919050565b6000602082840312156123e3578081fd5b5051919050565b600080604083850312156123fc578182fd5b8235915060208301356121868161287d565b60008060008060808587031215612423578182fd5b84519350602085015192506040850151915060608501516124438161287d565b939692955090935050565b600080600080600080600080610100898b03121561246a578586fd5b885197506020890151965060408901519550606089015194506080890151935060a0890151925060c0890151915060e08901516124a68161287d565b809150509295985092959890939650565b600080600080600080600080610100898b0312156124d3578182fd5b505086516020880151604089015160608a015160808b015160a08c015160c08d015160e0909d0151959e949d50929b919a50985090965094509092509050565b6001600160a01b03169052565b60008151808452612538816020860160208601612838565b601f01601f19169290920160200192915050565b6000825161255e818460208701612838565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b03848116825283166020820152606060408201819052600090611c7890830184612520565b6001600160a01b03848116825283166020820152608060408201819052601290820152714175746f6d6174696341617665526570617960701b60a082015260c060608201819052600090611c7890830184612520565b6001600160a01b0384811682528316602082015260806040820181905260129082015271105d5d1bdb585d1a58d0585d99509bdbdcdd60721b60a082015260c060608201819052600090611c7890830184612520565b6001600160a01b03929092168252602082015260400190565b9115158252602082015260400190565b6000602082526121366020830184612520565b6020808252601d908201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604082015260600190565b6020808252600c908201526b139bdd08185d5d1a08189bdd60a21b604082015260600190565b6020808252602a908201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6040820152691bdd081cdd58d8d9595960b21b606082015260800190565b600060408252612765604083018551612513565b60208401516127776060840182612513565b5060408401516080830152606084015160a0830152608084015160c083015260a08401516127a860e0840182612513565b5060c08401516101006127bd81850183612513565b60e08601516101208581015291506127d9610160850183612520565b95015161014084015250506020015290565b61ffff91909116815260200190565b90815260200190565b918252602082015260400190565b60405181810167ffffffffffffffff8111828210171561283057600080fd5b604052919050565b60005b8381101561285357818101518382015260200161283b565b83811115612862576000848401525b50505050565b6001600160a01b0381168114611d3157600080fd5b8015158114611d3157600080fd5b6001600160801b0381168114611d3157600080fdfea2646970667358221220bb87b2bdc93b561563e7b7fef6cf9ab1e91ae6a39ba0d6e5c5c2c252d568a31664736f6c63430006060033
{"success": true, "error": null, "results": {"detectors": [{"check": "tx-origin", "impact": "Medium", "confidence": "Medium"}, {"check": "name-reused", "impact": "High", "confidence": "High"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-lowlevel", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'tx-origin', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'name-reused', 'impact': 'High', 'confidence': 'High'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-lowlevel', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}
95
0x1ee897382603a2b54d02e542bb1204d1e2ced86b
pragma solidity 0.6.12; library EnumerableSet { struct AddressSet { // Storage of set values address[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (address => 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(AddressSet storage set, address value) internal 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(AddressSet storage set, address value) internal 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. address 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(AddressSet storage set, address value) internal view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function length(AddressSet storage set) internal 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(AddressSet storage set, uint256 index) internal view returns (address) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } } interface IWhitelist { function address_belongs(address _who) external view returns (address); function getUserWallets(address _which) external view returns (address[] memory); } interface IERC20Token { function totalSupply() external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); } interface IGovernanceProxy { function trigger(address contr, bytes calldata params) external; function acceptGovernanceAddress() external; } contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(),"Not Owner"); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0),"Zero address not allowed"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract Governance is Ownable { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet walletsCEO; // wallets of CEO. It should participate in votes with Absolute majority, otherwise Escrowed wallets will not be counted. uint256 public requiredCEO; // number COE wallets require to participate in vote IGovernanceProxy public governanceProxy; IERC20Token[4] public tokenContract; // tokenContract[0] = MainToken, tokenContract[1] = ETN, tokenContract[2] = STOCK IERC20Token[4] public escrowContract; // contract that hold (lock) investor's pre-minted tokens (0-Main, 1-ETN, 2-STOCK) uint256[4] public circulationSupply; // Circulation Supply of according tokens uint256[4] public circulationSupplyUpdated; // timestamp when Circulation Supply was updated IWhitelist public whitelist; // whitelist contract uint256 public closeTime; // timestamp when votes will close uint256 public expeditedLevel = 10; // user who has this percentage of Main token circulation supply can expedite voting uint256 public absoluteLevel = 90; // this percentage of participants voting power considering as Absolute Majority enum Vote {None, Yea, Nay} enum Status {New, Canceled, Approved, Rejected, Pending} struct Rule { address contr; // contract address which have to be triggered uint8[4] majority; // require more than this percentage of participants voting power (in according tokens). string funcAbi; // function ABI (ex. "setGroupBonusRatio(uint256)") } Rule[] rules; struct Ballot { uint256 closeVote; // timestamp when vote will close uint256 ruleId; // rule which edit bytes args; // ABI encoded arguments for proposal which is required to call appropriate function Status status; address creator; // wallet address of ballot creator. uint256[4] votesYea; // YEA votes according communities (tokens) uint256[4] totalVotes; // The total voting power od all participant according communities (tokens) address[] participant; // the users who voted (primary address) uint256 processedParticipants; // The number of participant that was verified. Uses to split verification on many transactions mapping (address => Vote) votes; //Vote: Yea or Nay. If None -the user did not vote. mapping (address => mapping (uint256 => uint256)) power; // Voting power. primary address => community index => voting power uint256 ceoParticipate; //number of ceo wallets participated at voting } Ballot[] ballots; uint256 public unprocessedBallot; // The start index of ballots which are unprocessed and maybe ready for vote. mapping (address => bool) public blockedWallets; // The wallets which are excluded from voting mapping (uint256 => mapping(address => bool)) public isInEscrow; // The wallets which may has pre-minted tokens. Token index => wallet mapping (uint256 => address[]) excluded; // The list of address that should be subtracted from TotalSupply to calculate Circulation Supply. // ex. Company wallet, Downside protection, Vault smart contract. event AddRule(address indexed contractAddress, string funcAbi, uint8[4] majorMain); event SetNewAddress(address indexed previousAddress, address indexed newAddress); event BlockWallet(address indexed walletAddress, bool isAdded); event AddBallot(address indexed creator, uint256 indexed ruleId, uint256 indexed ballotId); event ExpeditedBallot(uint256 indexed ballotId, uint256 indexed closeTime); event ApplyBallot(uint256 indexed ruleId, uint256 indexed ballotId); event NewVote(address indexed voter, address indexed primary, uint256 indexed ballotId); event ChangeVote(address indexed voter, address indexed primary, uint256 indexed ballotId); event PosableMajority(uint256 indexed ballotId); event CEOWallet(address indexed wallet, bool add); /** * @dev Throws if called by any account other than the one of COE wallets. */ modifier onlyCEO() { require(walletsCEO.contains(msg.sender),"Not CEO"); _; } constructor(address CEO_wallet) public { require(CEO_wallet != address(0),"Zero address not allowed"); // add rule with Absolute majority (above 90% participants) which allow to add another rules rules.push(Rule(address(this), [90,0,0,0], "addRule(address,uint8[4],string)")); walletsCEO.add(CEO_wallet); requiredCEO = 1; } function addCEOWallet(address CEO_wallet) external onlyCEO { require(CEO_wallet != address(0),"Zero address not allowed"); walletsCEO.add(CEO_wallet); requiredCEO = walletsCEO.length(); emit CEOWallet(CEO_wallet, true); } function removeCEOWallet(address CEO_wallet) external onlyCEO { require(CEO_wallet != address(0),"Zero address not allowed"); require(walletsCEO.length() > 1, "Should left at least one CEO wallet"); walletsCEO.remove(CEO_wallet); requiredCEO = walletsCEO.length(); emit CEOWallet(CEO_wallet, false); } function setRequiredCEO(uint256 req) external onlyCEO { require(req <= walletsCEO.length(),"More then added wallets"); requiredCEO = req; } function getWalletsCEO() external view returns(address[] memory wallets) { return walletsCEO._values; } /** * @dev Accept Governance in case changing voting contract. */ function acceptGovernanceAddress() external onlyOwner { governanceProxy.acceptGovernanceAddress(); } /** * @dev Calculation Supply = Total Supply - Total balance on Excluded wallets. * @param index The index of token (0 - Main, 1 - ETN, 2 - STOCK). * @return list of excluded address. */ function getExcluded(uint256 index) external view returns(address[] memory) { require(index >= 0 && index < 4, "Wrong index"); return excluded[index]; } /** * @dev Add addresses to excluded list * @param index The index of token (0 - Main, 1 - ETN, 2 - STOCK). * @param wallet List of addresses to add */ function addExcluded(uint256 index, address[] memory wallet) external onlyOwner { require(index >= 0 && index < 4, "Wrong index"); for (uint i = 0; i < wallet.length; i++) { require(wallet[i] != address(0),"Zero address not allowed"); excluded[index].push(wallet[i]); } } /** * @dev Remove addresses from excluded list * @param index The index of token (0 - Main, 1 - ETN, 2 - STOCK). * @param wallet The address to remove */ function removeExcluded(uint256 index, address wallet) external onlyOwner { require(index >= 0 && index < 4, "Wrong index"); require(wallet != address(0),"Zero address not allowed"); uint len = excluded[index].length; for (uint i = 0; i < len; i++) { if (excluded[index][i] == wallet) { excluded[index][i] = excluded[index][len-1]; excluded[index].pop(); } } } /** * @dev Set percentage of participants voting power considering as Absolute Majority * @param level The percentage */ function setAbsoluteLevel(uint256 level) external onlyOwner { require(level > 50 && level <= 100, "Wrong level"); absoluteLevel = level; } /** * @dev Set percentage of total circulation that allows user to expedite proposal * @param level The percentage */ function setExpeditedLevel(uint256 level) external onlyOwner { require(level >= 1 && level <= 100, "Wrong level"); expeditedLevel = level; } /** * @dev Add/Remove address from the list of wallets which is disallowed to vote. * @param wallet The address to add or remove. * @param add Add to the list if true (1) or remove from the list if false (0). */ function manageBlockedWallet(address wallet, bool add) external onlyOwner { emit BlockWallet(wallet, add); blockedWallets[wallet] = add; } /** * @dev Set token contract address. * @param token The address of token contract. * @param index The index of token: 0 - Main, 1 - ETN, 2 - STOCK. */ function setTokenContract(IERC20Token token, uint index) external onlyOwner { require(token != IERC20Token(0) && tokenContract[index] == IERC20Token(0),"Change address not allowed"); tokenContract[index] = token; } /** * @dev Set Escrow contract address, where pre-minted tokens locked (index of token: 0 - Main, 1 - ETN, 2 - STOCK). * @param escrow The address of token contract. * @param index The index of token: 0 - Main, 1 - ETN, 2 - STOCK. */ function setEscrowContract(IERC20Token escrow, uint index) external onlyOwner { require(escrow != IERC20Token(0),"Change address not allowed"); escrowContract[index] = escrow; } /** * @dev Set whitelist contract address to a newAddr. * @param newAddr The address of whitelist contract. */ function setWhitelist(address newAddr) external onlyOwner { require(newAddr != address(0),"Zero address not allowed"); emit SetNewAddress(address(whitelist), newAddr); whitelist = IWhitelist(newAddr); } /** * @dev Set Governance Proxy contract address to a newAddr. * @param newAddr The address of Governance Proxy contract. */ function setGovernanceProxy(address newAddr) external onlyOwner { require(newAddr != address(0),"Zero address not allowed"); emit SetNewAddress(address(governanceProxy), newAddr); governanceProxy = IGovernanceProxy(newAddr); } /** * @dev Update time when new votes will close. Should be called after 00:00:00 UTC 1st day of each month */ function updateCloseTime() external { require(closeTime < block.timestamp, "Wait for 1st day of month"); // close time is not passed (uint year, uint month, uint day) = timestampToDate(block.timestamp); day = 1; if (month == 12) { year++; month = 1; } else { month++; } closeTime = timestampFromDateTime(year, month, day, 0, 0, 0); // 1st day of each month at 00:00:00 UTC uint len = ballots.length; for (uint i = unprocessedBallot; i < len; i++) { if (ballots[i].status == Status.Pending) { if(ballots[i].closeVote == 0) ballots[i].closeVote = closeTime; else ballots[i].closeVote += closeTime; // Expedited vote ballots[i].status = Status.New; } } } /** * @dev Add wallet that received pre-minted tokens. * @param wallet The address of wallet. * @return true if address added. */ function addPremintedWallet(address wallet) external returns(bool){ for (uint i = 0; i < 4; i++ ) { if(address(escrowContract[i]) == msg.sender) { isInEscrow[i][wallet] = true; return true; } } return false; } /** * @dev Add new rule - function that call target contract to change setting. * @param contr The contract address which have to be triggered * @param majority The majority level (%) for the tokens (index: 0 - Main, 1 - ETN, 2 - STOCK). * @param funcAbi The function ABI (ex. "setGroupBonusRatio(uint256)") */ function addRule( address contr, uint8[4] memory majority, string memory funcAbi ) external onlyOwner { require(contr != address(0), "Zero address"); rules.push(Rule(contr, majority, funcAbi)); emit AddRule(contr, funcAbi, majority); } /** * @dev Change majority levels of rules. * @param ruleId The rules index * @param majority The majority level (%) for the tokens (index: 0 - Main, 1 - ETN, 2 - STOCK). */ function changeRuleMajority(uint256 ruleId, uint8[4] memory majority) external onlyOwner { Rule storage r = rules[ruleId]; r.majority = majority; } /** * @dev Change destination contract address of rules. * @param ruleId The rules index * @param contr The new contract address of selected rule. */ function changeRuleAddress(uint256 ruleId, address contr) external onlyOwner { require(contr != address(0), "Zero address"); Rule storage r = rules[ruleId]; r.contr = contr; } /** * @dev Get total number of rules. * @return The total number of rules. */ function getTotalRules() external view returns(uint256) { return rules.length; } /** * @dev Get rules details. * @param ruleId The rules index * @return contr The contract address * @return majority The level of majority in according tokens * @return funcAbi The function Abi */ function getRule(uint256 ruleId) external view returns(address contr, uint8[4] memory majority, string memory funcAbi) { Rule storage r = rules[ruleId]; return (r.contr, r.majority, r.funcAbi); } /** * @dev Get total number of ballots. * @return The total number of ballots. */ function getTotalBallots() external view returns(uint256) { return ballots.length; } /** * @dev Get ballot details. Uses to show the list of available proposal for voting * @param ballotId The ballot index * @return closeVote * @return ruleId * @return args * @return status * @return creator * @return totalVotes * @return votesYea */ function getBallot(uint256 ballotId) external view returns( uint256 closeVote, uint256 ruleId, bytes memory args, Status status, address creator, uint256[4] memory totalVotes, uint256[4] memory votesYea) { Ballot storage b = ballots[ballotId]; return (b.closeVote, b.ruleId, b.args, b.status, b.creator,b.totalVotes,b.votesYea); } /** * @dev Get number of participants who vote for ballot. * @param ballotId The ballot index * @return number of participants who take pert in voting */ function getParticipantsNumber(uint256 ballotId) external view returns(uint256) { return ballots[ballotId].participant.length; } /** * @dev Get number of participant who vote for ballot. * @param ballotId The ballot index * @param start The start position (index) to return data. * @param number The number of records (positions) to return. * @return participants The list of participant primary addresses * @return mainVotes The ist of voting power in main (JNTR) tokens * @return etnVotes The ist of voting power in ETN tokens * @return stockVotes The ist of voting power in Stock tokens * @return votes The list of votes (1 -Yea, 2 -Nay). */ function getParticipants(uint256 ballotId, uint256 start, uint256 number) external view returns(address[] memory participants, uint256[] memory mainVotes, uint256[] memory etnVotes, uint256[] memory stockVotes, Vote[] memory votes) { Ballot storage b = ballots[ballotId]; participants = new address[](number); mainVotes = new uint256[](number); etnVotes = new uint256[](number); stockVotes = new uint256[](number); votes = new Vote[](number); uint256 len = number; if (start + number > b.participant.length) len = b.participant.length - start; for(uint i = 0; i < len; i++) { participants[i] = b.participant[start + i]; mainVotes[i] = b.power[participants[i]][0]; // voting power in community A (Main token) etnVotes[i] = b.power[participants[i]][1]; // voting power in community B (ETN token) stockVotes[i] = b.power[participants[i]][2]; // voting power in community C (STOCK token) votes[i] = b.votes[participants[i]]; } } /** * @dev Create new proposal (ballot) * @param ruleId The rule id which parameter propose to change. * @param args The list of parameters. * @param isExpedited The proposal should be expedited if user have more then 10% of circulation supply. */ function createBallot(uint256 ruleId, bytes memory args, bool isExpedited) external { require(ruleId < rules.length,"Wrong rule ID"); Rule storage r = rules[ruleId]; _getCirculation(r.majority); //require update circulationSupply of Main token (address primary, uint256[4] memory power) = _getVotingPower(msg.sender, r.majority, false, true); uint256 highestPercentage; for (uint i = 0; i < 4; i++) { if (circulationSupply[i] > 0) { uint256 percentage = power[i] * 100 / circulationSupply[i]; // ownership percentage of token if (percentage > highestPercentage) highestPercentage = percentage; } } require(highestPercentage > 0, "Less then 1% of circulationSupply"); uint256 ballotId = ballots.length; Ballot memory b; b.ruleId = ruleId; b.args = args; b.creator = msg.sender; b.votesYea = power; b.totalVotes = power; if(highestPercentage >= expeditedLevel && isExpedited && r.majority[0] < absoluteLevel) { // proposal can be expedited if user has 10% of Main token circulation supply // and requiring majority is less then 90% b.closeVote = 24 hours; } if (block.timestamp + 24 hours <= closeTime) { if(b.closeVote == 0) b.closeVote = closeTime; else { b.closeVote += block.timestamp; // Expedited vote emit ExpeditedBallot(ballotId, b.closeVote); } } else { b.status = Status.Pending; } ballots.push(b); emit AddBallot(msg.sender, ruleId, ballotId); // Add vote Yea ballots[ballotId].participant.push(primary); // add creator primary address as participant ballots[ballotId].votes[primary] = Vote.Yea; for (uint i = 0; i < 4; i++) { if (power[i] > 0) { ballots[ballotId].power[primary][i] = power[i]; } } emit NewVote(msg.sender, primary, ballotId); if (highestPercentage >= 50) { // Check creator voting power for majority 50%+1 of total circulation supply if (_checkMajority(r.majority, power, power, false) == Vote.Yea) { // check Instant execution ballots[ballotId].status = Status.Approved; _executeBallot(ballotId); } } } /** * @dev Cancel proposal. * @param ballotId The ballot index */ function cancelBallot(uint256 ballotId) external { require(ballotId < ballots.length,"Wrong ballot ID"); Ballot storage b = ballots[ballotId]; require(msg.sender == b.creator,"Only creator can cancel"); b.closeVote = block.timestamp; b.status = Status.Canceled; if (unprocessedBallot == ballotId) unprocessedBallot++; } /** * @dev Vote for proposal. * @param ballotId The ballot index * @param v The user vote (1 - Yea, 2 - Nay) */ function vote(uint256 ballotId, Vote v) external { require(ballotId < ballots.length,"Wrong ballot ID"); Ballot storage b = ballots[ballotId]; require(v != Vote.None, "Should vote Yea or Nay"); require(b.status == Status.New, "Voting for disallowed"); require(b.closeVote > block.timestamp, "Ballot expired"); (address primary, uint256[4] memory power) = _getVotingPower(msg.sender, rules[b.ruleId].majority, false, true); if (b.votes[primary] == Vote.None) { // Add vote b.participant.push(primary); // add creator primary address as participant b.votes[primary] = v; for (uint i = 0; i < 4; i++) { if (power[i] > 0) { b.power[primary][i] = power[i]; // store user's voting power b.totalVotes[i] += power[i]; if (v == Vote.Yea) b.votesYea[i] += power[i]; } } // add CEO wallet as participant only for Absolute majority voting if (rules[b.ruleId].majority[0] >= absoluteLevel && walletsCEO.contains(msg.sender)) { b.ceoParticipate++; } emit NewVote(msg.sender, primary, ballotId); } else if (b.votes[primary] != v) { // Change vote b.votes[primary] = v; for (uint i = 0; i < 4; i++) { if (power[i] > 0) { if (v == Vote.Yea) b.votesYea[i] += power[i]; else b.votesYea[i] -= b.power[primary][i]; // remove previous votes b.totalVotes[i] = b.totalVotes[i] + power[i] - b.power[primary][i]; b.power[primary][i] = power[i]; // store user's voting power } } emit ChangeVote(msg.sender, primary, ballotId); } if (_checkMajority(rules[b.ruleId].majority, b.votesYea, b.totalVotes, false) != Vote.None) { // check Instant execution // Server-side may watch for PosableMajority event. // If it emitted the server-side may call verify function to apply changes without waiting voting close. emit PosableMajority(ballotId); } } /** * @dev Verify voting. Can be called many times if there are too many participants which cause Out of Gas error. * @param ballotId The ballot index * @param part The number of participant to verify. Uses to avoid Out of Gas. */ function verify(uint256 ballotId, uint part) external { _verify(ballotId, part); } /** * @dev Verify next unverified voting. Can be called many times if there are too many participants which cause Out of Gas error. * @param part The number of participant to verify. Uses to avoid Out of Gas. */ function verifyNext(uint part) external { uint len = ballots.length; for (uint i = unprocessedBallot; i < len; i++) { if (ballots[i].status == Status.New) { _verify(i, part); return; // exit after verification to avoid Out of Gas error } else if (ballots[i].status != Status.Pending && unprocessedBallot == i) unprocessedBallot++; } } /** * @dev Calculate Circulation Supply = Total supply - sum(excluded addresses balance) */ function getCirculation() external { uint8[4] memory m; for (uint i = 0; i < 4; i++) { if (tokenContract[i] != IERC20Token(0)) m[i] = 50; } _getCirculation(m); } /** * @dev Apply changes from ballot. * @param ballotId The ballot index */ function _executeBallot(uint256 ballotId) internal { require(ballots[ballotId].status == Status.Approved,"Ballot is not Approved"); Ballot storage b = ballots[ballotId]; Rule storage r = rules[b.ruleId]; bytes memory command; command = abi.encodePacked(bytes4(keccak256(bytes(r.funcAbi))), b.args); governanceProxy.trigger(r.contr, command); b.closeVote = block.timestamp; if (unprocessedBallot == ballotId) unprocessedBallot++; emit ApplyBallot(b.ruleId, ballotId); } /** * @dev Verify voting. Can be called many times if there are too many participants which cause Out of Gas error. * @param ballotId The ballot index * @param part The number of participant to verify. Uses to avoid Out of Gas. */ function _verify(uint256 ballotId, uint part) internal { require(ballotId < ballots.length,"Wrong ballot ID"); Ballot storage b = ballots[ballotId]; Rule storage r = rules[b.ruleId]; require(b.status == Status.New, "Can not be verified"); uint256[4] memory totalVotes; uint256[4] memory totalYea; if (b.processedParticipants > 0) { // continue verification totalVotes = b.totalVotes; totalYea = b.votesYea; } uint256 len = b.processedParticipants + part; if (len > b.participant.length || b.closeVote > block.timestamp) // if voting is not closed only etire number of participants should be count len = b.participant.length; bool acceptEscrowed = true; if (r.majority[0] >= absoluteLevel && b.ceoParticipate < requiredCEO) // only for Absolute majority voting acceptEscrowed = false; // reject escrowed wallets if CED did not vote with required number of wallets for (uint i = b.processedParticipants; i < len; i++) { (address primary, uint256[4] memory power) = _getVotingPower(b.participant[i], r.majority, true, acceptEscrowed); for (uint j = 0; j < 4; j++) { if (power[j] > 0) { totalVotes[j] += power[j]; if (b.votes[primary] == Vote.Yea){ totalYea[j] += power[j]; } } b.power[primary][j] = power[j]; // store user's voting power } } b.processedParticipants = len; b.votesYea = totalYea; b.totalVotes = totalVotes; Vote result; if (len == b.participant.length) { // Check Absolute majority at first _getCirculation(r.majority); if (b.closeVote < block.timestamp) // if vote closed { result = _checkMajority(r.majority, totalYea, totalVotes, true); if (result == Vote.None) result = Vote.Nay; // if no required majority then reject proposal } else result = _checkMajority(r.majority, totalYea, totalVotes, false); // Check majority for instant execution if (result == Vote.Yea) { b.status = Status.Approved; _executeBallot(ballotId); } else if (result == Vote.Nay) { b.status = Status.Rejected; b.closeVote = block.timestamp; if (unprocessedBallot == ballotId) unprocessedBallot++; } else b.processedParticipants = 0; //continue voting and reset counter to be able recount votes } } /** * @dev Calculate Circulation Supply = Total supply - sum(excluded addresses balance). * @param tokensApply if element of array = 0 then exclude that token (index: 0 = MainToken, 1 = ETN, 2 = STOCK) * @param votesYea The total voting power said Yea. * @param totalVotes The total voting power of all participants. * @param isClosed the voting is closed * @return result the majority Yea (1), Nay (2) in case absolute majority, or None (0) if no majority. */ function _checkMajority( uint8[4] memory tokensApply, uint256[4] memory votesYea, uint256[4] memory totalVotes, bool isClosed) internal view returns(Vote result) { uint256 majorityYea; uint256 majorityNay; uint256 requireMajority; for (uint i = 0; i < 4; i++) { if (tokensApply[i] != 0) { requireMajority++; // check majority of circulation supply at first if (votesYea[i] * 2 > circulationSupply[i]) majorityYea++; // the voting power is more then 50% of circulation supply else if ((totalVotes[i]-votesYea[i]) * 2 > circulationSupply[i]) majorityNay++; // the voting power is more then 50% of circulation supply else if (isClosed && votesYea[i] > totalVotes[i] * tokensApply[i] / 100) majorityYea++; // the voting power is more then require of all participants total votes power } } if (majorityYea == requireMajority) result = Vote.Yea; else if (majorityNay == requireMajority) result = Vote.Nay; } /** * @dev Calculate Circulation Supply = Total supply - sum(excluded addresses balance) * @param tokensApply if element of array = 0 then exclude that token (index: 0 = MainToken, 1 = ETN, 2 = STOCK) */ function _getCirculation(uint8[4] memory tokensApply) internal { uint256[4] memory total; for (uint i = 0; i < 4; i++) { if (tokensApply[i] != 0 && circulationSupplyUpdated[i] != block.timestamp) { uint len = excluded[i].length; for (uint j = 0; j < len; j++) { total[i] += tokenContract[i].balanceOf(excluded[i][j]); if (escrowContract[i] != IERC20Token(0) && isInEscrow[i][excluded[i][j]]) { total[i] += escrowContract[i].balanceOf(excluded[i][j]); } } uint256 t = IERC20Token(tokenContract[i]).totalSupply(); require(t >= total[i], "Total Supply less then accounts balance"); circulationSupply[i] = t - total[i]; circulationSupplyUpdated[i] = block.timestamp; // timestamp when circulationSupply updates } } } /** * @dev Calculate Voting Power of voter in provided communities (tokens) * @param voter The wallet address of voter. * @param tokensApply if element of array = 0 then exclude that token (index: 0 = MainToken, 1 = ETN, 2 = STOCK) * @param isPrimary is true when voter address is primary address. Uses in verify function. * @return primary - The primary address the wallet belong. * @return votingPower - the voting power according communities. */ function _getVotingPower(address voter, uint8[4] memory tokensApply, bool isPrimary, bool acceptEscrowed) internal view returns(address primary, uint256[4] memory votingPower) { if (isPrimary) primary = voter; else primary = whitelist.address_belongs(voter); require (!blockedWallets[primary], "Wallet is blocked for voting"); address[] memory userWallets; if (primary != address(0)) { userWallets = whitelist.getUserWallets(primary); } else { primary = voter; userWallets = new address[](0); } bool hasPower = false; for (uint i = 0; i < 4; i++) { if (tokensApply[i] != 0) { votingPower[i] += tokenContract[i].balanceOf(primary); if (acceptEscrowed && escrowContract[i] != IERC20Token(0) && isInEscrow[i][primary]) { votingPower[i] += escrowContract[i].balanceOf(primary); } for(uint j = 0; j < userWallets.length; j++) { votingPower[i] += tokenContract[i].balanceOf(userWallets[j]); if (acceptEscrowed && escrowContract[i] != IERC20Token(0) && isInEscrow[i][userWallets[j]]) { votingPower[i] += escrowContract[i].balanceOf(userWallets[j]); } } if (votingPower[i] > 0) hasPower = true; } } require(isPrimary || hasPower, "No voting power"); } /** * @dev Calculate number of days from 1/1/1970 to selected date. * @param year The year number * @param month The month number * @param day The day number * @return _days number of day. */ 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 - 2440588; _days = uint(__days); } /** * @dev Calculate timestamp (UNIX time) of selected date and time. * @param year The year number * @param month The month number * @param day The day number * @param hour number of hours * @param minute number of minutes * @param second number of seconds * @return timestamp UNIX time */ function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * 86400 + hour * 3600 + minute * 60 + second; } function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + 2440588; 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); } /** * @dev Calculate date from timestamp (UNIX time) . * @param timestamp UNIX time * @return year The year number * @return month The month number * @return day The day number */ function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / 86400); } }
0x608060405234801561001057600080fd5b50600436106102bb5760003560e01c80638691058e11610182578063a5e02039116100e9578063e43807f9116100a2578063f2fde38b1161007c578063f2fde38b14610c0a578063f5609aa414610c30578063f9d5ee7514610c38578063fd1ef5e914610d52576102bb565b8063e43807f914610ade578063eabe98e414610b0c578063f18e9af414610bb4576102bb565b8063a5e02039146108ce578063abe1736d146108f4578063ae903098146108fc578063bf151cb814610928578063cf216ecf14610930578063db141afb1461094d576102bb565b8063943e82161161013b578063943e82161461070c57806394b3241e146107325780639dae083814610816578063a2994eff1461086e578063a30fb02014610894578063a34fdd62146108b1576102bb565b80638691058e1461067157806386b5d147146106975780638c988b87146106d75780638da5cb5b146106f45780638f32d59b146106fc57806393e59dc114610704576102bb565b80634629f3771161022657806366987206116101df57806366987206146105695780636b0719e9146105715780636d0c11081461061e578063715018a61461063b5780637c2338ec14610643578063854cff2f1461064b576102bb565b80634629f3771461042d578063469a97b214610435578063484620371461043d57806357eaef051461050b57806362474c4314610544578063627749e614610561576102bb565b8063324114691161027857806332411469146103675780633a0d09411461038d5780633e4661a5146103b957806341161b10146103d6578063419723e7146103f957806342a6112b14610401576102bb565b80630ca2f66f146102c057806314866bc2146102ee578063155ca224146102f65780631d28a7a91461031357806330eba8de14610330578063317b1a331461035f575b600080fd5b6102ec600480360360408110156102d657600080fd5b50803590602001356001600160a01b0316610d78565b005b6102ec610f67565b6102ec6004803603602081101561030c57600080fd5b5035611003565b6102ec6004803603602081101561032957600080fd5b5035611111565b61034d6004803603602081101561034657600080fd5b50356111ba565b60408051918252519081900360200190f35b61034d6111ce565b6102ec6004803603602081101561037d57600080fd5b50356001600160a01b03166111d4565b6102ec600480360360408110156103a357600080fd5b50803590602001356001600160a01b0316611307565b61034d600480360360208110156103cf57600080fd5b50356113d8565b6102ec600480360360408110156103ec57600080fd5b50803590602001356113e5565b61034d6113ef565b6102ec6004803603604081101561041757600080fd5b506001600160a01b0381351690602001356113f5565b61034d6114eb565b6102ec6114f1565b61045a6004803603602081101561045357600080fd5b5035611695565b6040516001600160a01b03841681526020810183608080838360005b8381101561048e578181015183820152602001610476565b5050505090500180602001828103825283818151815260200191508051906020019080838360005b838110156104ce5781810151838201526020016104b6565b50505050905090810190601f1680156104fb5780820380516001836020036101000a031916815260200191505b5094505050505060405180910390f35b6105286004803603602081101561052157600080fd5b50356117c2565b604080516001600160a01b039092168252519081900360200190f35b61034d6004803603602081101561055a57600080fd5b50356117df565b61034d61180b565b61034d611811565b6102ec6004803603606081101561058757600080fd5b81359190810190604081016020820135600160201b8111156105a857600080fd5b8201836020820111156105ba57600080fd5b803590602001918460018302840111600160201b831117156105db57600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295505050503515159050611817565b6102ec6004803603602081101561063457600080fd5b5035611e37565b6102ec611ed1565b610528611f60565b6102ec6004803603602081101561066157600080fd5b50356001600160a01b0316611f6f565b6102ec6004803603602081101561068757600080fd5b50356001600160a01b0316612059565b6106c3600480360360408110156106ad57600080fd5b50803590602001356001600160a01b0316612144565b604080519115158252519081900360200190f35b6102ec600480360360208110156106ed57600080fd5b5035612164565b610528612218565b6106c3612227565b610528612238565b6102ec6004803603604081101561072257600080fd5b508035906020013560ff16612247565b6102ec600480360360c081101561074857600080fd5b6040805160808181019092526001600160a01b0384351693928301929160a0830191906020840190600490839083908082843760009201919091525091949392602081019250359050600160201b8111156107a257600080fd5b8201836020820111156107b457600080fd5b803590602001918460018302840111600160201b831117156107d557600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550612912945050505050565b61081e612b3b565b60408051602080825283518183015283519192839290830191858101910280838360005b8381101561085a578181015183820152602001610842565b505050509050019250505060405180910390f35b6106c36004803603602081101561088457600080fd5b50356001600160a01b0316612ba0565b610528600480360360208110156108aa57600080fd5b5035612c14565b61081e600480360360208110156108c757600080fd5b5035612c21565b6106c3600480360360208110156108e457600080fd5b50356001600160a01b0316612cd0565b61034d612ce5565b6102ec6004803603604081101561091257600080fd5b506001600160a01b038135169060200135612ceb565b6102ec612d99565b6102ec6004803603602081101561094657600080fd5b5035612dfa565b6109766004803603606081101561096357600080fd5b5080359060208101359060400135612e95565b60405180806020018060200180602001806020018060200186810386528b818151815260200191508051906020019060200280838360005b838110156109c65781810151838201526020016109ae565b5050505090500186810385528a818151815260200191508051906020019060200280838360005b83811015610a055781810151838201526020016109ed565b50505050905001868103845289818151815260200191508051906020019060200280838360005b83811015610a44578181015183820152602001610a2c565b50505050905001868103835288818151815260200191508051906020019060200280838360005b83811015610a83578181015183820152602001610a6b565b50505050905001868103825287818151815260200191508051906020019060200280838360005b83811015610ac2578181015183820152602001610aaa565b505050509050019a505050505050505050505060405180910390f35b6102ec60048036036040811015610af457600080fd5b506001600160a01b038135169060200135151561324c565b6102ec60048036036040811015610b2257600080fd5b81359190810190604081016020820135600160201b811115610b4357600080fd5b820183602082011115610b5557600080fd5b803590602001918460208302840111600160201b83111715610b7657600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295506132fd945050505050565b6102ec600480360360a0811015610bca57600080fd5b604080516080818101909252833593928301929160a0830191906020840190600490839083908082843760009201919091525091945061345b9350505050565b6102ec60048036036020811015610c2057600080fd5b50356001600160a01b03166134d0565b61034d61351e565b610c5560048036036020811015610c4e57600080fd5b5035613524565b6040518088815260200187815260200180602001866004811115610c7557fe5b81526001600160a01b038616602082015260400184608080838360005b83811015610caa578181015183820152602001610c92565b5050505090500183600460200280838360005b83811015610cd5578181015183820152602001610cbd565b50505050905001828103825287818151815260200191508051906020019080838360005b83811015610d11578181015183820152602001610cf9565b50505050905090810190601f168015610d3e5780820380516001836020036101000a031916815260200191505b509850505050505050505060405180910390f35b6102ec60048036036020811015610d6857600080fd5b50356001600160a01b0316613696565b610d80612227565b610dbd576040805162461bcd60e51b81526020600482015260096024820152682737ba1027bbb732b960b91b604482015290519081900360640190fd5b60048210610e00576040805162461bcd60e51b815260206004820152600b60248201526a0aee4dedcce40d2dcc8caf60ab1b604482015290519081900360640190fd5b6001600160a01b038116610e49576040805162461bcd60e51b815260206004820152601860248201526000805160206150e8833981519152604482015290519081900360640190fd5b6000828152601e6020526040812054905b81811015610f61576000848152601e6020526040902080546001600160a01b038516919083908110610e8857fe5b6000918252602090912001546001600160a01b03161415610f59576000848152601e6020526040902080546000198401908110610ec157fe5b6000918252602080832090910154868352601e909152604090912080546001600160a01b039092169183908110610ef457fe5b600091825260208083209190910180546001600160a01b0319166001600160a01b039490941693909317909255858152601e90915260409020805480610f3657fe5b600082815260209020810160001990810180546001600160a01b03191690550190555b600101610e5a565b50505050565b610f6f612227565b610fac576040805162461bcd60e51b81526020600482015260096024820152682737ba1027bbb732b960b91b604482015290519081900360640190fd5b6004805460408051630a4335e160e11b815290516001600160a01b03909216926314866bc292828201926000929082900301818387803b158015610fef57600080fd5b505af1158015610f61573d6000803e3d6000fd5b601a54811061104b576040805162461bcd60e51b815260206004820152600f60248201526e15dc9bdb99c818985b1b1bdd081251608a1b604482015290519081900360640190fd5b6000601a828154811061105a57fe5b906000526020600020906011020190508060030160019054906101000a90046001600160a01b03166001600160a01b0316336001600160a01b0316146110e7576040805162461bcd60e51b815260206004820152601760248201527f4f6e6c792063726561746f722063616e2063616e63656c000000000000000000604482015290519081900360640190fd5b42815560038101805460ff19166001179055601b5482141561110d57601b805460010190555b5050565b61111c6001336137dd565b611157576040805162461bcd60e51b81526020600482015260076024820152664e6f742043454f60c81b604482015290519081900360640190fd5b61116160016137fe565b8111156111b5576040805162461bcd60e51b815260206004820152601760248201527f4d6f7265207468656e2061646465642077616c6c657473000000000000000000604482015290519081900360640190fd5b600355565b600d81600481106111c757fe5b0154905081565b601a5490565b6111df6001336137dd565b61121a576040805162461bcd60e51b81526020600482015260076024820152664e6f742043454f60c81b604482015290519081900360640190fd5b6001600160a01b038116611263576040805162461bcd60e51b815260206004820152601860248201526000805160206150e8833981519152604482015290519081900360640190fd5b600161126f60016137fe565b116112ab5760405162461bcd60e51b81526004018080602001828103825260238152602001806150c56023913960400191505060405180910390fd5b6112b6600182613802565b506112c160016137fe565b600355604080516000815290516001600160a01b038316917fad778e03daea9f91a9bdab82d8408cd6da95e76dfe65a4dc76c3a03ffe24355b919081900360200190a250565b61130f612227565b61134c576040805162461bcd60e51b81526020600482015260096024820152682737ba1027bbb732b960b91b604482015290519081900360640190fd5b6001600160a01b038116611396576040805162461bcd60e51b815260206004820152600c60248201526b5a65726f206164647265737360a01b604482015290519081900360640190fd5b6000601983815481106113a557fe5b6000918252602090912060039091020180546001600160a01b0319166001600160a01b0393909316929092179091555050565b601181600481106111c757fe5b61110d8282613909565b601b5481565b6113fd612227565b61143a576040805162461bcd60e51b81526020600482015260096024820152682737ba1027bbb732b960b91b604482015290519081900360640190fd5b6001600160a01b03821615801590611469575060006005826004811061145c57fe5b01546001600160a01b0316145b6114ba576040805162461bcd60e51b815260206004820152601a60248201527f4368616e67652061646472657373206e6f7420616c6c6f776564000000000000604482015290519081900360640190fd5b81600582600481106114c857fe5b0180546001600160a01b0319166001600160a01b03929092169190911790555050565b60195490565b4260165410611547576040805162461bcd60e51b815260206004820152601960248201527f5761697420666f722031737420646179206f66206d6f6e746800000000000000604482015290519081900360640190fd5b600080600061155542613e1e565b9250925092506001905081600c141561157557600192830192915061157c565b6001909101905b61158c8383836000806000613e3d565b601655601a54601b545b8181101561168e576004601a82815481106115ad57fe5b600091825260209091206003601190920201015460ff1660048111156115cf57fe5b141561168657601a81815481106115e257fe5b9060005260206000209060110201600001546000141561162257601654601a828154811061160c57fe5b600091825260209091206011909102015561164a565b601654601a828154811061163257fe5b60009182526020909120601190910201805490910190555b6000601a828154811061165957fe5b60009182526020909120600360119092020101805460ff1916600183600481111561168057fe5b02179055505b600101611596565b5050505050565b600061169f614e2d565b60606000601985815481106116b057fe5b60009182526020822060039091020180546040805160808101918290529294506001600160a01b039091169260018501926002860192909184916004918390855b825461010083900a900460ff168152602060019283018181049485019490930390920291018084116116f1575050855460408051602060026001851615610100026000190190941693909304601f81018490048402820184019092528181529698508795509350850191508390508280156117ad5780601f10611782576101008083540402835291602001916117ad565b820191906000526020600020905b81548152906001019060200180831161179057829003601f168201915b50505050509050935093509350509193909250565b600981600481106117cf57fe5b01546001600160a01b0316905081565b6000601a82815481106117ee57fe5b9060005260206000209060110201600c018054905090505b919050565b60165481565b60185481565b601954831061185d576040805162461bcd60e51b815260206004820152600d60248201526c15dc9bdb99c81c9d5b19481251609a1b604482015290519081900360640190fd5b60006019848154811061186c57fe5b600091825260208220604080516080810191829052600390930290910193506118d39260018501916004918390855b825461010083900a900460ff1681526020600192830181810494850194909303909202910180841161189b5790505050505050613e67565b60006118dd614e2d565b604080516080810191829052611939913391906001870190600490826000855b825461010083900a900460ff168152602060019283018181049485019490930390920291018084116118fd5790505050505050600060016141fb565b90925090506000805b60048110156119a7576000600d826004811061195a57fe5b0154111561199f576000600d826004811061197157fe5b015484836004811061197f57fe5b60200201516064028161198e57fe5b0490508281111561199d578092505b505b600101611942565b50600081116119e75760405162461bcd60e51b81526004018080602001828103825260218152602001806151086021913960400191505060405180910390fd5b601a546119f2614e4b565b602081018990526040810188905233608082015260a0810184905260c081018490526017548310801590611a235750865b8015611a375750601854600187015460ff16105b15611a43576201518081525b60165442620151800111611a99578051611a61576016548152611a94565b8051420180825260405183907f9ed43afbaea7fd5a97ba95f36ae3dc2b29134925933f1c9f094fada5b1c74f0190600090a35b611aa1565b600460608201525b601a8054600181018255600091909152815160119091027f057c384a7d1c54f3a1b2e5e67b2617b8224fdfd1ea7234eea573a6ff665ff63e81019182556020808401517f057c384a7d1c54f3a1b2e5e67b2617b8224fdfd1ea7234eea573a6ff665ff63f83015560408401518051859493611b42937f057c384a7d1c54f3a1b2e5e67b2617b8224fdfd1ea7234eea573a6ff665ff640909101920190614eb5565b50606082015160038201805460ff19166001836004811115611b6057fe5b021790555060808201516003820180546001600160a01b0390921661010002610100600160a81b031990921691909117905560a0820151611ba79060048084019190614f33565b5060c0820151611bbd9060088301906004614f33565b5060e08201518051611bd991600c840191602090910190614f60565b50610100820151600d8201556101209091015160109091015560405182908a9033907f32f839e764a213b6556ae7aaa82c0f7f4c1f2436a287e0ff1aae1038637d426f90600090a4601a8281548110611c2e57fe5b60009182526020808320601192909202909101600c01805460018082018355918452919092200180546001600160a01b0319166001600160a01b038816179055601a805484908110611c7c57fe5b600091825260208083206001600160a01b038a168452600e60119093020191909101905260409020805460ff19166001836002811115611cb857fe5b021790555060005b6004811015611d3b576000858260048110611cd757fe5b60200201511115611d3357848160048110611cee57fe5b6020020151601a8481548110611d0057fe5b600091825260208083206001600160a01b038b168452600f60119093020191909101815260408083208584529091529020555b600101611cc0565b5060405182906001600160a01b0387169033907f94c5996438a85a41e683585fc1a40635372ccd17c4d948a7c48ae50679bdf5c890600090a460328310611e2c576001604080516080810191829052611dd79160018a0190600490826000855b825461010083900a900460ff16815260206001928301818104948501949093039092029101808411611d9b579050505050505086876000614870565b6002811115611de257fe5b1415611e2c576002601a8381548110611df757fe5b60009182526020909120600360119092020101805460ff19166001836004811115611e1e57fe5b0217905550611e2c826149a4565b505050505050505050565b611e3f612227565b611e7c576040805162461bcd60e51b81526020600482015260096024820152682737ba1027bbb732b960b91b604482015290519081900360640190fd5b603281118015611e8d575060648111155b611ecc576040805162461bcd60e51b815260206004820152600b60248201526a15dc9bdb99c81b195d995b60aa1b604482015290519081900360640190fd5b601855565b611ed9612227565b611f16576040805162461bcd60e51b81526020600482015260096024820152682737ba1027bbb732b960b91b604482015290519081900360640190fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6004546001600160a01b031681565b611f77612227565b611fb4576040805162461bcd60e51b81526020600482015260096024820152682737ba1027bbb732b960b91b604482015290519081900360640190fd5b6001600160a01b038116611ffd576040805162461bcd60e51b815260206004820152601860248201526000805160206150e8833981519152604482015290519081900360640190fd5b6015546040516001600160a01b038084169216907fdcfb84bc948acc41559a77bd534eb5bca79b091c1eecdf1a441cad8662d25f7890600090a3601580546001600160a01b0319166001600160a01b0392909216919091179055565b6120646001336137dd565b61209f576040805162461bcd60e51b81526020600482015260076024820152664e6f742043454f60c81b604482015290519081900360640190fd5b6001600160a01b0381166120e8576040805162461bcd60e51b815260206004820152601860248201526000805160206150e8833981519152604482015290519081900360640190fd5b6120f3600182613780565b506120fe60016137fe565b600355604080516001815290516001600160a01b038316917fad778e03daea9f91a9bdab82d8408cd6da95e76dfe65a4dc76c3a03ffe24355b919081900360200190a250565b601d60209081526000928352604080842090915290825290205460ff1681565b601a54601b545b81811015612212576000601a828154811061218257fe5b600091825260209091206003601190920201015460ff1660048111156121a457fe5b14156121bb576121b48184613909565b5050612215565b6004601a82815481106121ca57fe5b600091825260209091206003601190920201015460ff1660048111156121ec57fe5b141580156121fb575080601b54145b1561220a57601b805460010190555b60010161216b565b50505b50565b6000546001600160a01b031690565b6000546001600160a01b0316331490565b6015546001600160a01b031681565b601a54821061228f576040805162461bcd60e51b815260206004820152600f60248201526e15dc9bdb99c818985b1b1bdd081251608a1b604482015290519081900360640190fd5b6000601a838154811061229e57fe5b60009182526020822060119091020191508260028111156122bb57fe5b1415612307576040805162461bcd60e51b815260206004820152601660248201527553686f756c6420766f746520596561206f72204e617960501b604482015290519081900360640190fd5b6000600382015460ff16600481111561231c57fe5b14612366576040805162461bcd60e51b8152602060048201526015602482015274159bdd1a5b99c8199bdc88191a5cd85b1b1bddd959605a1b604482015290519081900360640190fd5b805442106123ac576040805162461bcd60e51b815260206004820152600e60248201526d10985b1b1bdd08195e1c1a5c995960921b604482015290519081900360640190fd5b60006123b6614e2d565b6124173360198560010154815481106123cb57fe5b600091825260209182902060408051608081019182905260039093029091016001908101805460ff168452929360049291849186018084116118fd5790505050505050600060016141fb565b909250905060006001600160a01b0383166000908152600e8501602052604090205460ff16600281111561244757fe5b141561260857600c83018054600180820183556000928352602080842090920180546001600160a01b0319166001600160a01b0387169081179091558352600e860190915260409091208054869260ff19909116908360028111156124a857fe5b021790555060005b600481101561257a5760008282600481106124c757fe5b60200201511115612572578181600481106124de57fe5b602090810291909101516001600160a01b0385166000908152600f870183526040808220858352909352919091205581816004811061251957fe5b602002015184600801826004811061252d57fe5b0180549091019055600185600281111561254357fe5b14156125725781816004811061255557fe5b602002015184600401826004811061256957fe5b01805490910190555b6001016124b0565b50601854601984600101548154811061258f57fe5b600091825260209091206001600390920201015460ff16108015906125ba57506125ba6001336137dd565b156125cb5760108301805460010190555b60405185906001600160a01b0384169033907f94c5996438a85a41e683585fc1a40635372ccd17c4d948a7c48ae50679bdf5c890600090a46127f7565b83600281111561261457fe5b6001600160a01b0383166000908152600e8501602052604090205460ff16600281111561263d57fe5b146127f7576001600160a01b0382166000908152600e840160205260409020805485919060ff1916600183600281111561267357fe5b021790555060005b60048110156127bd57600082826004811061269257fe5b602002015111156127b55760018560028111156126ab57fe5b14156126de578181600481106126bd57fe5b60200201518460040182600481106126d157fe5b018054909101905561271e565b6001600160a01b0383166000908152600f8501602090815260408083208484529091529020546004808601908390811061271457fe5b0180549190910390555b6001600160a01b0383166000908152600f85016020908152604080832084845290915290205482826004811061275057fe5b602002015185600801836004811061276457fe5b0154010384600801826004811061277757fe5b015581816004811061278557fe5b602090810291909101516001600160a01b0385166000908152600f87018352604080822085835290935291909120555b60010161267b565b5060405185906001600160a01b0384169033907fedbaaf37298af46a75a97cd92f060695f25eafb242b77b2c6b579f07fa1e7e7f90600090a45b60006128d0601985600101548154811061280d57fe5b60009182526020822060408051608081019182905293600390930290910160010191600491908390855b825461010083900a900460ff16815260206001928301818104948501949093039092029101808411612837575050604080516080810191829052945060048b810194509250905082845b815481526020019060010190808311612881575050604080516080810191829052935060088b0192506004915082845b8154815260200190600101908083116128b15750505050506000614870565b60028111156128db57fe5b1461168e5760405185907f48a6bbbc082c68e04f02544b5bec1ae07c423d0f03abe65f176eab49cb711aa790600090a25050505050565b61291a612227565b612957576040805162461bcd60e51b81526020600482015260096024820152682737ba1027bbb732b960b91b604482015290519081900360640190fd5b6001600160a01b0383166129a1576040805162461bcd60e51b815260206004820152600c60248201526b5a65726f206164647265737360a01b604482015290519081900360640190fd5b604080516060810182526001600160a01b038581168252602082018581529282018490526019805460018101825560009190915282517f944998273e477b495144fb8794c914197f3ccb46be2900f4698fd0ef743c9695600390920291820180546001600160a01b03191691909316178255925191929091612a47917f944998273e477b495144fb8794c914197f3ccb46be2900f4698fd0ef743c969601906004614fc1565b5060408201518051612a63916002840191602090910190614eb5565b505050826001600160a01b03167fd5113003af6e925540acd35cdd30915a3c27b04053032b334bbb47d63d63b92a8284604051808060200183600460200280838360005b83811015612abf578181015183820152602001612aa7565b50505050905001828103825284818151815260200191508051906020019080838360005b83811015612afb578181015183820152602001612ae3565b50505050905090810190601f168015612b285780820380516001836020036101000a031916815260200191505b50935050505060405180910390a2505050565b60606001600001805480602002602001604051908101604052809291908181526020018280548015612b9657602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311612b78575b5050505050905090565b6000805b6004811015612c0b573360098260048110612bbb57fe5b01546001600160a01b03161415612c03576000908152601d602090815260408083206001600160a01b03861684529091529020805460ff191660019081179091559050611806565b600101612ba4565b50600092915050565b600581600481106117cf57fe5b606060048210612c66576040805162461bcd60e51b815260206004820152600b60248201526a0aee4dedcce40d2dcc8caf60ab1b604482015290519081900360640190fd5b6000828152601e602090815260409182902080548351818402810184019094528084529091830182828015612cc457602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311612ca6575b50505050509050919050565b601c6020526000908152604090205460ff1681565b60175481565b612cf3612227565b612d30576040805162461bcd60e51b81526020600482015260096024820152682737ba1027bbb732b960b91b604482015290519081900360640190fd5b6001600160a01b038216612d8b576040805162461bcd60e51b815260206004820152601a60248201527f4368616e67652061646472657373206e6f7420616c6c6f776564000000000000604482015290519081900360640190fd5b81600982600481106114c857fe5b612da1614e2d565b60005b6004811015612df057600060058260048110612dbc57fe5b01546001600160a01b031614612de8576032828260048110612dda57fe5b60ff90921660209290920201525b600101612da4565b5061221581613e67565b612e02612227565b612e3f576040805162461bcd60e51b81526020600482015260096024820152682737ba1027bbb732b960b91b604482015290519081900360640190fd5b60018110158015612e51575060648111155b612e90576040805162461bcd60e51b815260206004820152600b60248201526a15dc9bdb99c81b195d995b60aa1b604482015290519081900360640190fd5b601755565b60608060608060606000601a8981548110612eac57fe5b906000526020600020906011020190508667ffffffffffffffff81118015612ed357600080fd5b50604051908082528060200260200182016040528015612efd578160200160208202803683370190505b5095508667ffffffffffffffff81118015612f1757600080fd5b50604051908082528060200260200182016040528015612f41578160200160208202803683370190505b5094508667ffffffffffffffff81118015612f5b57600080fd5b50604051908082528060200260200182016040528015612f85578160200160208202803683370190505b5093508667ffffffffffffffff81118015612f9f57600080fd5b50604051908082528060200260200182016040528015612fc9578160200160208202803683370190505b5092508667ffffffffffffffff81118015612fe357600080fd5b5060405190808252806020026020018201604052801561300d578160200160208202803683370190505b50600c8201549092508790898201111561302b5750600c8101548890035b60005b8181101561323e5782600c01818b018154811061304757fe5b9060005260206000200160009054906101000a90046001600160a01b031688828151811061307157fe5b60200260200101906001600160a01b031690816001600160a01b03168152505082600f0160008983815181106130a357fe5b60200260200101516001600160a01b03166001600160a01b031681526020019081526020016000206000808152602001908152602001600020548782815181106130e957fe5b60200260200101818152505082600f01600089838151811061310757fe5b60200260200101516001600160a01b03166001600160a01b031681526020019081526020016000206000600181526020019081526020016000205486828151811061314e57fe5b60200260200101818152505082600f01600089838151811061316c57fe5b60200260200101516001600160a01b03166001600160a01b03168152602001908152602001600020600060028152602001908152602001600020548582815181106131b357fe5b60200260200101818152505082600e0160008983815181106131d157fe5b60200260200101516001600160a01b03166001600160a01b0316815260200190815260200160002060009054906101000a900460ff1684828151811061321357fe5b6020026020010190600281111561322657fe5b9081600281111561323357fe5b90525060010161302e565b505050939792965093509350565b613254612227565b613291576040805162461bcd60e51b81526020600482015260096024820152682737ba1027bbb732b960b91b604482015290519081900360640190fd5b60408051821515815290516001600160a01b038416917f4763e330ab75e782bfd2fc8d3b5995911099f851c8a4cfce85d7d57d1db3ffe9919081900360200190a26001600160a01b03919091166000908152601c60205260409020805460ff1916911515919091179055565b613305612227565b613342576040805162461bcd60e51b81526020600482015260096024820152682737ba1027bbb732b960b91b604482015290519081900360640190fd5b60048210613385576040805162461bcd60e51b815260206004820152600b60248201526a0aee4dedcce40d2dcc8caf60ab1b604482015290519081900360640190fd5b60005b81518110156122125760006001600160a01b03168282815181106133a857fe5b60200260200101516001600160a01b031614156133fa576040805162461bcd60e51b815260206004820152601860248201526000805160206150e8833981519152604482015290519081900360640190fd5b6000838152601e60205260409020825183908390811061341657fe5b60209081029190910181015182546001808201855560009485529290932090920180546001600160a01b0319166001600160a01b039093169290921790915501613388565b613463612227565b6134a0576040805162461bcd60e51b81526020600482015260096024820152682737ba1027bbb732b960b91b604482015290519081900360640190fd5b6000601983815481106134af57fe5b600091825260209091206003909102019050610f6160018201836004614fc1565b6134d8612227565b613515576040805162461bcd60e51b81526020600482015260096024820152682737ba1027bbb732b960b91b604482015290519081900360640190fd5b61221581614c77565b60035481565b6000806060600080613534614e2d565b61353c614e2d565b6000601a898154811061354b57fe5b6000918252602091829020601191909102018054600180830154600384015460028086018054604080516101009783161588026000190190921693909304601f81018a90048a0282018a019093528281529698509496929560ff8316949092046001600160a01b031692600889019260048a019290918791908301828280156136155780601f106135ea57610100808354040283529160200191613615565b820191906000526020600020905b8154815290600101906020018083116135f857829003601f168201915b505060408051608081019182905294995086935060049250905082845b81548152602001906001019080831161363257505060408051608081019182905294965085935060049250905082845b8154815260200190600101908083116136625750505050509050975097509750975097509750975050919395979092949650565b61369e612227565b6136db576040805162461bcd60e51b81526020600482015260096024820152682737ba1027bbb732b960b91b604482015290519081900360640190fd5b6001600160a01b038116613724576040805162461bcd60e51b815260206004820152601860248201526000805160206150e8833981519152604482015290519081900360640190fd5b6004546040516001600160a01b038084169216907fdcfb84bc948acc41559a77bd534eb5bca79b091c1eecdf1a441cad8662d25f7890600090a3600480546001600160a01b0319166001600160a01b0392909216919091179055565b600061378c83836137dd565b612c0b57508154600180820184556000848152602080822090930180546001600160a01b0319166001600160a01b038616908117909155855490825282860190935260409020919091555b92915050565b6001600160a01b031660009081526001919091016020526040902054151590565b5490565b6001600160a01b038116600090815260018301602052604081205480156138ff578354600019808301919081019060009087908390811061383f57fe5b60009182526020909120015487546001600160a01b039091169150819088908590811061386857fe5b600091825260208083209190910180546001600160a01b0319166001600160a01b039485161790559183168152600189810190925260409020908401905586548790806138b157fe5b60008281526020808220830160001990810180546001600160a01b03191690559092019092556001600160a01b03881682526001898101909152604082209190915594506137d79350505050565b60009150506137d7565b601a548210613951576040805162461bcd60e51b815260206004820152600f60248201526e15dc9bdb99c818985b1b1bdd081251608a1b604482015290519081900360640190fd5b6000601a838154811061396057fe5b906000526020600020906011020190506000601982600101548154811061398357fe5b600091825260208220600385810154920201925060ff1660048111156139a557fe5b146139ed576040805162461bcd60e51b815260206004820152601360248201527210d85b881b9bdd081899481d995c9a599a5959606a1b604482015290519081900360640190fd5b6139f5614e2d565b6139fd614e2d565b600d84015415613a6c5760408051608081019182905290600886019060049082845b815481526020019060010190808311613a1f575050604080516080810191829052949650600489810194509250905082845b815481526020019060010190808311613a5157505050505090505b600d840154600c85015490860190811180613a875750845442105b15613a935750600c8401545b601854600185810154909160ff90911610801590613ab657506003548660100154105b15613abf575060005b600d8601545b82811015613c4c576000613ad7614e2d565b613b5389600c018481548110613ae957fe5b60009182526020822001546040805160808101918290526001600160a01b039092169260018d01916004918390855b825461010083900a900460ff16815260206001928301818104948501949093039092029101808411613b1857905050505050506001876141fb565b9150915060005b6004811015613c41576000828260048110613b7157fe5b60200201511115613bfe57818160048110613b8857fe5b6020020151888260048110613b9957fe5b602002018051909101905260016001600160a01b0384166000908152600e8c01602052604090205460ff166002811115613bcf57fe5b1415613bfe57818160048110613be157fe5b6020020151878260048110613bf257fe5b60200201805190910190525b818160048110613c0a57fe5b602090810291909101516001600160a01b0385166000908152600f8d01835260408082208583529093529190912055600101613b5a565b505050600101613ac5565b50600d8601829055613c646004808801908590614f33565b50613c7460088701856004614f33565b50600c860154600090831415611e2c576040805160808101918290526001888101805460ff168352613cbf9390916004919083906020860180841161189b5790505050505050613e67565b8654421115613d4057604080516080810191829052613d21916001890190600490826000855b825461010083900a900460ff16815260206001928301818104948501949093039092029101808411613ce5579050505050505085876001614870565b90506000816002811115613d3157fe5b1415613d3b575060025b613d9c565b604080516080810191829052613d99916001890190600490826000855b825461010083900a900460ff16815260206001928301818104948501949093039092029101808411613d5d579050505050505085876000614870565b90505b6001816002811115613daa57fe5b1415613dcd5760038701805460ff19166002179055613dc8896149a4565b611e2c565b6002816002811115613ddb57fe5b1415613e0c576003878101805460ff19169091179055428755601b54891415613dc857601b80546001019055611e2c565b6000600d880155505050505050505050565b60008080613e30620151808504614d1b565b9196909550909350915050565b60008183603c0285610e1002613e548a8a8a614db1565b6201518002010101979650505050505050565b613e6f614e2d565b60005b600481101561221257828160048110613e8757fe5b602002015160ff1615801590613eab57504260118260048110613ea657fe5b015414155b156141f3576000818152601e6020526040812054905b818110156140e45760058360048110613ed657fe5b01546000848152601e6020526040902080546001600160a01b03909216916370a08231919084908110613f0557fe5b60009182526020918290200154604080516001600160e01b031960e086901b1681526001600160a01b0390921660048301525160248083019392829003018186803b158015613f5357600080fd5b505afa158015613f67573d6000803e3d6000fd5b505050506040513d6020811015613f7d57600080fd5b5051848460048110613f8b57fe5b6020020180519091019052600060098460048110613fa557fe5b01546001600160a01b03161480159061400957506000838152601d60209081526040808320601e9092528220805491929184908110613fe057fe5b60009182526020808320909101546001600160a01b0316835282019290925260400190205460ff165b156140dc576009836004811061401b57fe5b01546000848152601e6020526040902080546001600160a01b03909216916370a0823191908490811061404a57fe5b60009182526020918290200154604080516001600160e01b031960e086901b1681526001600160a01b0390921660048301525160248083019392829003018186803b15801561409857600080fd5b505afa1580156140ac573d6000803e3d6000fd5b505050506040513d60208110156140c257600080fd5b50518484600481106140d057fe5b60200201805190910190525b600101613ec1565b506000600583600481106140f457fe5b0160009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561414157600080fd5b505afa158015614155573d6000803e3d6000fd5b505050506040513d602081101561416b57600080fd5b5051905083836004811061417b57fe5b60200201518110156141be5760405162461bcd60e51b815260040180806020018281038252602781526020018061509e6027913960400191505060405180910390fd5b8383600481106141ca57fe5b60200201518103600d84600481106141de57fe5b015542601184600481106141ee57fe5b015550505b600101613e72565b6000614205614e2d565b83156142135785915061428f565b60155460408051632b5f251f60e11b81526001600160a01b038981166004830152915191909216916356be4a3e916024808301926020929190829003018186803b15801561426057600080fd5b505afa158015614274573d6000803e3d6000fd5b505050506040513d602081101561428a57600080fd5b505191505b6001600160a01b0382166000908152601c602052604090205460ff16156142fd576040805162461bcd60e51b815260206004820152601c60248201527f57616c6c657420697320626c6f636b656420666f7220766f74696e6700000000604482015290519081900360640190fd5b60606001600160a01b038316156144295760155460408051636cbae15760e01b81526001600160a01b03868116600483015291519190921691636cbae157916024808301926000929190829003018186803b15801561435b57600080fd5b505afa15801561436f573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052602081101561439857600080fd5b8101908080516040519392919084600160201b8211156143b757600080fd5b9083019060208201858111156143cc57600080fd5b82518660208202830111600160201b821117156143e857600080fd5b82525081516020918201928201910280838360005b838110156144155781810151838201526020016143fd565b50505050905001604052505050905061443d565b506040805160008152602081019091528692505b6000805b60048110156148185787816004811061445657fe5b602002015160ff1615614810576005816004811061447057fe5b0154604080516370a0823160e01b81526001600160a01b038881166004830152915191909216916370a08231916024808301926020929190829003018186803b1580156144bc57600080fd5b505afa1580156144d0573d6000803e3d6000fd5b505050506040513d60208110156144e657600080fd5b50518482600481106144f457fe5b6020020180519091019052858015614524575060006009826004811061451657fe5b01546001600160a01b031614155b801561455257506000818152601d602090815260408083206001600160a01b038916845290915290205460ff165b156145f4576009816004811061456457fe5b0154604080516370a0823160e01b81526001600160a01b038881166004830152915191909216916370a08231916024808301926020929190829003018186803b1580156145b057600080fd5b505afa1580156145c4573d6000803e3d6000fd5b505050506040513d60208110156145da57600080fd5b50518482600481106145e857fe5b60200201805190910190525b60005b83518110156147f1576005826004811061460d57fe5b015484516001600160a01b03909116906370a082319086908490811061462f57fe5b60200260200101516040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b15801561467457600080fd5b505afa158015614688573d6000803e3d6000fd5b505050506040513d602081101561469e57600080fd5b50518583600481106146ac57fe5b60200201805190910190528680156146dc57506000600983600481106146ce57fe5b01546001600160a01b031614155b801561472c5750601d6000838152602001908152602001600020600085838151811061470457fe5b6020908102919091018101516001600160a01b031682528101919091526040016000205460ff165b156147e9576009826004811061473e57fe5b015484516001600160a01b03909116906370a082319086908490811061476057fe5b60200260200101516040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b1580156147a557600080fd5b505afa1580156147b9573d6000803e3d6000fd5b505050506040513d60208110156147cf57600080fd5b50518583600481106147dd57fe5b60200201805190910190525b6001016145f7565b50600084826004811061480057fe5b6020020151111561481057600191505b600101614441565b5085806148225750805b614865576040805162461bcd60e51b815260206004820152600f60248201526e2737903b37ba34b733903837bbb2b960891b604482015290519081900360640190fd5b505094509492505050565b60008060008060005b600481101561497a5788816004811061488e57fe5b602002015160ff161561497257600190910190600d81600481106148ae57fe5b01548882600481106148bc57fe5b602002015160020211156148d557600190930192614972565b600d81600481106148e257fe5b01548882600481106148f057fe5b602002015188836004811061490157fe5b602002015103600202111561491b57600190920191614972565b8580156149665750606489826004811061493157fe5b602002015160ff1688836004811061494557fe5b6020020151028161495257fe5b0488826004811061495f57fe5b6020020151115b15614972576001909301925b600101614879565b508083141561498c5760019350614999565b8082141561499957600293505b505050949350505050565b6002601a82815481106149b357fe5b600091825260209091206003601190920201015460ff1660048111156149d557fe5b14614a20576040805162461bcd60e51b815260206004820152601660248201527510985b1b1bdd081a5cc81b9bdd08105c1c1c9bdd995960521b604482015290519081900360640190fd5b6000601a8281548110614a2f57fe5b9060005260206000209060110201905060006019826001015481548110614a5257fe5b906000526020600020906003020190506060816002016040518082805460018160011615610100020316600290048015614ac35780601f10614aa1576101008083540402835291820191614ac3565b820191906000526020600020905b815481529060010190602001808311614aaf575b505091505060405180910390208360020160405160200180836001600160e01b031916815260040182805460018160011615610100020316600290048015614b425780601f10614b20576101008083540402835291820191614b42565b820191906000526020600020905b815481529060010190602001808311614b2e575b505060408051601f19818403018152828252600480548954633a69008960e21b86526001600160a01b0390811692860183815260248701958652845160448801528451949a509116975063e9a4022496509094508793909291606490910190602085019080838360005b83811015614bc4578181015183820152602001614bac565b50505050905090810190601f168015614bf15780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b158015614c1157600080fd5b505af1158015614c25573d6000803e3d6000fd5b50504285555050601b54841415614c4057601b805460010190555b60018301546040518591907faeb20a030565c3c07c3f8deaa39160f5ffb7a9494af3b97d916fe432c5bda26b90600090a350505050565b6001600160a01b038116614cc0576040805162461bcd60e51b815260206004820152601860248201526000805160206150e8833981519152604482015290519081900360640190fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b60008080836226496581018262023ab1600483020590506004600362023ab18302010590910390600062164b09610fa0600185010205905060046105b58202058303601f019250600061098f8460500281614d7257fe5b0590506000605061098f83020585039050600b820560301994909401606402929092018301996002600c90940290910392909201975095509350505050565b60006107b2841015614dc257600080fd5b838383600062253d8c600460036064611324600c600d19890105890101050205600c80600d19870105600c02600287030361016f0281614dfe57fe5b0560046105b5600c600d1989010589016112c0010205617d4b8603010103039050809450505050509392505050565b60405180608001604052806004906020820280368337509192915050565b60405180610140016040528060008152602001600081526020016060815260200160006004811115614e7957fe5b815260006020820152604001614e8d614e2d565b8152602001614e9a614e2d565b81526020016060815260200160008152602001600081525090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10614ef657805160ff1916838001178555614f23565b82800160010185558215614f23579182015b82811115614f23578251825591602001919060010190614f08565b50614f2f929150615050565b5090565b8260048101928215614f235791602002820182811115614f23578251825591602001919060010190614f08565b828054828255906000526020600020908101928215614fb5579160200282015b82811115614fb557825182546001600160a01b0319166001600160a01b03909116178255602090920191600190910190614f80565b50614f2f929150615065565b6001830191839082156150445791602002820160005b8382111561501557835183826101000a81548160ff021916908360ff1602179055509260200192600101602081600001049283019260010302614fd7565b80156150425782816101000a81549060ff0219169055600101602081600001049283019260010302615015565b505b50614f2f929150615084565b5b80821115614f2f5760008155600101615051565b5b80821115614f2f5780546001600160a01b0319168155600101615066565b5b80821115614f2f57805460ff1916815560010161508556fe546f74616c20537570706c79206c657373207468656e206163636f756e74732062616c616e636553686f756c64206c656674206174206c65617374206f6e652043454f2077616c6c65745a65726f2061646472657373206e6f7420616c6c6f77656400000000000000004c657373207468656e203125206f662063697263756c6174696f6e537570706c79a2646970667358221220d25f689a2636e27e53d8e674314c37765fbafb3c2ffaeb4adeaffe615ac7a41164736f6c634300060c0033
{"success": true, "error": null, "results": {"detectors": [{"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "tautology", "impact": "Medium", "confidence": "High"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "write-after-write", "impact": "Medium", "confidence": "High"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'tautology', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'write-after-write', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}]}
96
0x1ef4e71b962224bbf60e80a4c890f5567d00c5a5
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; } } 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 Seed is Ownable { using SafeMath for uint256; string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; uint256 constant UINT256_MAX = ~uint256(0); 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 = "Seed"; _symbol = "SEED"; _decimals = 18; _totalSupply = 1000000 * 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 _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 mint(address account, uint256 amount) external onlyOwner { _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } 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 _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 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; } } abstract contract ReentrancyGuard { bool private _entered; modifier noReentrancy() { require(!_entered); _entered = true; _; _entered = false; } } interface ISeedStake is IOwnershipTransferrable { event StakeIncreased(address indexed staker, uint256 amount); event StakeDecreased(address indexed staker, uint256 amount); event Rewards(address indexed staker, uint256 mintage, uint256 developerFund); event MelodyAdded(address indexed melody); event MelodyRemoved(address indexed melody); function seed() external returns (address); function totalStaked() external returns (uint256); function staked(address staker) external returns (uint256); function lastClaim(address staker) external returns (uint256); function addMelody(address melody) external; function removeMelody(address melody) external; function upgrade(address owned, address upgraded) external; } contract SeedDAO is ReentrancyGuard { using SafeMath for uint256; uint256 constant PROPOSAL_FEE = 10 * 1e18; event NewProposal(uint64 indexed proposal); event FundProposed(uint64 indexed proposal, address indexed destination, uint256 amount); event MelodyAdditionProposed(uint64 indexed proposal, address melody); event MelodyRemovalProposed(uint64 indexed proposal, address melody); event StakeUpgradeProposed(uint64 indexed proposal, address newStake); event DAOUpgradeProposed(uint64 indexed proposal, address newDAO); event ProposalVoteAdded(uint64 indexed proposal, address indexed staker); event ProposalVoteRemoved(uint64 indexed proposal, address indexed staker); event ProposalPassed(uint64 indexed proposal); event ProposalRemoved(uint64 indexed proposal); enum ProposalType { Null, Fund, MelodyAddition, MelodyRemoval, StakeUpgrade, DAOUpgrade } struct ProposalMetadata { ProposalType pType; // Allows the creator to withdraw the proposal address creator; // Used to mark proposals older than 30 days as invalid uint256 submitted; // Stakers who voted yes mapping(address => bool) stakers; // Whether or not the proposal is completed // Stops it from being acted on multiple times bool completed; } // The info string is intended for an URL to describe the proposal struct FundProposal { address destination; uint256 amount; string info; } struct MelodyAdditionProposal { address melody; string info; } struct MelodyRemovalProposal { address melody; string info; } struct StakeUpgradeProposal { address newStake; // List of addresses owned by the Stake contract address[] owned; string info; } struct DAOUpgradeProposal { address newDAO; string info; } mapping(uint64 => ProposalMetadata) public proposals; mapping(uint64 => mapping(address => bool)) public used; mapping(uint64 => FundProposal) public _fundProposals; mapping(uint64 => MelodyAdditionProposal) public _melodyAdditionProposals; mapping(uint64 => MelodyRemovalProposal) public _melodyRemovalProposals; mapping(uint64 => StakeUpgradeProposal) public _stakeUpgradeProposals; mapping(uint64 => DAOUpgradeProposal) public _daoUpgradeProposals; // Address of the DAO we upgraded to address _upgrade; // ID to use for the next proposal uint64 _nextProposalID; ISeedStake private _stake; Seed private _SEED; // Check the proposal is valid modifier pendingProposal(uint64 proposal) { require(proposals[proposal].pType != ProposalType.Null); require(!proposals[proposal].completed); // Don't allow old proposals to suddenly be claimed require(proposals[proposal].submitted + 30 days > block.timestamp); _; } // Check this contract hasn't been replaced modifier active() { require(_upgrade == address(0)); _; } constructor(address stake) { _stake = ISeedStake(stake); _SEED = Seed(_stake.seed()); } function stake() external view returns (address) { return address(_stake); } function upgraded() external view returns (bool) { return _upgrade != address(0); } function upgrade() external view returns (address) { return _upgrade; } function _createNewProposal(ProposalType pType) internal active returns (uint64) { // Make sure this isn't spam by transferring the proposal fee require(_SEED.transferFrom(msg.sender, address(this), PROPOSAL_FEE)); // Increment the next proposal ID now // Means we don't have to return a value we subtract one from later _nextProposalID += 1; emit NewProposal(_nextProposalID); // Set up the proposal's metadata ProposalMetadata storage meta = proposals[_nextProposalID]; meta.pType = pType; meta.creator = msg.sender; meta.submitted = block.timestamp; // Automatically vote for the proposal's creator meta.stakers[msg.sender] = true; emit ProposalVoteAdded(_nextProposalID, msg.sender); return _nextProposalID; } function proposeFund(address destination, uint256 amount, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.Fund); _fundProposals[proposalID] = FundProposal(destination, amount, info); emit FundProposed(proposalID, destination, amount); return proposalID; } function proposeMelodyAddition(address melody, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.MelodyAddition); _melodyAdditionProposals[proposalID] = MelodyAdditionProposal(melody, info); emit MelodyAdditionProposed(proposalID, melody); return proposalID; } function proposeMelodyRemoval(address melody, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.MelodyRemoval); _melodyRemovalProposals[proposalID] = MelodyRemovalProposal(melody, info); emit MelodyRemovalProposed(proposalID, melody); return proposalID; } function proposeStakeUpgrade(address newStake, address[] calldata owned, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.StakeUpgrade); // Ensure the SEED token was included as an owned contract for (uint i = 0; i < owned.length; i++) { if (owned[i] == address(_SEED)) { break; } require(i != owned.length - 1); } _stakeUpgradeProposals[proposalID] = StakeUpgradeProposal(newStake, owned, info); emit StakeUpgradeProposed(proposalID, newStake); return proposalID; } function proposeDAOUpgrade(address newDAO, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.DAOUpgrade); _daoUpgradeProposals[proposalID] = DAOUpgradeProposal(newDAO, info); emit DAOUpgradeProposed(proposalID, newDAO); return proposalID; } function addVote(uint64 proposalID) external active pendingProposal(proposalID) { proposals[proposalID].stakers[msg.sender] = true; emit ProposalVoteAdded(proposalID, msg.sender); } function removeVote(uint64 proposalID) external active pendingProposal(proposalID) { proposals[proposalID].stakers[msg.sender] = false; emit ProposalVoteRemoved(proposalID, msg.sender); } // Send the SEED held by this contract to what it upgraded to // Intended to enable a contract like the timelock, if transferred to this // Without this, it'd be trapped here, forever function forwardSEED() public { require(_upgrade != address(0)); require(_SEED.transfer(_upgrade, _SEED.balanceOf(address(this)))); } // Complete a proposal // Takes in a list of stakers so this contract doesn't have to track them all in an array // This would be extremely expensive as a stakers vote weight can drop to 0 // This selective process allows only counting meaningful votes function completeProposal(uint64 proposalID, address[] calldata stakers) external active pendingProposal(proposalID) noReentrancy { ProposalMetadata storage meta = proposals[proposalID]; uint256 requirement; // Only require a majority vote for a funding request/to remove a melody if ((meta.pType == ProposalType.Fund) || (meta.pType == ProposalType.MelodyRemoval)) { requirement = _stake.totalStaked().div(2).add(1); // Require >66% to add a new melody // Adding an insecure or malicious melody will cause the staking pool to be drained } else if (meta.pType == ProposalType.MelodyAddition) { requirement = _stake.totalStaked().div(3).mul(2).add(1); // Require >80% to upgrade the stake/DAO contract // Upgrading to an insecure or malicious contract risks unlimited minting } else if ((meta.pType == ProposalType.StakeUpgrade) || (meta.pType == ProposalType.DAOUpgrade)) { requirement = _stake.totalStaked().div(5).mul(4).add(1); // Panic in case the enum is expanded and not properly handled here } else { require(false); } // Make sure there's enough vote weight behind this proposal uint256 votes = 0; for (uint i = 0; i < stakers.length; i++) { // Don't allow people to vote with flash loans if (_stake.lastClaim(stakers[i]) == block.timestamp) { continue; } require(meta.stakers[stakers[i]]); require(!used[proposalID][stakers[i]]); used[proposalID][stakers[i]] = true; votes = votes.add(_stake.staked(stakers[i])); } require(votes >= requirement); meta.completed = true; emit ProposalPassed(proposalID); if (meta.pType == ProposalType.Fund) { FundProposal memory proposal = _fundProposals[proposalID]; require(_SEED.transfer(proposal.destination, proposal.amount)); } else if (meta.pType == ProposalType.MelodyAddition) { _stake.addMelody(_melodyAdditionProposals[proposalID].melody); } else if (meta.pType == ProposalType.MelodyRemoval) { _stake.removeMelody(_melodyRemovalProposals[proposalID].melody); } else if (meta.pType == ProposalType.StakeUpgrade) { StakeUpgradeProposal memory proposal = _stakeUpgradeProposals[proposalID]; for (uint i = 0; i < proposal.owned.length; i++) { _stake.upgrade(proposal.owned[i], proposal.newStake); } // Register the new staking contract as a melody so it can move the funds over _stake.addMelody(address(proposal.newStake)); _stake = ISeedStake(proposal.newStake); } else if (meta.pType == ProposalType.DAOUpgrade) { _upgrade = _daoUpgradeProposals[proposalID].newDAO; _stake.transferOwnership(_upgrade); forwardSEED(); } else { require(false); } } // Voluntarily withdraw a proposal function withdrawProposal(uint64 proposalID) external active pendingProposal(proposalID) { require(proposals[proposalID].creator == msg.sender); proposals[proposalID].completed = true; emit ProposalRemoved(proposalID); } }
0x608060405234801561001057600080fd5b506004361061012c5760003560e01c80637e8de02e116100ad578063d55ec69711610071578063d55ec697146106c2578063d979c4aa146106ca578063da6aaeab146106f0578063df7400cb14610716578063eb1ea9c6146107945761012c565b80637e8de02e146105b657806380a5bdfb146105dc578063a76cf56e14610602578063c28de2cd14610628578063d37b7fa6146106445761012c565b8063433a5a69116100f4578063433a5a69146103a25780634c01cb57146103aa5780636bda20341461045857806371fb7cf11461050d5780637586d6ce146105905761012c565b8063198743561461013157806319db3f2a146101cb5780631d6ec3561461024b57806331c5eec8146103195780633a4b66f11461037e575b600080fd5b6101af6004803603604081101561014757600080fd5b6001600160a01b038235169190810190604081016020820135600160201b81111561017157600080fd5b82018360208201111561018357600080fd5b803590602001918460018302840111600160201b831117156101a457600080fd5b5090925090506107c9565b604080516001600160401b039092168252519081900360200190f35b610249600480360360408110156101e157600080fd5b6001600160401b038235169190810190604081016020820135600160201b81111561020b57600080fd5b82018360208201111561021d57600080fd5b803590602001918460208302840111600160201b8311171561023e57600080fd5b5090925090506108ca565b005b6101af6004803603606081101561026157600080fd5b6001600160a01b038235169190810190604081016020820135600160201b81111561028b57600080fd5b82018360208201111561029d57600080fd5b803590602001918460208302840111600160201b831117156102be57600080fd5b919390929091602081019035600160201b8111156102db57600080fd5b8201836020820111156102ed57600080fd5b803590602001918460018302840111600160201b8311171561030e57600080fd5b509092509050611403565b61033f6004803603602081101561032f57600080fd5b50356001600160401b03166115bb565b6040518085600581111561034f57fe5b81526001600160a01b039094166020850152506040808401929092521515606083015251908190036080019150f35b6103866115f2565b604080516001600160a01b039092168252519081900360200190f35b610249611601565b6103d0600480360360208110156103c057600080fd5b50356001600160401b0316611720565b60405180836001600160a01b0316815260200180602001828103825283818151815260200191508051906020019080838360005b8381101561041c578181015183820152602001610404565b50505050905090810190601f1680156104495780820380516001836020036101000a031916815260200191505b50935050505060405180910390f35b61047e6004803603602081101561046e57600080fd5b50356001600160401b03166117d4565b60405180846001600160a01b0316815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b838110156104d05781810151838201526020016104b8565b50505050905090810190601f1680156104fd5780820380516001836020036101000a031916815260200191505b5094505050505060405180910390f35b6101af6004803603606081101561052357600080fd5b6001600160a01b0382351691602081013591810190606081016040820135600160201b81111561055257600080fd5b82018360208201111561056457600080fd5b803590602001918460018302840111600160201b8311171561058557600080fd5b50909250905061188a565b610249600480360360208110156105a657600080fd5b50356001600160401b03166119a1565b610249600480360360208110156105cc57600080fd5b50356001600160401b0316611ac9565b6103d0600480360360208110156105f257600080fd5b50356001600160401b0316611bc9565b6102496004803603602081101561061857600080fd5b50356001600160401b0316611c48565b610630611d4d565b604080519115158252519081900360200190f35b6101af6004803603604081101561065a57600080fd5b6001600160a01b038235169190810190604081016020820135600160201b81111561068457600080fd5b82018360208201111561069657600080fd5b803590602001918460018302840111600160201b831117156106b757600080fd5b509092509050611d5e565b610386611e5f565b6103d0600480360360208110156106e057600080fd5b50356001600160401b0316611e6e565b6103d06004803603602081101561070657600080fd5b50356001600160401b0316611ee9565b6101af6004803603604081101561072c57600080fd5b6001600160a01b038235169190810190604081016020820135600160201b81111561075657600080fd5b82018360208201111561076857600080fd5b803590602001918460018302840111600160201b8311171561078957600080fd5b509092509050611f68565b610630600480360360408110156107aa57600080fd5b5080356001600160401b031690602001356001600160a01b0316612069565b6000806107d66003612089565b90506040518060400160405280866001600160a01b0316815260200185858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250506001600160401b0384168152600560209081526040909120835181546001600160a01b0319166001600160a01b039091161781558382015180519193506108789260018501929101906122db565b5050604080516001600160a01b038816815290516001600160401b03841692507f339826f1c3d7b31c2395903a0738e18e4c9463f3d6749d47e35a9feb2344e8db9181900360200190a2949350505050565b6008546001600160a01b0316156108e057600080fd5b8260006001600160401b03821660009081526001602052604090205460ff16600581111561090a57fe5b141561091557600080fd5b6001600160401b03811660009081526001602052604090206003015460ff161561093e57600080fd5b6001600160401b038116600090815260016020819052604090912001544262278d009091011161096d57600080fd5b60005460ff161561097d57600080fd5b6000805460ff1916600190811782556001600160401b03861682526020819052604082209190825460ff1660058111156109b357fe5b14806109ce57506003825460ff1660058111156109cc57fe5b145b15610a6c57610a656001610a5f6002600960009054906101000a90046001600160a01b03166001600160a01b031663817b1cd26040518163ffffffff1660e01b8152600401602060405180830381600087803b158015610a2d57600080fd5b505af1158015610a41573d6000803e3d6000fd5b505050506040513d6020811015610a5757600080fd5b505190612277565b9061229b565b9050610b7a565b6002825460ff166005811115610a7e57fe5b1415610ae957610a656001610a5f6002610ae36003600960009054906101000a90046001600160a01b03166001600160a01b031663817b1cd26040518163ffffffff1660e01b8152600401602060405180830381600087803b158015610a2d57600080fd5b906122b4565b6004825460ff166005811115610afb57fe5b1480610b1657506005825460ff166005811115610b1457fe5b145b1561012c57610a656001610a5f6004610ae36005600960009054906101000a90046001600160a01b03166001600160a01b031663817b1cd26040518163ffffffff1660e01b8152600401602060405180830381600087803b158015610a2d57600080fd5b6000805b85811015610dc55760095442906001600160a01b0316635c16e15e898985818110610ba557fe5b905060200201356001600160a01b03166040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b158015610bf457600080fd5b505af1158015610c08573d6000803e3d6000fd5b505050506040513d6020811015610c1e57600080fd5b50511415610c2b57610dbd565b836002016000888884818110610c3d57fe5b602090810292909201356001600160a01b03168352508101919091526040016000205460ff16610c6c57600080fd5b6001600160401b038816600090815260026020526040812090888884818110610c9157fe5b602090810292909201356001600160a01b03168352508101919091526040016000205460ff1615610cc157600080fd5b6001600160401b0388166000908152600260205260408120600191898985818110610ce857fe5b6001600160a01b0360209182029390930135831684528301939093526040909101600020805493151560ff199094169390931790925550600954610dba91166398807d84898985818110610d3857fe5b905060200201356001600160a01b03166040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b158015610d8757600080fd5b505af1158015610d9b573d6000803e3d6000fd5b505050506040513d6020811015610db157600080fd5b5051839061229b565b91505b600101610b7e565b5081811015610dd357600080fd5b60038301805460ff191660011790556040516001600160401b038816907f6085cc60943f0b976690a6f940d11a998d1a616c9469dc9196e763e342ca583f90600090a26001835460ff166005811115610e2857fe5b1415610f9f57610e36612359565b6001600160401b038816600090815260036020908152604091829020825160608101845281546001600160a01b03168152600180830154828501526002808401805487516101009482161594909402600019011691909104601f81018690048602830186018752808352929593949386019391929091830182828015610efd5780601f10610ed257610100808354040283529160200191610efd565b820191906000526020600020905b815481529060010190602001808311610ee057829003601f168201915b505050919092525050600a5482516020808501516040805163a9059cbb60e01b81526001600160a01b039485166004820152602481019290925251959650919092169363a9059cbb9350604480830193928290030181600087803b158015610f6457600080fd5b505af1158015610f78573d6000803e3d6000fd5b505050506040513d6020811015610f8e57600080fd5b5051610f9957600080fd5b506113f0565b6002835460ff166005811115610fb157fe5b141561103a576009546001600160401b038816600090815260046020819052604080832054815163791cbf9f60e11b81526001600160a01b0391821693810193909352905193169263f2397f3e9260248084019391929182900301818387803b15801561101d57600080fd5b505af1158015611031573d6000803e3d6000fd5b505050506113f0565b6003835460ff16600581111561104c57fe5b14156110b4576009546001600160401b0388166000908152600560205260408082205481516316d4489b60e11b81526001600160a01b0391821660048201529151931692632da891369260248084019391929182900301818387803b15801561101d57600080fd5b6004835460ff1660058111156110c657fe5b1415611341576110d4612383565b6001600160401b038816600090815260066020908152604091829020825160608101845281546001600160a01b031681526001820180548551818602810186019096528086529194929385810193929083018282801561115d57602002820191906000526020600020905b81546001600160a01b0316815260019091019060200180831161113f575b5050509183525050600282810180546040805160206001841615610100026000190190931694909404601f810183900483028501830190915280845293810193908301828280156111ef5780601f106111c4576101008083540402835291602001916111ef565b820191906000526020600020905b8154815290600101906020018083116111d257829003601f168201915b505050505081525050905060005b8160200151518110156112b157600954602083015180516001600160a01b03909216916399a88ec491908490811061123157fe5b602002602001015184600001516040518363ffffffff1660e01b815260040180836001600160a01b03168152602001826001600160a01b0316815260200192505050600060405180830381600087803b15801561128d57600080fd5b505af11580156112a1573d6000803e3d6000fd5b5050600190920191506111fd9050565b5060095481516040805163791cbf9f60e11b81526001600160a01b0392831660048201529051919092169163f2397f3e91602480830192600092919082900301818387803b15801561130257600080fd5b505af1158015611316573d6000803e3d6000fd5b50509151600980546001600160a01b0319166001600160a01b03909216919091179055506113f09050565b6005835460ff16600581111561135357fe5b141561012c576001600160401b03871660009081526007602052604080822054600880546001600160a01b0319166001600160a01b039283161790819055600954835163f2fde38b60e01b815291831660048301529251929091169263f2fde38b9260248084019382900301818387803b1580156113d057600080fd5b505af11580156113e4573d6000803e3d6000fd5b505050506113f0611601565b50506000805460ff191690555050505050565b6000806114106004612089565b905060005b8581101561147257600a546001600160a01b031687878381811061143557fe5b905060200201356001600160a01b03166001600160a01b0316141561145957611472565b600019860181141561146a57600080fd5b600101611415565b506040518060600160405280886001600160a01b03168152602001878780806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250505090825250604080516020601f88018190048102820181019092528681529181019190879087908190840183828082843760009201829052509390945250506001600160401b0384168152600660209081526040909120835181546001600160a01b0319166001600160a01b0390911617815583820151805191935061154b9260018501929101906123ad565b50604082015180516115679160028401916020909101906122db565b5050604080516001600160a01b038a16815290516001600160401b03841692507ffd08ecdf1b11b329fffd11e68af1d1f874ca2e56aa45a1e13065e6cc26373b2c9181900360200190a29695505050505050565b600160208190526000918252604090912080549181015460039091015460ff8084169361010090046001600160a01b031692911684565b6009546001600160a01b031690565b6008546001600160a01b031661161657600080fd5b600a54600854604080516370a0823160e01b815230600482015290516001600160a01b039384169363a9059cbb93169184916370a0823191602480820192602092909190829003018186803b15801561166e57600080fd5b505afa158015611682573d6000803e3d6000fd5b505050506040513d602081101561169857600080fd5b5051604080516001600160e01b031960e086901b1681526001600160a01b03909316600484015260248301919091525160448083019260209291908290030181600087803b1580156116e957600080fd5b505af11580156116fd573d6000803e3d6000fd5b505050506040513d602081101561171357600080fd5b505161171e57600080fd5b565b6004602090815260009182526040918290208054600180830180548651600261010094831615949094026000190190911692909204601f81018690048602830186019096528582526001600160a01b039092169492939092908301828280156117ca5780601f1061179f576101008083540402835291602001916117ca565b820191906000526020600020905b8154815290600101906020018083116117ad57829003601f168201915b5050505050905082565b60036020908152600091825260409182902080546001808301546002808501805488516101009582161595909502600019011691909104601f81018790048702840187019097528683526001600160a01b039093169590949192918301828280156118805780601f1061185557610100808354040283529160200191611880565b820191906000526020600020905b81548152906001019060200180831161186357829003601f168201915b5050505050905083565b6000806118976001612089565b90506040518060600160405280876001600160a01b0316815260200186815260200185858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250506001600160401b038416815260036020908152604091829020845181546001600160a01b0319166001600160a01b0390911617815584820151600182015591840151805192935061194b92600285019291909101906122db565b50506040805187815290516001600160a01b03891692506001600160401b038416917fc6befa0284988cf06a62f33e703b26fa8fe104aff100ff179eb9b02174018530919081900360200190a395945050505050565b6008546001600160a01b0316156119b757600080fd5b8060006001600160401b03821660009081526001602052604090205460ff1660058111156119e157fe5b14156119ec57600080fd5b6001600160401b03811660009081526001602052604090206003015460ff1615611a1557600080fd5b6001600160401b038116600090815260016020819052604090912001544262278d0090910111611a4457600080fd5b6001600160401b03821660009081526001602052604090205461010090046001600160a01b03163314611a7657600080fd5b6001600160401b0382166000818152600160208190526040808320600301805460ff1916909217909155517f9253f303ac7bc301d8f26a3c594cf868be86bee4afd53c746f29cc0103a4274f9190a25050565b6008546001600160a01b031615611adf57600080fd5b8060006001600160401b03821660009081526001602052604090205460ff166005811115611b0957fe5b1415611b1457600080fd5b6001600160401b03811660009081526001602052604090206003015460ff1615611b3d57600080fd5b6001600160401b038116600090815260016020819052604090912001544262278d0090910111611b6c57600080fd5b6001600160401b0382166000818152600160209081526040808320338085526002909101909252808320805460ff19169055519092917f55b02b9855e513ee8f9281215332c8cf0f8304cadcdca4e1b3910609797103e691a35050565b6005602090815260009182526040918290208054600180830180548651600261010094831615949094026000190190911692909204601f81018690048602830186019096528582526001600160a01b039092169492939092908301828280156117ca5780601f1061179f576101008083540402835291602001916117ca565b6008546001600160a01b031615611c5e57600080fd5b8060006001600160401b03821660009081526001602052604090205460ff166005811115611c8857fe5b1415611c9357600080fd5b6001600160401b03811660009081526001602052604090206003015460ff1615611cbc57600080fd5b6001600160401b038116600090815260016020819052604090912001544262278d0090910111611ceb57600080fd5b6001600160401b0382166000818152600160208181526040808420338086526002909101909252808420805460ff191690931790925590519092917fc7442600edbdac0b51781946ea453c6ec64fba32dc76e7e711cbe79a15ec5fec91a35050565b6008546001600160a01b0316151590565b600080611d6b6002612089565b90506040518060400160405280866001600160a01b0316815260200185858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250506001600160401b0384168152600460209081526040909120835181546001600160a01b0319166001600160a01b03909116178155838201518051919350611e0d9260018501929101906122db565b5050604080516001600160a01b038816815290516001600160401b03841692507f29cd6c86b51064508c60d447e776b80d8c6f25603856be845b6a2abe192a00779181900360200190a2949350505050565b6008546001600160a01b031690565b60066020908152600091825260409182902080546002808301805486516101006001831615026000190190911692909204601f81018690048602830186019096528582526001600160a01b039092169492939092908301828280156117ca5780601f1061179f576101008083540402835291602001916117ca565b6007602090815260009182526040918290208054600180830180548651600261010094831615949094026000190190911692909204601f81018690048602830186019096528582526001600160a01b039092169492939092908301828280156117ca5780601f1061179f576101008083540402835291602001916117ca565b600080611f756005612089565b90506040518060400160405280866001600160a01b0316815260200185858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250506001600160401b0384168152600760209081526040909120835181546001600160a01b0319166001600160a01b039091161781558382015180519193506120179260018501929101906122db565b5050604080516001600160a01b038816815290516001600160401b03841692507f29ff7ec46662ba30200783e0d6cbe17047c2ab7058785f9d441e8b21a88e25749181900360200190a2949350505050565b600260209081526000928352604080842090915290825290205460ff1681565b6008546000906001600160a01b0316156120a257600080fd5b600a54604080516323b872dd60e01b8152336004820152306024820152678ac7230489e80000604482015290516001600160a01b03909216916323b872dd916064808201926020929091908290030181600087803b15801561210357600080fd5b505af1158015612117573d6000803e3d6000fd5b505050506040513d602081101561212d57600080fd5b505161213857600080fd5b600880546001600160401b03600160a01b80830482166001018216810267ffffffffffffffff60a01b19909316929092179283905560405191909204909116907fe1c41d4ba86fb17ee8e9f88a333876ca22e0d2940c46a544405bb18a6b932a5c90600090a2600854600160a01b90046001600160401b03166000908152600160208190526040909120805490918491839160ff19909116908360058111156121dd57fe5b02179055508054610100600160a81b031916336101008102919091178255426001808401919091556000828152600284016020526040808220805460ff19169093179092556008549151600160a01b9092046001600160401b0316917fc7442600edbdac0b51781946ea453c6ec64fba32dc76e7e711cbe79a15ec5fec9190a35050600854600160a01b90046001600160401b0316919050565b600080821161228557600080fd5b600082848161229057fe5b049150505b92915050565b6000828201838110156122ad57600080fd5b9392505050565b6000826122c357506000612295565b828202828482816122d057fe5b04146122ad57600080fd5b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061231c57805160ff1916838001178555612349565b82800160010185558215612349579182015b8281111561234957825182559160200191906001019061232e565b5061235592915061240e565b5090565b604051806060016040528060006001600160a01b0316815260200160008152602001606081525090565b604051806060016040528060006001600160a01b0316815260200160608152602001606081525090565b828054828255906000526020600020908101928215612402579160200282015b8281111561240257825182546001600160a01b0319166001600160a01b039091161782556020909201916001909101906123cd565b50612355929150612423565b5b80821115612355576000815560010161240f565b5b808211156123555780546001600160a01b031916815560010161242456fea264697066735822122080803a5515c04a1c7376c40091ec3e34d629fe21f1c7523075a5dcc7c05ffedc64736f6c63430007000033
{"success": true, "error": null, "results": {"detectors": [{"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}]}
97
0x1f2e6c889c2121c4e4f317ab85b089080f87be1a
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 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 override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This 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 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 length) public view returns (uint256) { if (securityLevel == 0) { return 2; // for testing } if (length == Timelock.Short) { if (securityLevel == 1) { return timeInDays(1); } else if (securityLevel == 2) { return timeInDays(2); } else { return timeInDays(3); } } else if (length == 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 length); event UnlockInitiated(Timelock length, uint256 whenUnlocked); function getReleaseTime(Timelock length) public view returns (uint256) { return releaseTimes[length]; } function initiateUnlock(Timelock length) public onlyOwner { uint256 newReleaseTime = now.add(getDelay(length)); releaseTimes[length] = newReleaseTime; emit UnlockInitiated(length, newReleaseTime); } function lock(Timelock length) public onlyOwner { releaseTimes[length] = 0; emit Locked(length); } 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 mintFees = [0, 0, 0]; uint256[] private burnFees = [0, 0, 0]; 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() 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 { mintFees = newMintFees; emit MintFeesSet(newMintFees); } function setBurnFees(uint256[] memory newBurnFees) public onlyOwner whenNotLockedL { burnFees = newBurnFees; emit BurnFeesSet(newBurnFees); } function setDualFees(uint256[] memory newDualFees) public onlyOwner whenNotLockedM { dualFees = newDualFees; emit DualFeesSet(newDualFees); } function setIntegrator(address account, bool isVerified) public onlyOwner whenNotLockedM { verifiedIntegrators[account] = isVerified; emit IntegratorSet(account, isVerified); } function getFee( address account, uint256 numTokens, uint256[] storage fees ) internal view returns (uint256) { if (verifiedIntegrators[account]) { return 0; } if (numTokens == 1) { return fees[0]; } return fees[1] + numTokens * fees[2]; } 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; event ControllerSet(address account, bool isVerified); event DirectRedemption(uint256 punkId, address by, address indexed to); function isController(address account) internal view returns (bool) { return verifiedControllers[account]; } function setController(address account, bool isVerified) public onlyOwner whenNotLockedM { 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()); } }
0x608060405234801561001057600080fd5b50600436106101375760003560e01c806370a08231116100b857806395d89b411161007c57806395d89b4114610430578063a3895fff14610438578063a457c2d7146104de578063a9059cbb1461050a578063dd62ed3e14610536578063f2fde38b1461056457610137565b806370a08231146103a8578063715018a6146103ce57806379cc6790146103d657806385535cc5146104025780638da5cb5b1461042857610137565b806339509351116100ff578063395093511461026757806340c10f191461029357806342966c68146102c15780635353a2d8146102de57806365cacaa41461038457610137565b806306fdde031461013c578063095ea7b3146101b957806318160ddd146101f957806323b872dd14610213578063313ce56714610249575b600080fd5b61014461058a565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561017e578181015183820152602001610166565b50505050905090810190601f1680156101ab5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101e5600480360360408110156101cf57600080fd5b506001600160a01b038135169060200135610621565b604080519115158252519081900360200190f35b61020161063e565b60408051918252519081900360200190f35b6101e56004803603606081101561022957600080fd5b506001600160a01b03813581169160208101359091169060400135610644565b6102516106d1565b6040805160ff9092168252519081900360200190f35b6101e56004803603604081101561027d57600080fd5b506001600160a01b0381351690602001356106da565b6102bf600480360360408110156102a957600080fd5b506001600160a01b03813516906020013561072e565b005b6102bf600480360360208110156102d757600080fd5b5035610794565b6102bf600480360360208110156102f457600080fd5b81019060208101813564010000000081111561030f57600080fd5b82018360208201111561032157600080fd5b8035906020019184600183028401116401000000008311171561034357600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295506107a8945050505050565b61038c610809565b604080516001600160a01b039092168252519081900360200190f35b610201600480360360208110156103be57600080fd5b50356001600160a01b031661081d565b6102bf610838565b6102bf600480360360408110156103ec57600080fd5b506001600160a01b0381351690602001356108da565b6102bf6004803603602081101561041857600080fd5b50356001600160a01b031661093a565b61038c6109ba565b6101446109c9565b6102bf6004803603602081101561044e57600080fd5b81019060208101813564010000000081111561046957600080fd5b82018360208201111561047b57600080fd5b8035906020019184600183028401116401000000008311171561049d57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550610a2a945050505050565b6101e5600480360360408110156104f457600080fd5b506001600160a01b038135169060200135610a8b565b6101e56004803603604081101561052057600080fd5b506001600160a01b038135169060200135610af9565b6102016004803603604081101561054c57600080fd5b506001600160a01b0381358116916020013516610b0d565b6102bf6004803603602081101561057a57600080fd5b50356001600160a01b0316610b38565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156106165780601f106105eb57610100808354040283529160200191610616565b820191906000526020600020905b8154815290600101906020018083116105f957829003601f168201915b505050505090505b90565b600061063561062e610c91565b8484610c95565b50600192915050565b60035490565b6000610651848484610d81565b6106c78461065d610c91565b6106c28560405180606001604052806028815260200161133b602891396001600160a01b038a1660009081526002602052604081209061069b610c91565b6001600160a01b03168152602081019190915260400160002054919063ffffffff610eea16565b610c95565b5060019392505050565b60065460ff1690565b60006106356106e7610c91565b846106c285600260006106f8610c91565b6001600160a01b03908116825260208083019390935260409182016000908120918c16815292529020549063ffffffff610c3016565b610736610c91565b6000546001600160a01b03908116911614610786576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b6107908282610f81565b5050565b6107a561079f610c91565b8261107f565b50565b6107b0610c91565b6000546001600160a01b03908116911614610800576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b6107a581611187565b60065461010090046001600160a01b031690565b6001600160a01b031660009081526001602052604090205490565b610840610c91565b6000546001600160a01b03908116911614610890576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6000610917826040518060600160405280602481526020016113836024913961090a86610905610c91565b610b0d565b919063ffffffff610eea16565b905061092b83610925610c91565b83610c95565b610935838361107f565b505050565b610942610c91565b6000546001600160a01b03908116911614610992576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b600680546001600160a01b0390921661010002610100600160a81b0319909216919091179055565b6000546001600160a01b031690565b60058054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156106165780601f106105eb57610100808354040283529160200191610616565b610a32610c91565b6000546001600160a01b03908116911614610a82576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b6107a58161119a565b6000610635610a98610c91565b846106c2856040518060600160405280602581526020016114116025913960026000610ac2610c91565b6001600160a01b03908116825260208083019390935260409182016000908120918d1681529252902054919063ffffffff610eea16565b6000610635610b06610c91565b8484610d81565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b610b40610c91565b6000546001600160a01b03908116911614610b90576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b6001600160a01b038116610bd55760405162461bcd60e51b81526004018080602001828103825260268152602001806112cd6026913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b600082820183811015610c8a576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b3390565b6001600160a01b038316610cda5760405162461bcd60e51b81526004018080602001828103825260248152602001806113ed6024913960400191505060405180910390fd5b6001600160a01b038216610d1f5760405162461bcd60e51b81526004018080602001828103825260228152602001806112f36022913960400191505060405180910390fd5b6001600160a01b03808416600081815260026020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b038316610dc65760405162461bcd60e51b81526004018080602001828103825260258152602001806113c86025913960400191505060405180910390fd5b6001600160a01b038216610e0b5760405162461bcd60e51b81526004018080602001828103825260238152602001806112886023913960400191505060405180910390fd5b610e16838383610935565b610e5981604051806060016040528060268152602001611315602691396001600160a01b038616600090815260016020526040902054919063ffffffff610eea16565b6001600160a01b038085166000908152600160205260408082209390935590841681522054610e8e908263ffffffff610c3016565b6001600160a01b0380841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b60008184841115610f795760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610f3e578181015183820152602001610f26565b50505050905090810190601f168015610f6b5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b6001600160a01b038216610fdc576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015290519081900360640190fd5b610fe860008383610935565b600354610ffb908263ffffffff610c3016565b6003556001600160a01b038216600090815260016020526040902054611027908263ffffffff610c3016565b6001600160a01b03831660008181526001602090815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b6001600160a01b0382166110c45760405162461bcd60e51b81526004018080602001828103825260218152602001806113a76021913960400191505060405180910390fd5b6110d082600083610935565b611113816040518060600160405280602281526020016112ab602291396001600160a01b038516600090815260016020526040902054919063ffffffff610eea16565b6001600160a01b03831660009081526001602052604090205560035461113f908263ffffffff6111ad16565b6003556040805182815290516000916001600160a01b038516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050565b80516107909060049060208401906111ef565b80516107909060059060208401906111ef565b6000610c8a83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610eea565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061123057805160ff191683800117855561125d565b8280016001018555821561125d579182015b8281111561125d578251825591602001919060010190611242565b5061126992915061126d565b5090565b61061e91905b80821115611269576000815560010161127356fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a206275726e20616d6f756e7420657863656564732062616c616e63654f776e61626c653a206e6577206f776e657220697320746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e63654f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657245524332303a206275726e20616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa26469706673582212206d395fa55e2ae2c2a151a4acf52f39b59ceb44e59f7c5aadc9c3e7ebac982e9764736f6c63430006080033
{"success": true, "error": null, "results": {"detectors": [{"check": "weak-prng", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'weak-prng', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}]}
98
0x1f5b389e9a505aa1465507c40e1cff67f536ec9d
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; } }
0x608060405234801561001057600080fd5b50600436106102115760003560e01c806356574b8c11610125578063b39e12cf116100ad578063ca15c8731161007c578063ca15c8731461049a578063d547741f146104ad578063dda641ae146104c0578063fa8dacba14610216578063ff1f7799146104d357610211565b8063b39e12cf14610445578063b86315851461044d578063c4336c1c14610460578063c4d66de81461048757610211565b806391d14854116100f457806391d14854146103f15780639654ff16146104045780639ac1c4ad146104175780639c3e452f1461042a578063a217fddf1461043d57610211565b806356574b8c146103985780635fd55293146103ab5780637ce845d0146103be5780639010d07c146103d157610211565b8063248a9ca3116101a85780632f7263cd116101775780632f7263cd1461031f57806336568abe1461033f5780633d42b1ce14610352578063416880b01461036557806344c9af281461037857610211565b8063248a9ca3146102d357806327040f68146102e657806327e5455a146102f95780632f2ff15d1461030c57610211565b80631d703812116101e45780631d703812146102875780631d9c7f0a1461029a5780631da42e5e146102ad57806321eb5859146102c057610211565b80630b975991146102165780630dd357011461023f5780630e01bff81461025f5780631c8a253e14610272575b600080fd5b610229610224366004615046565b6104e6565b6040516102369190615324565b60405180910390f35b61025261024d3660046150fd565b6104f9565b6040516102369190615e27565b61022961026d3660046150a9565b61063c565b61028561028036600461507e565b610794565b005b6102296102953660046150fd565b6107aa565b6102296102a8366004615144565b6107b8565b6102856102bb366004615144565b6107e6565b6102856102ce36600461517d565b610a25565b6102296102e13660046150fd565b611065565b6102296102f4366004615046565b61107a565b6102856103073660046150fd565b611085565b61028561031a366004615115565b6117d2565b61033261032d366004615046565b611816565b6040516102369190615319565b61028561034d366004615115565b61184b565b6102296103603660046150fd565b61188d565b610229610373366004615144565b61189f565b61038b6103863660046150fd565b6119ca565b604051610236919061532d565b6102296103a636600461507e565b611c29565b6102856103b9366004615046565b611c42565b6102296103cc366004615046565b611c50565b6103e46103df366004615144565b611cab565b6040516102369190615250565b6103326103ff366004615115565b611cd2565b61022961041236600461507e565b611cf0565b6102856104253660046150fd565b611d1c565b610229610438366004615144565b611e6f565b610229611f8a565b6103e4611f8f565b61028561045b3660046150fd565b611f9e565b61047361046e3660046150fd565b612434565b6040516102369897969594939291906152c4565b610285610495366004615046565b61251d565b6102296104a83660046150fd565b6125a9565b6102856104bb366004615115565b6125c0565b6102296104ce366004615046565b6125fa565b6102296104e136600461507e565b612615565b60006104f182612629565b90505b919050565b610501614f2f565b6098548290811061052d5760405162461bcd60e51b815260040161052490615cc0565b60405180910390fd5b6098838154811061053a57fe5b600091825260209182902060408051610100808201835260089490940290920180546001600160a01b0316835260018082015484870152600280830154858501526003830154606086015260048301546080860152600583015460a0860152600683015460c08601526007830180548551938116159097026000190190961604601f81018790048702820187019093528281529294909360e086019392909183018282801561062a5780601f106105ff5761010080835404028352916020019161062a565b820191906000526020600020905b81548152906001019060200180831161060d57829003601f168201915b50505050508152505091505b50919050565b604080518082018252600b81526a2234b9ba3934b13aba37b960a91b602080830191909152609754925160009333926001600160a01b039091169163ec56a3739161068991869101615234565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016106bb9190615324565b60206040518083038186803b1580156106d357600080fd5b505afa1580156106e7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061070b9190615062565b6001600160a01b03161480610723575061072361264c565b61073f5760405162461bcd60e51b815260040161052490615d40565b606061074a8661265e565b6001600160a01b038716600090815260a1602090815260408083208984529091529020909150610780908563ffffffff61266b16565b925061078b816127b2565b50509392505050565b6107a66107a183836129b4565b6127b2565b5050565b60006104f182610438612c74565b609960205281600052604060002081815481106107d157fe5b90600052602060002001600091509150505481565b6040805180820182526008815267283ab734b9b432b960c11b6020808301919091526097549251919233926001600160a01b039091169163ec56a3739161082f91869101615234565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016108619190615324565b60206040518083038186803b15801561087957600080fd5b505afa15801561088d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108b19190615062565b6001600160a01b031614806108c957506108c961264c565b6108e55760405162461bcd60e51b815260040161052490615d40565b60006108ef612c74565b90506108f9614f7d565b6000858152609c6020526040902061091890858463ffffffff612d7016565b6000868152609d6020526040902090915061093a90828463ffffffff612e4216565b6000858152609e60205260409020610953908284612f92565b60408051606081018252918252602080830196875290820192835260a28054600181018255600091909152915180517faaf4f58de99300cfadc4585755f376d5fa747d5bc561d5bd9d710de1f91bf42d60049094029384015501517faaf4f58de99300cfadc4585755f376d5fa747d5bc561d5bd9d710de1f91bf42e82015593517faaf4f58de99300cfadc4585755f376d5fa747d5bc561d5bd9d710de1f91bf42f850155517faaf4f58de99300cfadc4585755f376d5fa747d5bc561d5bd9d710de1f91bf430909301929092555050565b609754604051633581777360e01b81526000916001600160a01b031690633581777390610a5490600401615dae565b60206040518083038186803b158015610a6c57600080fd5b505afa158015610a80573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610aa49190615062565b609754604051633581777360e01b81529192506000916001600160a01b0390911690633581777390610ad8906004016159f9565b60206040518083038186803b158015610af057600080fd5b505afa158015610b04573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b289190615062565b609754604051633581777360e01b81529192506000916001600160a01b0390911690633581777390610b5c90600401615871565b60206040518083038186803b158015610b7457600080fd5b505afa158015610b88573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bac9190615062565b609754604051633581777360e01b81529192506000916001600160a01b0390911690633581777390610be090600401615ac3565b60206040518083038186803b158015610bf857600080fd5b505afa158015610c0c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c309190615062565b6040516370cb318960e01b81529091506001600160a01b038516906370cb318990610c61908c908c90600401615e94565b60206040518083038186803b158015610c7957600080fd5b505afa158015610c8d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cb191906150dd565b610ccd5760405162461bcd60e51b815260040161052490615c12565b60405163f93c86f160e01b81526001600160a01b0385169063f93c86f190610cf9908c90600401615324565b60206040518083038186803b158015610d1157600080fd5b505afa158015610d25573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d4991906150dd565b610d655760405162461bcd60e51b81526004016105249061551d565b60405163a795d29360e01b81526001600160a01b0384169063a795d29390610d91908a90600401615324565b60206040518083038186803b158015610da957600080fd5b505afa158015610dbd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610de191906150dd565b610dfd5760405162461bcd60e51b815260040161052490615bcd565b60405163461a6f3f60e11b81526001600160a01b03851690638c34de7e90610e29908c90600401615324565b60206040518083038186803b158015610e4157600080fd5b505afa158015610e55573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e7991906150dd565b610e955760405162461bcd60e51b8152600401610524906155a3565b610e9f338a61308e565b506060610eab3361265e565b90506000610ef2338c8c8c8c8c8080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061321a92505050565b90506000846001600160a01b03166370a08231336040518263ffffffff1660e01b8152600401610f229190615250565b60206040518083038186803b158015610f3a57600080fd5b505afa158015610f4e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f729190615165565b90506000846001600160a01b0316630b975991336040518263ffffffff1660e01b8152600401610fa29190615250565b602060405180830381600087803b158015610fbc57600080fd5b505af1158015610fd0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ff49190615165565b9050808210156110165760405162461bcd60e51b8152600401610524906158cc565b7f839237f8da6208af7e49773f22501b3082aaae94d5b6ce8ee96f117835fe2f67836040516110459190615324565b60405180910390a1611056846127b2565b50505050505050505050505050565b60009081526065602052604090206002015490565b60006104f182613479565b609854819081106110a85760405162461bcd60e51b815260040161052490615cc0565b60046110b3836119ca565b60068111156110be57fe5b146110db5760405162461bcd60e51b8152600401610524906157ba565b609754604051633581777360e01b81526000916001600160a01b03169063358177739061110a90600401615dae565b60206040518083038186803b15801561112257600080fd5b505afa158015611136573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061115a9190615062565b9050336001600160a01b03166098848154811061117357fe5b60009182526020909120600890910201546001600160a01b031614806112b357506040516224441f60e71b81526001600160a01b038216906312220f80906111bf903390600401615250565b60206040518083038186803b1580156111d757600080fd5b505afa1580156111eb573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061120f91906150dd565b80156112b35750604051630ba7341960e11b81526001600160a01b0382169063174e683290611242903390600401615250565b60206040518083038186803b15801561125a57600080fd5b505afa15801561126e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112929190615165565b6098848154811061129f57fe5b906000526020600020906008020160010154145b6112cf5760405162461bcd60e51b815260040161052490615cf7565b609754604051633581777360e01b81526000916001600160a01b0316906335817773906112fe90600401615684565b60206040518083038186803b15801561131657600080fd5b505afa15801561132a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061134e9190615062565b609754604051633581777360e01b81529192506000916001600160a01b0390911690633581777390611382906004016159f9565b60206040518083038186803b15801561139a57600080fd5b505afa1580156113ae573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113d29190615062565b9050611426609886815481106113e457fe5b6000918252602090912060089091020154609880546001600160a01b03909216918890811061140f57fe5b9060005260206000209060080201600101546134b7565b61142f33611c42565b6114388561358e565b6098868154811061144557fe5b906000526020600020906008020160060181905550600061146586613695565b90506114ae6098878154811061147757fe5b906000526020600020906008020160010154826098898154811061149757fe5b9060005260206000209060080201600601546137ce565b611508609887815481106114be57fe5b906000526020600020906008020160000160009054906101000a90046001600160a01b031682609889815481106114f157fe5b9060005260206000209060080201600601546137ed565b61157a6098878154811061151857fe5b6000918252602090912060089091020154609880546001600160a01b03909216918990811061154357fe5b9060005260206000209060080201600101548360988a8154811061156357fe5b906000526020600020906008020160060154613816565b6000611626836001600160a01b031663f5b98f4160988a8154811061159b57fe5b9060005260206000209060080201600301546040518263ffffffff1660e01b81526004016115c99190615324565b60206040518083038186803b1580156115e157600080fd5b505afa1580156115f5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116199190615165565b839063ffffffff61384a16565b905061166f6098888154811061163857fe5b9060005260206000209060080201600101548260988a8154811061165857fe5b906000526020600020906008020160060154613884565b6116e16098888154811061167f57fe5b6000918252602090912060089091020154609880546001600160a01b03909216918a9081106116aa57fe5b9060005260206000209060080201600101548360988b815481106116ca57fe5b9060005260206000209060080201600601546138a3565b836001600160a01b0316630d4e8fd1609889815481106116fd57fe5b906000526020600020906008020160000160009054906101000a90046001600160a01b03168960988b8154811061173057fe5b9060005260206000209060080201600601546040518463ffffffff1660e01b81526004016117609392919061527d565b600060405180830381600087803b15801561177a57600080fd5b505af115801561178e573d6000803e3d6000fd5b505050507fb0142de902382ce87e0ae1e5ec0699b26d25bec2eeb06bca82e1253099b3119c876040516117c19190615324565b60405180910390a150505050505050565b6000828152606560205260409020600201546117f0906103ff6138d7565b61180c5760405162461bcd60e51b8152600401610524906153e6565b6107a682826138db565b60006118218261394a565b80156104f157505060a2546001600160a01b0391909116600090815260a360205260409020541090565b6118536138d7565b6001600160a01b0316816001600160a01b0316146118835760405162461bcd60e51b815260040161052490615dd8565b6107a68282613967565b60009081526099602052604090205490565b604080518082018252600b81526a2234b9ba3934b13aba37b960a91b602080830191909152609754925160009333926001600160a01b039091169163ec56a373916118ec91869101615234565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b815260040161191e9190615324565b60206040518083038186803b15801561193657600080fd5b505afa15801561194a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061196e9190615062565b6001600160a01b03161480611986575061198661264c565b6119a25760405162461bcd60e51b815260040161052490615d40565b6000848152609d602052604090206119c0908463ffffffff61266b16565b91505b5092915050565b609854600090829081106119f05760405162461bcd60e51b815260040161052490615cc0565b609883815481106119fd57fe5b90600052602060002090600802016005015460001415611b845760988381548110611a2457fe5b90600052602060002090600802016006015460001415611b7b57609754604051633581777360e01b81526000916001600160a01b031690633581777390611a6d9060040161565f565b60206040518083038186803b158015611a8557600080fd5b505afa158015611a99573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611abd9190615062565b9050806001600160a01b031663bf64d84960988681548110611adb57fe5b9060005260206000209060080201600401546040518263ffffffff1660e01b8152600401611b099190615324565b60206040518083038186803b158015611b2157600080fd5b505afa158015611b35573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b599190615165565b611b61612c74565b1415611b71576000925050610636565b6003925050610636565b60029150610636565b60988381548110611b9157fe5b906000526020600020906008020160050154611bab612c74565b1015611bba5760019150610636565b60988381548110611bc757fe5b90600052602060002090600802016006015460001415611bea5760049150610636565b60988381548110611bf757fe5b906000526020600020906008020160060154611c11612c74565b1015611c205760059150610636565b60069150610636565b609a60205281600052604060002081815481106107d157fe5b611c4d816000610794565b50565b600080611c5b612c74565b6001600160a01b038416600090815260a56020526040902060010154909150811115611c8b5760009150506104f4565b50506001600160a01b038116600090815260a560205260409020546104f4565b6000828152606560205260408120611cc9908363ffffffff6139d616565b90505b92915050565b6000828152606560205260408120611cc9908363ffffffff6139e216565b6001600160a01b0391909116600090815260a46020908152604080832093835260019093019052205490565b60985481908110611d3f5760405162461bcd60e51b815260040161052490615cc0565b60988281548110611d4c57fe5b60009182526020909120600890910201546001600160a01b03163314611d845760405162461bcd60e51b815260040161052490615354565b6000611d8f836119ca565b6006811115611d9a57fe5b14611db75760405162461bcd60e51b815260040161052490615b29565b611dbf612c74565b60988381548110611dcc57fe5b906000526020600020906008020160060181905550611e3360988381548110611df157fe5b6000918252602090912060089091020154609880546001600160a01b039092169185908110611e1c57fe5b9060005260206000209060080201600201546139f7565b507fc42cff898171c085fa87ecad4869a5fb22753dddf61048199b8c740c2109fb1182604051611e639190615324565b60405180910390a15050565b60408051808201825260058152644e6f64657360d81b602080830191909152609754925160009333926001600160a01b039091169163ec56a37391611eb691869101615234565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401611ee89190615324565b60206040518083038186803b158015611f0057600080fd5b505afa158015611f14573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f389190615062565b6001600160a01b03161480611f505750611f5061264c565b611f6c5760405162461bcd60e51b815260040161052490615d40565b6000848152609c602052604090206119c0908463ffffffff613ac316565b600081565b6097546001600160a01b031681565b60985481908110611fc15760405162461bcd60e51b815260040161052490615cc0565b609754604051633581777360e01b81526000916001600160a01b031690633581777390611ff090600401615dae565b60206040518083038186803b15801561200857600080fd5b505afa15801561201c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120409190615062565b9050806001600160a01b031663bed5012e336098868154811061205f57fe5b9060005260206000209060080201600101546040518363ffffffff1660e01b815260040161208e929190615264565b60206040518083038186803b1580156120a657600080fd5b505afa1580156120ba573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120de91906150dd565b6120fa5760405162461bcd60e51b81526004016105249061583c565b61214c6098848154811061210a57fe5b6000918252602090912060089091020154609880546001600160a01b03909216918690811061213557fe5b90600052602060002090600802016001015461308e565b506000612158846119ca565b9050600081600681111561216857fe5b1461223357600181600681111561217b57fe5b14806121925750600481600681111561219057fe5b145b806121a8575060058160068111156121a657fe5b145b806121be575060068160068111156121bc57fe5b145b156121db5760405162461bcd60e51b8152600401610524906154d5565b60028160068111156121e957fe5b14156122075760405162461bcd60e51b815260040161052490615c6f565b600381600681111561221557fe5b14156122335760405162461bcd60e51b8152600401610524906156f1565b600081600681111561224157fe5b1461225e5760405162461bcd60e51b815260040161052490615b86565b609754604051633581777360e01b81526000916001600160a01b03169063358177739061228d90600401615684565b60206040518083038186803b1580156122a557600080fd5b505afa1580156122b9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122dd9190615062565b90506060612310609887815481106122f157fe5b60009182526020909120600890910201546001600160a01b031661265e565b905061231b86613be3565b816001600160a01b03166394df393f6098888154811061233757fe5b906000526020600020906008020160000160009054906101000a90046001600160a01b03168860988a8154811061236a57fe5b90600052602060002090600802016002015460988b8154811061238957fe5b9060005260206000209060080201600501546040518563ffffffff1660e01b81526004016123ba949392919061529e565b600060405180830381600087803b1580156123d457600080fd5b505af11580156123e8573d6000803e3d6000fd5b505050506123f5816127b2565b7fdb0c41de0e1a6e61f3ea29d9618edd8bfe8cb4e041a267c54eec70418341272d866040516124249190615324565b60405180910390a1505050505050565b6098818154811061244157fe5b60009182526020918290206008909102018054600180830154600280850154600386015460048701546005880154600689015460078a01805460408051601f6000199c841615610100029c909c0190921698909804998a018d90048d0281018d019097528887526001600160a01b039099169b50959993989297919690959492938301828280156125135780601f106124e857610100808354040283529160200191612513565b820191906000526020600020905b8154815290600101906020018083116124f657829003601f168201915b5050505050905088565b600054610100900460ff16806125365750612536614095565b80612544575060005460ff16155b6125605760405162461bcd60e51b815260040161052490615a75565b600054610100900460ff1615801561258b576000805460ff1961ff0019909116610100171660011790555b6125948261409b565b80156107a6576000805461ff00191690555050565b60008181526065602052604081206104f190614125565b6000828152606560205260409020600201546125de906103ff6138d7565b6118835760405162461bcd60e51b81526004016105249061576a565b6001600160a01b03166000908152609a602052604090205490565b6000611cc98383612624612c74565b614130565b60006104f161263783611c50565b61264084613479565b9063ffffffff61416b16565b60006126588133611cd2565b90505b90565b60606104f18260006129b4565b600082600301546000141561268257506000611ccc565b8183600301541161279b5760038301545b8281116127835760008181526001808601602090815260408084205491889052832054612700926126f4919060028a019086906126d790899063ffffffff61419016565b81526020019081526020016000205461416b90919063ffffffff16565b9063ffffffff6141d216565b6000838152600287016020526040902054909150811461272e57600082815260028601602052604090208190555b60008281526020869052604090205415612752576000828152602086905260408120555b60008281526001860160205260409020541561277a5760008281526001860160205260408120555b50600101612693565b5061279582600163ffffffff61416b16565b60038401555b506000908152600291909101602052604090205490565b609754604051633581777360e01b81526000916001600160a01b0316906335817773906127e19060040161546c565b60206040518083038186803b1580156127f957600080fd5b505afa15801561280d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128319190615062565b9050600080805b845181101561294657826001600160a01b031685828151811061285757fe5b6020026020010151600001516001600160a01b0316146129115781156128d857604051634458328b60e01b81526001600160a01b03851690634458328b906128a59086908690600401615264565b600060405180830381600087803b1580156128bf57600080fd5b505af11580156128d3573d6000803e3d6000fd5b505050505b8481815181106128e457fe5b60200260200101516000015192508481815181106128fe57fe5b602002602001015160200151915061293e565b61293b85828151811061292057fe5b6020026020010151602001518361416b90919063ffffffff16565b91505b600101612838565b5080156129ae57604051634458328b60e01b81526001600160a01b03841690634458328b9061297b9085908590600401615264565b600060405180830381600087803b15801561299557600080fd5b505af11580156129a9573d6000803e3d6000fd5b505050505b50505050565b60606129bf83611816565b15611ccc576001600160a01b038316600090815260a3602052604090205460a25483158015906129fd5750806129fb838663ffffffff61416b16565b105b15612a1557612a12828563ffffffff61416b16565b90505b612a25818363ffffffff61419016565b67ffffffffffffffff81118015612a3b57600080fd5b50604051908082528060200260200182016040528015612a7557816020015b612a62614f97565b815260200190600190039081612a5a5790505b509250815b81831015612c5357600060a28481548110612a9157fe5b9060005260206000209060040201600201549050600060a28581548110612ab457fe5b90600052602060002090600402016003015490506000612ad5898484614130565b9050612ae881600063ffffffff61422516565b15612c45576001600160a01b0389166000908152609f6020526040902060a28054612b6a92919089908110612b1957fe5b6000918252602080832060408051808201825260049094029091018054845260010154838301526001600160a01b038f16845260a0825280842089855290915290912091908563ffffffff61423e16565b612bca60a28781548110612b7a57fe5b6000918252602080832060408051808201825260049094029091018054845260010154838301526001600160a01b038e16845260a18252808420888552909152909120908463ffffffff612e4216565b8887612bdc888763ffffffff61419016565b81518110612be657fe5b60209081029190910101516001600160a01b039091169052612c19612c0c8a8585614130565b829063ffffffff6141d216565b87612c2a888763ffffffff61419016565b81518110612c3457fe5b602002602001015160200181815250505b505050826001019250612a7a565b506001600160a01b038516600090815260a360205260409020555092915050565b609754604051633581777360e01b815260009182916001600160a01b0390911690633581777390612ca79060040161565f565b60206040518083038186803b158015612cbf57600080fd5b505afa158015612cd3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cf79190615062565b9050806001600160a01b031663ddd1b67e6040518163ffffffff1660e01b815260040160206040518083038186803b158015612d3257600080fd5b505afa158015612d46573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d6a9190615165565b91505090565b612d78614f7d565b6003840154612d8e83600163ffffffff61416b16565b1015612dac5760405162461bcd60e51b815260040161052490615435565b6003840154612dc657612dbf600061424c565b9050612e3b565b6000612dd28584613ac3565b9050612de581600063ffffffff61425f16565b15612dfc57612df4600061424c565b915050612e3b565b8380821015612e085750805b612e10614f7d565b612e29612e23848463ffffffff6141d216565b84614285565b9050612e368782876142d5565b925050505b9392505050565b6003830154612e5882600163ffffffff61416b16565b1015612e765760405162461bcd60e51b815260040161052490615733565b602082015182511115612e9b5760405162461bcd60e51b81526004016105249061548e565b6003830154612ea957612f8d565b6000612eb5848361266b565b9050612ec881600063ffffffff61425f16565b15612ed35750612f8d565b6020808401518451600085815260028801909352604090922054612f0d92612f01919063ffffffff61384a16565b9063ffffffff6142e316565b6000838152600286016020526040812091909155612f3283600163ffffffff61416b16565b90505b84600401548111612f8a576020808501518551600084815260018901909352604090922054612f6e92612f01919063ffffffff61384a16565b6000828152600180880160205260409091209190915501612f35565b50505b505050565b6001830154612fd057600180840182905560028085018390556000838152602086815260408220865181559086015193810193909355910155612f8d565b8083600201541115612ff45760405162461bcd60e51b815260040161052490615a30565b808360020154141561305557600081815260208481526040918290208251808401909352805483526001015490820152613034908363ffffffff61432516565b60008281526020858152604090912082518155910151600190910155612f8d565b60008181526020848152604080832085518155918501516001830155600291820183905581860180548452922001829055819055505050565b609754604051633581777360e01b815260009182916001600160a01b03909116906335817773906130c19060040161557a565b60206040518083038186803b1580156130d957600080fd5b505afa1580156130ed573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131119190615062565b6001600160a01b038516600090815260a6602090815260408083208784526001019091529020549091501515806131fe57506001600160a01b038416600090815260a6602090815260408083208684526001019091529020541580156131fe5750806001600160a01b031663049e41776040518163ffffffff1660e01b815260040160206040518083038186803b1580156131ab57600080fd5b505afa1580156131bf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131e39190615165565b6001600160a01b038516600090815260a66020526040902054105b6119c35760405162461bcd60e51b815260040161052490615d77565b6098805460408051610100810182526001600160a01b03898116825260208083018a8152938301898152606084018981524260808601908152600060a0870181815260c0880182815260e089018d815260018c018d559b90925287517f2237a976fa961f5921fd19f2b03c925c725d77b20ce8f790c19709c03de4d81460088c0290810180546001600160a01b0319169290991691909117885598517f2237a976fa961f5921fd19f2b03c925c725d77b20ce8f790c19709c03de4d8158a015593517f2237a976fa961f5921fd19f2b03c925c725d77b20ce8f790c19709c03de4d81689015591517f2237a976fa961f5921fd19f2b03c925c725d77b20ce8f790c19709c03de4d817880155517f2237a976fa961f5921fd19f2b03c925c725d77b20ce8f790c19709c03de4d81887015590517f2237a976fa961f5921fd19f2b03c925c725d77b20ce8f790c19709c03de4d819860155517f2237a976fa961f5921fd19f2b03c925c725d77b20ce8f790c19709c03de4d81a850155945180519495929491936133d1937f2237a976fa961f5921fd19f2b03c925c725d77b20ce8f790c19709c03de4d81b90910192910190614fae565b5050506000858152609960209081526040808320805460018181018355918552838520018590556001600160a01b038a168452609a83529083208054918201815583529120018190556098805461346f91908390811061342d57fe5b6000918252602090912060089091020154609880546001600160a01b03909216918490811061345857fe5b906000526020600020906008020160020154614363565b5095945050505050565b600080613484612c74565b905061348f83611c42565b6001600160a01b0383166000908152609f60205260409020612e3b908263ffffffff613ac316565b6001600160a01b038216600090815260a660209081526040808320848452600190810190925290912054141561352b576001600160a01b038216600090815260a6602052604090205461351190600163ffffffff61419016565b6001600160a01b038316600090815260a660205260409020555b6001600160a01b038216600090815260a6602090815260408083208484526001908101909252909120546135649163ffffffff61419016565b6001600160a01b03909216600090815260a660209081526040808320938352600190930190522055565b600080613599612c74565b90506000609884815481106135aa57fe5b906000526020600020906008020160050154905080821015613600576135f7609885815481106135d657fe5b9060005260206000209060080201600301548261416b90919063ffffffff16565b925050506104f4565b60006136376098868154811061361257fe5b906000526020600020906008020160030154612f01848661419090919063ffffffff16565b905061368b61367e6098878154811061364c57fe5b90600052602060002090600802016003015461367260018561416b90919063ffffffff16565b9063ffffffff61384a16565b839063ffffffff61416b16565b93505050506104f4565b6000818152609b602052604081205460988054839190859081106136b557fe5b90600052602060002090600802016001015490506000609885815481106136d857fe5b90600052602060002090600802016002015490508260001415613718576000828152609e60205260409020600101549250826137185792506104f4915050565b825b60008111801561374757506098868154811061373257fe5b90600052602060002090600802016006015481105b156137c5576098868154811061375957fe5b90600052602060002090600802016005015481106137a4576000838152609e602090815260408083208484529091529020600181015490546137a19190612f0190859061384a565b91505b6000838152609e60209081526040808320938352929052206002015461371a565b50949350505050565b6000838152609c60205260409020612f8d90838363ffffffff61440716565b6001600160a01b0383166000908152609f60205260409020612f8d90838363ffffffff61440716565b6001600160a01b038416600090815260a06020908152604080832086845290915290206129ae90838363ffffffff61440716565b60008261385957506000611ccc565b8282028284828161386657fe5b0414611cc95760405162461bcd60e51b815260040161052490615920565b6000838152609d60205260409020612f8d90838363ffffffff6144c816565b6001600160a01b038416600090815260a16020908152604080832086845290915290206129ae90838363ffffffff6144c816565b3390565b60008281526065602052604090206138f9908263ffffffff61454616565b156107a6576139066138d7565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6001600160a01b0316600090815260a46020526040902054151590565b6000828152606560205260409020613985908263ffffffff61455b16565b156107a6576139926138d7565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b6000611cc98383614570565b6000611cc9836001600160a01b0384166145b5565b600080613a02612c74565b6001600160a01b038516600090815260a560205260409020600101549091508114613a3f5760405162461bcd60e51b8152600401610524906157f1565b6001600160a01b038416600090815260a56020526040902054831115613a775760405162461bcd60e51b815260040161052490615895565b6001600160a01b038416600090815260a56020526040902054613aa0908463ffffffff61419016565b6001600160a01b03909416600090815260a5602052604090209390935592915050565b6003820154600090613adc83600163ffffffff61416b16565b1015613afa5760405162461bcd60e51b8152600401610524906156af565b6003830154613b0b57506000611ccc565b81836003015411613bda5760038301545b828111613bc2576000818152600185016020908152604080832054918790528220546002870154613b5892916126f4919063ffffffff61416b16565b905080856002015414613b6d57600285018190555b60008281526020869052604090205415613b91576000828152602086905260408120555b600082815260018601602052604090205415613bb95760008281526001860160205260408120555b50600101613b1c565b50613bd482600163ffffffff61416b16565b60038401555b50506002015490565b609754604051633581777360e01b81526000916001600160a01b031690633581777390613c12906004016159f9565b60206040518083038186803b158015613c2a57600080fd5b505afa158015613c3e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613c629190615062565b90506000613c6e612c74565b9050613c8181600163ffffffff61416b16565b60988481548110613c8e57fe5b9060005260206000209060080201600501819055506000609e600060988681548110613cb657fe5b9060005260206000209060080201600101548152602001908152602001600020600201541115613d2757609e600060988581548110613cf157fe5b60009182526020808320600160089093020191909101548352828101939093526040918201812060020154868252609b90935220555b613d8160988481548110613d3757fe5b90600052602060002090600802016001015460988581548110613d5657fe5b906000526020600020906008020160020154613d7c60018561416b90919063ffffffff16565b6145cd565b613de760988481548110613d9157fe5b6000918252602090912060089091020154609880546001600160a01b039092169186908110613dbc57fe5b906000526020600020906008020160020154613de260018561416b90919063ffffffff16565b6145ec565b613e6c60988481548110613df757fe5b6000918252602090912060089091020154609880546001600160a01b039092169186908110613e2257fe5b90600052602060002090600802016001015460988681548110613e4157fe5b906000526020600020906008020160020154613e6760018661416b90919063ffffffff16565b614615565b613ed260988481548110613e7c57fe5b6000918252602090912060089091020154609880546001600160a01b039092169186908110613ea757fe5b906000526020600020906008020160010154613ecd60018561416b90919063ffffffff16565b614649565b6000613f9e836001600160a01b031663f5b98f4160988781548110613ef357fe5b9060005260206000209060080201600301546040518263ffffffff1660e01b8152600401613f219190615324565b60206040518083038186803b158015613f3957600080fd5b505afa158015613f4d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f719190615165565b60988681548110613f7e57fe5b90600052602060002090600802016002015461384a90919063ffffffff16565b9050613fdc60988581548110613fb057fe5b90600052602060002090600802016001015482613fd760018661416b90919063ffffffff16565b6146e7565b61404360988581548110613fec57fe5b6000918252602090912060089091020154609880546001600160a01b03909216918790811061401757fe5b9060005260206000209060080201600101548361403e60018761416b90919063ffffffff16565b614706565b6129ae6098858154811061405357fe5b6000918252602090912060089091020154609880546001600160a01b03909216918790811061407e57fe5b90600052602060002090600802016001015461473a565b303b1590565b600054610100900460ff16806140b457506140b4614095565b806140c2575060005460ff16155b6140de5760405162461bcd60e51b815260040161052490615a75565b600054610100900460ff16158015614109576000805460ff1961ff0019909116610100171660011790555b6141116147e2565b61411c60003361180c565b61259482614874565b60006104f1826148ea565b6001600160a01b038316600090815260a0602090815260408083208584529091528120614163908363ffffffff613ac316565b949350505050565b600082820183811015611cc95760405162461bcd60e51b8152600401610524906155f8565b6000611cc983836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506148ee565b60008183106141e45750808203611ccc565b7f5b70a077a991facb623c7b2ee44cc539dc6ba345b6636552b8ea97fbbd4d54198383604051614215929190615e94565b60405180910390a1506000611ccc565b6000620f424019821061423457fe5b50620f4240011090565b6129ae84848484600161491a565b614254614f7d565b6104f1826001614285565b6000818311156142775750620f424081830310611ccc565b50620f424082820310611ccc565b61428d614f7d565b600082116142ad5760405162461bcd60e51b815260040161052490615998565b6142b5614f7d565b6040518060400160405280858152602001848152509050611cc981614b01565b612f8d83848484600061491a565b6000611cc983836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250614b4d565b61432d614f7d565b81518351611cc991614345919063ffffffff61384a16565b6020808501519086015161435e9163ffffffff61384a16565b614285565b60008061436e612c74565b6001600160a01b038516600090815260a560205260409020600101549091508111156143ba576001600160a01b038416600090815260a5602052604090208381556001018190556119c3565b6001600160a01b038416600090815260a5602052604090206001015481146143de57fe5b6001600160a01b038416600090815260a56020526040902054613aa0908463ffffffff61416b16565b61441881600163ffffffff61416b16565b8360030154111561443b5760405162461bcd60e51b8152600401610524906159c2565b60038301546144535760038301819055600483018190555b826004015481111561446757600483018190555b826003015481106144a9576000818152600184016020526040902054614493908363ffffffff61416b16565b6000828152600185016020526040902055612f8d565b60028301546144be908363ffffffff6141d216565b6002840155505050565b80836003015411156144ec5760405162461bcd60e51b8152600401610524906159c2565b60038301546144fd57600383018190555b600081815260018401602052604090205461451e908363ffffffff61416b16565b600082815260018501602052604090205560048301548114612f8d5760048301819055505050565b6000611cc9836001600160a01b038416614b84565b6000611cc9836001600160a01b038416614bce565b815460009082106145935760405162461bcd60e51b8152600401610524906153a4565b8260000182815481106145a257fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b6000838152609c60205260409020612f8d90838363ffffffff614c9416565b6001600160a01b0383166000908152609f60205260409020612f8d90838363ffffffff614c9416565b6001600160a01b038416600090815260a06020908152604080832086845290915290206129ae90838363ffffffff614c9416565b6001600160a01b038316600090815260a46020526040902054614691576001600160a01b038316600090815260a46020908152604080832084905560a25460a3909252909120555b6001600160a01b038316600090815260a460209081526040808320858452600101909152902054612f8d576001600160a01b0392909216600090815260a460209081526040808320938352600190930190522055565b6000838152609d60205260409020612f8d90838363ffffffff614d3716565b6001600160a01b038416600090815260a16020908152604080832086845290915290206129ae90838363ffffffff614d3716565b6001600160a01b038216600090815260a6602090815260408083208484526001019091529020546147a9576001600160a01b038216600090815260a6602052604090205461478f90600163ffffffff61416b16565b6001600160a01b038316600090815260a660205260409020555b6001600160a01b038216600090815260a6602090815260408083208484526001908101909252909120546135649163ffffffff61416b16565b600054610100900460ff16806147fb57506147fb614095565b80614809575060005460ff16155b6148255760405162461bcd60e51b815260040161052490615a75565b600054610100900460ff16158015614850576000805460ff1961ff0019909116610100171660011790555b614858614db1565b614860614db1565b8015611c4d576000805461ff001916905550565b6001600160a01b03811661489a5760405162461bcd60e51b815260040161052490615ae7565b6148ac816001600160a01b0316614e32565b6148c85760405162461bcd60e51b815260040161052490615961565b609780546001600160a01b0319166001600160a01b0392909216919091179055565b5490565b600081848411156149125760405162461bcd60e51b81526004016105249190615341565b505050900390565b600385015461493083600163ffffffff61416b16565b101561494e5760405162461bcd60e51b815260040161052490615435565b801561498857600384015461496a83600163ffffffff61416b16565b10156149885760405162461bcd60e51b815260040161052490615435565b6020830151835111156149ad5760405162461bcd60e51b81526004016105249061548e565b60038501546149bb57612f8a565b60006149c78684613ac3565b90506149da81600063ffffffff61425f16565b156149e55750612f8a565b6000614a0a8560200151612f0187600001518a6002015461384a90919063ffffffff16565b90508215614a3357614a3386614a2d838a600201546141d290919063ffffffff16565b86614407565b600287018190556000614a4d85600163ffffffff61416b16565b90505b876004015481116129a9576020808701518751600084815260018c019093526040832054614a899291612f01919063ffffffff61384a16565b90508415614ae557600082815260018a016020526040902054614ad390614ab6908363ffffffff6141d216565b600084815260018b0160205260409020549063ffffffff6141d216565b600083815260018a0160205260409020555b60008281526001808b0160205260409091209190915501614a50565b6000614b1582600001518360200151614e6b565b8251909150614b2a908263ffffffff6142e316565b82526020820151614b41908263ffffffff6142e316565b60209092019190915250565b60008183614b6e5760405162461bcd60e51b81526004016105249190615341565b506000838581614b7a57fe5b0495945050505050565b6000614b9083836145b5565b614bc657508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155611ccc565b506000611ccc565b60008181526001830160205260408120548015614c8a5783546000198083019190810190600090879083908110614c0157fe5b9060005260206000200154905080876000018481548110614c1e57fe5b600091825260208083209091019290925582815260018981019092526040902090840190558654879080614c4e57fe5b60019003818190600052602060002001600090559055866001016000878152602001908152602001600020600090556001945050505050611ccc565b6000915050611ccc565b8083600301541115614cb85760405162461bcd60e51b81526004016105249061562f565b6003830154614cd05760038301819055600483018190555b8260040154811115614ce457600483018190555b82600301548110614d2257600081815260208490526040902054614d0e908363ffffffff61416b16565b600082815260208590526040902055612f8d565b60028301546144be908363ffffffff61416b16565b8083600301541115614d5b5760405162461bcd60e51b81526004016105249061562f565b6003830154614d6c57600383018190555b600081815260208490526040902054614d8b908363ffffffff61416b16565b60008281526020859052604090205560048301548114612f8d5760048301819055505050565b600054610100900460ff1680614dca5750614dca614095565b80614dd8575060005460ff16155b614df45760405162461bcd60e51b815260040161052490615a75565b600054610100900460ff16158015614860576000805460ff1961ff0019909116610100171660011790558015611c4d576000805461ff001916905550565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590614163575050151592915050565b6000828281811115614e8757614e818282614ebb565b90925090505b8015614eb357614e9d828263ffffffff614ebe16565b9150614ea98282614ebb565b9092509050614e87565b509392505050565b91565b6000611cc983836040518060400160405280601881526020017f536166654d6174683a206d6f64756c6f206279207a65726f000000000000000081525060008183614f1c5760405162461bcd60e51b81526004016105249190615341565b50828481614f2657fe5b06949350505050565b60405180610100016040528060006001600160a01b03168152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001606081525090565b604051806040016040528060008152602001600081525090565b604080518082019091526000808252602082015290565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10614fef57805160ff191683800117855561501c565b8280016001018555821561501c579182015b8281111561501c578251825591602001919060010190615001565b5061502892915061502c565b5090565b61265b91905b808211156150285760008155600101615032565b600060208284031215615057578081fd5b8135611cc981615ece565b600060208284031215615073578081fd5b8151611cc981615ece565b60008060408385031215615090578081fd5b823561509b81615ece565b946020939093013593505050565b6000806000606084860312156150bd578081fd5b83356150c881615ece565b95602085013595506040909401359392505050565b6000602082840312156150ee578081fd5b81518015158114611cc9578182fd5b60006020828403121561510e578081fd5b5035919050565b60008060408385031215615127578182fd5b82359150602083013561513981615ece565b809150509250929050565b60008060408385031215615156578182fd5b50508035926020909101359150565b600060208284031215615176578081fd5b5051919050565b600080600080600060808688031215615194578081fd5b853594506020860135935060408601359250606086013567ffffffffffffffff808211156151c0578283fd5b81880189601f8201126151d1578384fd5b80359250818311156151e1578384fd5b8960208483010111156151f2578384fd5b6020810194505050809150509295509295909350565b60008151808452615220816020860160208601615ea2565b601f01601f19169290920160200192915050565b60008251615246818460208701615ea2565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b03929092168252602082015260400190565b6001600160a01b039390931683526020830191909152604082015260600190565b6001600160a01b0394909416845260208401929092526040830152606082015260800190565b600061010060018060a01b038b1683528960208401528860408401528760608401528660808401528560a08401528460c08401528060e084015261530a81840185615208565b9b9a5050505050505050505050565b901515815260200190565b90815260200190565b602081016007831061533b57fe5b91905290565b600060208252611cc96020830184615208565b60208082526030908201527f4f6e6c7920746f6b656e20686f6c646572732063616e2063616e63656c20646560408201526f1b1959d85d1a5bdb881c995c5d595cdd60821b606082015260800190565b60208082526022908201527f456e756d657261626c655365743a20696e646578206f7574206f6620626f756e604082015261647360f01b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526e0818591b5a5b881d1bc819dc985b9d608a1b606082015260800190565b6020808252601f908201527f43616e6e6f74207265647563652076616c756520696e20746865207061737400604082015260600190565b602080825260089082015267283ab734b9b432b960c11b604082015260600190565b60208082526027908201527f496e6372656173696e67206f662076616c756573206973206e6f7420696d706c604082015266195b595b9d195960ca1b606082015260800190565b60208082526028908201527f5468652064656c65676174696f6e20686173206265656e20616c7265616479206040820152671858d8d95c1d195960c21b606082015260800190565b60208082526038908201527f56616c696461746f72206973206e6f7420617574686f72697a656420746f206160408201527f63636570742064656c65676174696f6e20726571756573740000000000000000606082015260800190565b6020808252600f908201526e21b7b739ba30b73a39a437b63232b960891b604082015260600190565b60208082526035908201527f5468652076616c696461746f72206973206e6f742063757272656e746c7920616040820152746363657074696e67206e657720726571756573747360581b606082015260800190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b60208082526016908201527510d85b9b9bdd08185919081d1bc81d1a19481c185cdd60521b604082015260600190565b6020808252600b908201526a54696d6548656c7065727360a81b604082015260600190565b6020808252601190820152702a37b5b2b72630bab731b42637b1b5b2b960791b604082015260600190565b60208082526022908201527f43616e6e6f742063616c63756c6174652076616c756520696e207468652070616040820152611cdd60f21b606082015260800190565b60208082526022908201527f5468652064656c65676174696f6e2072657175657374206973206f7574646174604082015261195960f21b606082015260800190565b6020808252601e908201527f43616e2774207265647563652076616c756520696e2074686520706173740000604082015260600190565b60208082526030908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526f2061646d696e20746f207265766f6b6560801b606082015260800190565b6020808252601b908201527f43616e6e6f74207265717565737420756e64656c65676174696f6e0000000000604082015260600190565b6020808252602b908201527f546865726520617265206e6f2064656c65676174696f6e20726571756573747360408201526a040e8d0d2e640dadedce8d60ab1b606082015260800190565b6020808252818101527f4e6f207065726d697373696f6e7320746f206163636570742072657175657374604082015260600190565b6020808252600a908201526929b5b0b632aa37b5b2b760b11b604082015260600190565b6020808252601b908201527f556e6c6f636b696e6720616d6f756e7420697320746f6f206269670000000000604082015260600190565b60208082526034908201527f546f6b656e20686f6c64657220646f6573206e6f74206861766520656e6f75676040820152736820746f6b656e7320746f2064656c656761746560601b606082015260800190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b60208082526017908201527f41646472657373206973206e6f7420636f6e7472616374000000000000000000604082015260600190565b60208082526010908201526f4469766973696f6e206279207a65726f60801b604082015260600190565b6020808252601d908201527f43616e6e6f742073756274726163742066726f6d207468652070617374000000604082015260600190565b60208082526017908201527f44656c65676174696f6e506572696f644d616e61676572000000000000000000604082015260600190565b60208082526025908201527f43616e6e6f742070757420736c617368696e67206576656e7420696e20746865604082015264081c185cdd60da1b606082015260800190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b6020808252600a9082015269546f6b656e537461746560b01b604082015260600190565b60208082526022908201527f436f6e74726163744d616e616765722061646472657373206973206e6f742073604082015261195d60f21b606082015260800190565b6020808252603a908201527f546f6b656e20686f6c6465727320617265206f6e6c792061626c6520746f206360408201527f616e63656c2050524f504f5345442064656c65676174696f6e73000000000000606082015260800190565b60208082526027908201527f43616e6e6f74207365742064656c65676174696f6e20737461746520746f206160408201526618d8d95c1d195960ca1b606082015260800190565b60208082526025908201527f546869732064656c65676174696f6e20706572696f64206973206e6f7420616c6040820152641b1bddd95960da1b606082015260800190565b6020808252603e908201527f416d6f756e7420646f6573206e6f74206d656574207468652076616c6964617460408201527f6f722773206d696e696d756d2064656c65676174696f6e20616d6f756e740000606082015260800190565b60208082526031908201527f5468652064656c65676174696f6e20686173206265656e2063616e63656c6c656040820152703210313c903a37b5b2b7103437b63232b960791b606082015260800190565b60208082526019908201527f44656c65676174696f6e20646f6573206e6f7420657869737400000000000000604082015260600190565b60208082526029908201527f5065726d697373696f6e2064656e69656420746f207265717565737420756e6460408201526832b632b3b0ba34b7b760b91b606082015260800190565b60208082526019908201527f4d6573736167652073656e64657220697320696e76616c696400000000000000604082015260600190565b6020808252601e908201527f4c696d6974206f662076616c696461746f727320697320726561636865640000604082015260600190565b60208082526010908201526f56616c696461746f725365727669636560801b604082015260600190565b6020808252602f908201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560408201526e103937b632b9903337b91039b2b63360891b606082015260800190565b60006020825260018060a01b038351166020830152602083015160408301526040830151606083015260608301516080830152608083015160a083015260a083015160c083015260c083015160e083015260e08301516101008081850152506119c0610120840182615208565b918252602082015260400190565b60005b83811015615ebd578181015183820152602001615ea5565b838111156129ae5750506000910152565b6001600160a01b0381168114611c4d57600080fdfea264697066735822122088c330383e3eca2d1dd22b553b5b109eafd04aa92a00d266c363bddb03bdaf0064736f6c634300060a0033
{"success": true, "error": null, "results": {"detectors": [{"check": "uninitialized-state", "impact": "High", "confidence": "High"}, {"check": "divide-before-multiply", "impact": "Medium", "confidence": "Medium"}, {"check": "reentrancy-no-eth", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "write-after-write", "impact": "Medium", "confidence": "High"}, {"check": "weak-prng", "impact": "High", "confidence": "Medium"}]}}
true
null
{'detectors': [{'check': 'uninitialized-state', 'impact': 'High', 'confidence': 'High'}, {'check': 'divide-before-multiply', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'reentrancy-no-eth', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'write-after-write', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'weak-prng', 'impact': 'High', 'confidence': 'Medium'}]}
99
0x1f86e194446787AdF12123103a2f6362a894F0Ac
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 = 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 = 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); 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))); } } } 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] && _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; } 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; } } 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, 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 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 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; } 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) * (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]); } } function getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } } 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); 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 = 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 = 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 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(swapedTokens >= 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; } 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)); 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(DAI_JOIN_ADDRESS); 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 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(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); 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(); (,,,,,,,,,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); 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 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 = 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) { (, 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 = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB; /// @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])); } } }
0x6080604052600436106102465760003560e01c8063526d646111610139578063a8c90323116100b6578063d98bb5b11161007a578063d98bb5b1146105f5578063deca5f8814610615578063e3bbb4f114610635578063f05def811461064a578063f24ccbfe1461066a578063f851a4401461067f57610246565b8063a8c9032314610576578063b20b720914610596578063bfc36172146105ab578063bfe142a3146105cb578063c91d59fe146105e057610246565b80637f9ad5d6116100fd5780637f9ad5d614610504578063870e44d9146105175780638da5cb5b1461052c578063a56f971814610541578063a7304bf71461055657610246565b8063526d64611461049b578063696806c0146104b05780637753f47b146104c557806379521f02146104da5780637b925ab1146104ef57610246565b806336fc603f116101c7578063441697521161018b578063441697521461041157806349a3d737146104265780634d2ab9dc146104465780634d3f199e1461045b57806351c4a6311461047b57610246565b806336fc603f146103925780633816377e146103a757806339df1878146103c75780633a128322146103dc57806341c0e1b5146103fc57610246565b80631e48907b1161020e5780631e48907b146102f05780631ec18ec0146103105780632a56f602146103305780632b6e6581146103505780632b8f40071461037057610246565b806304c9805c1461024b57806305a363de1461027657806306d5e37e14610298578063087b0286146102c657806318bf60e1146102db575b600080fd5b34801561025757600080fd5b50610260610694565b60405161026d9190612722565b60405180910390f35b34801561028257600080fd5b5061028b61069a565b60405161026d9190612713565b3480156102a457600080fd5b506102b86102b3366004612144565b61069f565b60405161026d9291906125af565b6102d96102d43660046121ee565b61086d565b005b3480156102e757600080fd5b50610260610bbf565b3480156102fc57600080fd5b506102d961030b36600461204d565b610bc5565b34801561031c57600080fd5b5061026061032b366004612085565b610bfe565b34801561033c57600080fd5b5061026061034b3660046122e2565b610e41565b34801561035c57600080fd5b5061026061036b366004612085565b610e6b565b34801561037c57600080fd5b5061038561133e565b60405161026d9190612490565b34801561039e57600080fd5b5061026061134d565b3480156103b357600080fd5b506102d96103c23660046122e2565b611353565b3480156103d357600080fd5b50610385611380565b3480156103e857600080fd5b506102d96103f73660046120fd565b611398565b34801561040857600080fd5b506102d9611437565b34801561041d57600080fd5b5061038561145c565b34801561043257600080fd5b506102d9610441366004612085565b611474565b34801561045257600080fd5b5061026061152a565b34801561046757600080fd5b506102d96104763660046122e2565b611530565b34801561048757600080fd5b506102d96104963660046120bd565b61155b565b3480156104a757600080fd5b506103856115e5565b3480156104bc57600080fd5b506102606115fd565b3480156104d157600080fd5b50610385611603565b3480156104e657600080fd5b5061038561161b565b3480156104fb57600080fd5b5061038561162a565b6102d96105123660046121ee565b611642565b34801561052357600080fd5b5061026061194f565b34801561053857600080fd5b5061038561195b565b34801561054d57600080fd5b5061026061196a565b34801561056257600080fd5b506102d961057136600461204d565b611970565b34801561058257600080fd5b506102d96105913660046122e2565b6119a9565b3480156105a257600080fd5b506103856119d4565b3480156105b757600080fd5b506102b86105c6366004612144565b6119e3565b3480156105d757600080fd5b50610385611ae2565b3480156105ec57600080fd5b50610385611afa565b34801561060157600080fd5b5061026061061036600461204d565b611b0d565b34801561062157600080fd5b506102d961063036600461204d565b611c3d565b34801561064157600080fd5b50610260611c6a565b34801561065657600080fd5b506102d9610665366004612312565b611c70565b34801561067657600080fd5b50610385611c9d565b34801561068b57600080fd5b50610385611cac565b61014d81565b604081565b600854604051632e4aba1f60e21b8152600091829182916001600160a01b03169063b92ae87c906106d4908790600401612490565b60206040518083038186803b1580156106ec57600080fd5b505afa158015610700573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107249190612128565b905061072e611f8d565b60085460405163335d71f560e21b81526001600160a01b039091169063cd75c7d49061075e908890600401612490565b60c06040518083038186803b15801561077657600080fd5b505afa15801561078a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107ae9190612164565b9050816107c45750600092508291506108669050565b60008660018111156107d257fe5b1480156107e157508060a00151155b156107f55750600092508291506108669050565b600061080086611b0d565b9050600187600181111561081057fe5b1415610832576020909101516001600160801b03168110935091506108669050565b600087600181111561084057fe5b1415610862576040909101516001600160801b03168111935091506108669050565b5050505b9250929050565b6040516320eb73ed60e11b815273637726f8b08a7abe3ae3acab01a80e2d8ddef77b906341d6e7da906108a4903390600401612490565b60206040518083038186803b1580156108bc57600080fd5b505afa1580156108d0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108f49190612128565b6109195760405162461bcd60e51b815260040161091090612609565b60405180910390fd5b6003546040516370a0823160e01b815281906eb3f879cb30fe243b4dfee438691c04906370a0823190610950903090600401612490565b60206040518083038186803b15801561096857600080fd5b505afa15801561097c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109a091906122fa565b10610a2b5760405163d8ccd0f360e01b81526eb3f879cb30fe243b4dfee438691c049063d8ccd0f3906109d7908490600401612722565b602060405180830381600087803b1580156109f157600080fd5b505af1158015610a05573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a299190612128565b505b600080610a3960008561069f565b9150915081610a4757600080fd5b6000610a54600654610e41565b6007546009546040519293506001600160a01b0391821692638a0e833f9234928a92911690610a89908c908890602401612679565b60408051601f198184030181529181526020820180516001600160e01b03166378e810b160e11b1790525160e086901b6001600160e01b0319168152610ad4939291906004016124be565b6000604051808303818588803b158015610aed57600080fd5b505af1158015610b01573d6000803e3d6000fd5b5050505050600080610b146000886119e3565b9150915081610b2257600080fd5b610b2a611cbb565b600a546040516001600160a01b039091169063d061ce509030908a90610b56908990879060200161272b565b6040516020818303038152906040526040518463ffffffff1660e01b8152600401610b8393929190612540565b600060405180830381600087803b158015610b9d57600080fd5b505af1158015610bb1573d6000803e3d6000fd5b505050505050505050505050565b60065481565b6001546001600160a01b03163314610bdc57600080fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015610c4e57600080fd5b505afa158015610c62573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c869190612069565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b158015610cd757600080fd5b505afa158015610ceb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d0f9190612069565b90506000826001600160a01b031663bf92857c866040518263ffffffff1660e01b8152600401610d3f9190612490565b6101006040518083038186803b158015610d5857600080fd5b505afa158015610d6c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d9091906123df565b5050509450505050506000826001600160a01b031663b3596f07886040518263ffffffff1660e01b8152600401610dc79190612490565b60206040518083038186803b158015610ddf57600080fd5b505afa158015610df3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e1791906122fa565b9050610e34610e268383611cf1565b670de05bc096e9c000611d22565b9450505050505b92915050565b6000806004543a1115610e5657600454610e58565b3a5b9050610e648184611d4a565b9392505050565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316632f58b80d6040518163ffffffff1660e01b815260040160206040518083038186803b158015610ebb57600080fd5b505afa158015610ecf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ef39190612069565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b158015610f4457600080fd5b505afa158015610f58573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f7c9190612069565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b158015610fcd57600080fd5b505afa158015610fe1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110059190612069565b90506000806000856001600160a01b0316632c6d0e9b896040518263ffffffff1660e01b81526004016110389190612490565b6101006040518083038186803b15801561105157600080fd5b505afa158015611065573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110899190612376565b50505094505093509350506000856001600160a01b0316635fc526ff8b6040518263ffffffff1660e01b81526004016110c29190612490565b60806040518083038186803b1580156110da57600080fd5b505afa1580156110ee573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111129190612336565b50509150506000856001600160a01b031663b3596f078c6040518263ffffffff1660e01b81526004016111459190612490565b60206040518083038186803b15801561115d57600080fd5b505afa158015611171573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061119591906122fa565b90506000876001600160a01b03166318a4dbca8d8d6040518363ffffffff1660e01b81526004016111c79291906124a4565b60206040518083038186803b1580156111df57600080fd5b505afa1580156111f3573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061121791906122fa565b905060006112258284611d22565b90508561123d57509850610e3b975050505050505050565b600061126561125f61124f888b611d4a565b61125a8a6064611d4a565b611d6e565b87611d7e565b90508181116112745780611276565b815b905087811061129257879b505050505050505050505050610e3b565b60006112ab6112a1888b611d22565b61125a8886611d22565b905060006112dd6112ce836112c96112c38888611d6e565b8b611d22565b611d89565b6112d88c86611d6e565b611cf1565b90508781101561131c576113086113026112f7838d611d4a565b61125a8c6064611d4a565b82611d7e565b92508383116113175782611319565b835b92505b611329610e268488611cf1565b9d505050505050505050505050505092915050565b6009546001600160a01b031681565b60055481565b6000546001600160a01b0316331461136a57600080fd5b64746a528800811061137b57600080fd5b600455565b735c55b921f590a89c1ebe84df170e655a82b6212681565b6000546001600160a01b031633146113af57600080fd5b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6001600160a01b038316141561141357600080546040516001600160a01b039091169183156108fc02918491818181858888f1935050505015801561140d573d6000803e3d6000fd5b50611433565b600054611433906001600160a01b0384811691168363ffffffff611d9916565b5050565b6000546001600160a01b0316331461144e57600080fd5b6000546001600160a01b0316ff5b73322d58b9e75a6918f7e7849aee0ff09369977e0881565b6001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14156114a9576114a482824761155b565b611433565b6114338282846001600160a01b03166370a08231306040518263ffffffff1660e01b81526004016114da9190612490565b60206040518083038186803b1580156114f257600080fd5b505afa158015611506573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061049691906122fa565b61019081565b6000546001600160a01b0316331461154757600080fd5b622dc6c0811061155657600080fd5b600555565b80611565576115e0565b6001600160a01b03831673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14156115c6576040516001600160a01b0383169082156108fc029083906000818181858888f193505050501580156115c0573d6000803e3d6000fd5b506115e0565b6115e06001600160a01b038416838363ffffffff611d9916565b505050565b73637726f8b08a7abe3ae3acab01a80e2d8ddef77b81565b60035481565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b6008546001600160a01b031681565b731b14e8d511c9a4395425314f849bd737baf8208f81565b6040516320eb73ed60e11b815273637726f8b08a7abe3ae3acab01a80e2d8ddef77b906341d6e7da90611679903390600401612490565b60206040518083038186803b15801561169157600080fd5b505afa1580156116a5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116c99190612128565b6116e55760405162461bcd60e51b815260040161091090612609565b6002546040516370a0823160e01b815281906eb3f879cb30fe243b4dfee438691c04906370a082319061171c903090600401612490565b60206040518083038186803b15801561173457600080fd5b505afa158015611748573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061176c91906122fa565b106117f75760405163d8ccd0f360e01b81526eb3f879cb30fe243b4dfee438691c049063d8ccd0f3906117a3908490600401612722565b602060405180830381600087803b1580156117bd57600080fd5b505af11580156117d1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117f59190612128565b505b60008061180560018561069f565b915091508161181357600080fd5b6000611820600554610e41565b6007546009546040519293506001600160a01b0391821692638a0e833f9234928a92911690611855908c908890602401612679565b60408051601f198184030181529181526020820180516001600160e01b0316633a84827360e11b1790525160e086901b6001600160e01b03191681526118a0939291906004016124be565b6000604051808303818588803b1580156118b957600080fd5b505af11580156118cd573d6000803e3d6000fd5b50505050506000806118e06001886119e3565b91509150816118ee57600080fd5b6118f6611cbb565b600a546040516001600160a01b039091169063d061ce509030908a90611922908990879060200161272b565b6040516020818303038152906040526040518463ffffffff1660e01b8152600401610b83939291906124ea565b670de05bc096e9c00081565b6000546001600160a01b031681565b60025481565b6001546001600160a01b0316331461198757600080fd5b600180546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b031633146119c057600080fd5b622dc6c081106119cf57600080fd5b600655565b6007546001600160a01b031681565b6000806119ee611f8d565b60085460405163335d71f560e21b81526001600160a01b039091169063cd75c7d490611a1e908790600401612490565b60c06040518083038186803b158015611a3657600080fd5b505afa158015611a4a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a6e9190612164565b90506000611a7b85611b0d565b90506001866001811115611a8b57fe5b1415611aab576040909101516001600160801b0316811092509050610866565b6000866001811115611ab957fe5b1415611ad9576020909101516001600160801b0316811192509050610866565b50509250929050565b7324a42fd28c976a61df5d00d0599c34c4f90748c881565b6eb3f879cb30fe243b4dfee438691c0481565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015611b5d57600080fd5b505afa158015611b71573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b959190612069565b9050600080826001600160a01b031663bf92857c866040518263ffffffff1660e01b8152600401611bc69190612490565b6101006040518083038186803b158015611bdf57600080fd5b505afa158015611bf3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c1791906123df565b50505094505093505050611c34611c2e8383611d89565b83611cf1565b95945050505050565b6000546001600160a01b03163314611c5457600080fd5b6001546001600160a01b03161561198757600080fd5b60045481565b6000546001600160a01b03163314611c8757600080fd5b8015611c97576002829055611433565b50600355565b600a546001600160a01b031681565b6001546001600160a01b031681565b4715611cef5760405133904780156108fc02916000818181858888f19350505050158015611ced573d6000803e3d6000fd5b505b565b600081611d13611d0985670de0b6b3a7640000611d4a565b6002855b04611d89565b81611d1a57fe5b049392505050565b6000670de0b6b3a7640000611d13611d3a8585611d4a565b6002670de0b6b3a7640000611d0d565b6000811580611d6557505080820282828281611d6257fe5b04145b610e3b57600080fd5b80820382811115610e3b57600080fd5b6000818381611d1a57fe5b80820182811015610e3b57600080fd5b6115e08363a9059cbb60e01b8484604051602401611db8929190612596565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526060611e3f826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611e799092919063ffffffff16565b8051909150156115e05780806020019051810190611e5d9190612128565b6115e05760405162461bcd60e51b81526004016109109061262f565b6060611e888484600085611e90565b949350505050565b6060611e9b85611f54565b611eb75760405162461bcd60e51b8152600401610910906125d2565b60006060866001600160a01b03168587604051611ed49190612474565b60006040518083038185875af1925050503d8060008114611f11576040519150601f19603f3d011682016040523d82523d6000602084013e611f16565b606091505b50915091508115611f2a579150611e889050565b805115611f3a5780518082602001fd5b8360405162461bcd60e51b815260040161091091906125bf565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590611e88575050151592915050565b6040805160c081018252600080825260208201819052918101829052606081018290526080810182905260a081019190915290565b8035610e3b81612790565b600082601f830112611fdd578081fd5b813567ffffffffffffffff811115611ff3578182fd5b612006601f8201601f1916602001612739565b915080825283602082850101111561201d57600080fd5b8060208401602084013760009082016020015292915050565b80516001600160801b0381168114610e3b57600080fd5b60006020828403121561205e578081fd5b8135610e6481612790565b60006020828403121561207a578081fd5b8151610e6481612790565b60008060408385031215612097578081fd5b82356120a281612790565b915060208301356120b281612790565b809150509250929050565b6000806000606084860312156120d1578081fd5b83356120dc81612790565b925060208401356120ec81612790565b929592945050506040919091013590565b6000806040838503121561210f578182fd5b823561211a81612790565b946020939093013593505050565b600060208284031215612139578081fd5b8151610e64816127a5565b60008060408385031215612156578182fd5b8235600281106120a2578283fd5b600060c08284031215612175578081fd5b61217f60c0612739565b825161218a81612790565b81526121998460208501612036565b60208201526121ab8460408501612036565b60408201526121bd8460608501612036565b60608201526121cf8460808501612036565b608082015260a08301516121e2816127a5565b60a08201529392505050565b60008060408385031215612200578182fd5b823567ffffffffffffffff80821115612217578384fd5b61012091850180870383131561222b578485fd5b61223483612739565b61223e8883611fc2565b815261224d8860208401611fc2565b602082015260408201356040820152606082013560608201526080820135608082015261227d8860a08401611fc2565b60a082015261228f8860c08401611fc2565b60c082015260e08201359350828411156122a7578586fd5b6122b388858401611fcd565b60e082015261010093508382013584820152809550505050506122d98460208501611fc2565b90509250929050565b6000602082840312156122f3578081fd5b5035919050565b60006020828403121561230b578081fd5b5051919050565b60008060408385031215612324578182fd5b8235915060208301356120b2816127a5565b6000806000806080858703121561234b578182fd5b845193506020850151925060408501519150606085015161236b816127a5565b939692955090935050565b600080600080600080600080610100898b031215612392578586fd5b885197506020890151965060408901519550606089015194506080890151935060a0890151925060c0890151915060e08901516123ce816127a5565b809150509295985092959890939650565b600080600080600080600080610100898b0312156123fb578182fd5b505086516020880151604089015160608a015160808b015160a08c015160c08d015160e0909d0151959e949d50929b919a50985090965094509092509050565b6001600160a01b03169052565b60008151808452612460816020860160208601612760565b601f01601f19169290920160200192915050565b60008251612486818460208701612760565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b03848116825283166020820152606060408201819052600090611c3490830184612448565b6001600160a01b03848116825283166020820152608060408201819052601290820152714175746f6d6174696341617665526570617960701b60a082015260c060608201819052600090611c3490830184612448565b6001600160a01b0384811682528316602082015260806040820181905260129082015271105d5d1bdb585d1a58d0585d99509bdbdcdd60721b60a082015260c060608201819052600090611c3490830184612448565b6001600160a01b03929092168252602082015260400190565b9115158252602082015260400190565b600060208252610e646020830184612448565b6020808252601d908201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604082015260600190565b6020808252600c908201526b139bdd08185d5d1a08189bdd60a21b604082015260600190565b6020808252602a908201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6040820152691bdd081cdd58d8d9595960b21b606082015260800190565b60006040825261268d60408301855161243b565b602084015161269f606084018261243b565b5060408401516080830152606084015160a0830152608084015160c083015260a08401516126d060e084018261243b565b5060c08401516101006126e58185018361243b565b60e0860151610120858101529150612701610160850183612448565b95015161014084015250506020015290565b61ffff91909116815260200190565b90815260200190565b918252602082015260400190565b60405181810167ffffffffffffffff8111828210171561275857600080fd5b604052919050565b60005b8381101561277b578181015183820152602001612763565b8381111561278a576000848401525b50505050565b6001600160a01b0381168114611ced57600080fd5b8015158114611ced57600080fdfea2646970667358221220111419d1fa3552b2268f282c63c0ca0838148e71ec081287d5f76caa26e108a364736f6c63430006060033
{"success": true, "error": null, "results": {"detectors": [{"check": "tx-origin", "impact": "Medium", "confidence": "Medium"}, {"check": "name-reused", "impact": "High", "confidence": "High"}, {"check": "erc20-interface", "impact": "Medium", "confidence": "High"}, {"check": "arbitrary-send", "impact": "High", "confidence": "Medium"}, {"check": "unchecked-lowlevel", "impact": "Medium", "confidence": "Medium"}, {"check": "incorrect-equality", "impact": "Medium", "confidence": "High"}, {"check": "uninitialized-local", "impact": "Medium", "confidence": "Medium"}, {"check": "unchecked-transfer", "impact": "High", "confidence": "Medium"}, {"check": "unused-return", "impact": "Medium", "confidence": "Medium"}, {"check": "locked-ether", "impact": "Medium", "confidence": "High"}]}}
true
null
{'detectors': [{'check': 'tx-origin', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'name-reused', 'impact': 'High', 'confidence': 'High'}, {'check': 'erc20-interface', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'arbitrary-send', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unchecked-lowlevel', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'incorrect-equality', 'impact': 'Medium', 'confidence': 'High'}, {'check': 'uninitialized-local', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'unchecked-transfer', 'impact': 'High', 'confidence': 'Medium'}, {'check': 'unused-return', 'impact': 'Medium', 'confidence': 'Medium'}, {'check': 'locked-ether', 'impact': 'Medium', 'confidence': 'High'}]}