diff --git a/.gitignore b/.gitignore index 38ea2e7e1..0310e1e2a 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,4 @@ node_modules # Don't track NPM lockfile (we use Yarn) package-lock.json +packages/liquidator/secret.json diff --git a/packages/contracts/contracts/B.Protocol/Admin.sol b/packages/contracts/contracts/B.Protocol/Admin.sol new file mode 100644 index 000000000..ff03a5e07 --- /dev/null +++ b/packages/contracts/contracts/B.Protocol/Admin.sol @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.6.11; + +import "./../Dependencies/Ownable.sol"; + +interface WithAdmin { + function admin() external view returns(address); +} + +interface BAMMLikeInterface { + function setParams(uint _A, uint _fee, uint _callerFee) external; + function transferOwnership(address _newOwner) external; +} + +contract Admin is Ownable { + WithAdmin public immutable comptroller; + BAMMLikeInterface public immutable bamm; + + address public pendingOwner; + uint public ttl; + + event PendingOwnerAlert(address newOwner); + + constructor(WithAdmin _comptroller, BAMMLikeInterface _bamm) public { + comptroller = _comptroller; + bamm = _bamm; + } + + function setParams(uint _A, uint _fee, uint _callerFee) public onlyOwner { + bamm.setParams(_A, _fee, _callerFee); + } + + function setBAMMPendingOwnership(address newOwner) public { + require(msg.sender == comptroller.admin(), "only market admin can change ownership"); + pendingOwner = newOwner; + ttl = now + 14 days; + + emit PendingOwnerAlert(newOwner); + } + + function transferBAMMOwnership() public onlyOwner { + require(pendingOwner != address(0), "pending owner is 0"); + require(now >= ttl, "too early"); + + bamm.transferOwnership(pendingOwner); + + pendingOwner = address(0); + } +} \ No newline at end of file diff --git a/packages/contracts/contracts/B.Protocol/BAMM.sol b/packages/contracts/contracts/B.Protocol/BAMM.sol index ee6ee65b6..fd47e4f7e 100644 --- a/packages/contracts/contracts/B.Protocol/BAMM.sol +++ b/packages/contracts/contracts/B.Protocol/BAMM.sol @@ -2,73 +2,120 @@ pragma solidity 0.6.11; -import "./../StabilityPool.sol"; -import "./CropJoinAdapter.sol"; +import "./TokenAdapter.sol"; import "./PriceFormula.sol"; import "./../Interfaces/IPriceFeed.sol"; -import "./../Dependencies/IERC20.sol"; import "./../Dependencies/SafeMath.sol"; import "./../Dependencies/Ownable.sol"; import "./../Dependencies/AggregatorV3Interface.sol"; +import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; +import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; +import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; -contract BAMM is CropJoinAdapter, PriceFormula, Ownable { +interface ICToken { + function redeem(uint redeemTokens) external returns (uint); + function balanceOf(address a) external view returns (uint); + function liquidateBorrow(address borrower, uint amount, address collateral) external returns (uint); + function underlying() external view returns(IERC20); +} + +contract BAMM is TokenAdapter, PriceFormula, Ownable, ReentrancyGuard { using SafeMath for uint256; + using SafeERC20 for IERC20; - AggregatorV3Interface public immutable priceAggregator; IERC20 public immutable LUSD; - StabilityPool immutable public SP; + uint public immutable lusdDecimals; + IERC20[] public collaterals; // IMPORTANT - collateral != LUSD + mapping(address => AggregatorV3Interface) public priceAggregators; + mapping(address => uint) public collateralDecimals; + mapping(address => bool) public cTokens; + ICToken public immutable cBorrow; address payable public immutable feePool; uint public constant MAX_FEE = 100; // 1% + uint public constant MAX_CALLER_FEE = 100; // 1% uint public fee = 0; // fee in bps + uint public callerFee = 0; // fee in bps uint public A = 20; uint public constant MIN_A = 20; uint public constant MAX_A = 200; uint public immutable maxDiscount; // max discount in bips - address public immutable frontEndTag; - uint constant public PRECISION = 1e18; - event ParamsSet(uint A, uint fee); + event ParamsSet(uint A, uint fee, uint callerFee); event UserDeposit(address indexed user, uint lusdAmount, uint numShares); - event UserWithdraw(address indexed user, uint lusdAmount, uint ethAmount, uint numShares); - event RebalanceSwap(address indexed user, uint lusdAmount, uint ethAmount, uint timestamp); + event UserWithdraw(address indexed user, uint lusdAmount, uint numShares); + event RebalanceSwap(address indexed user, uint lusdAmount, IERC20 token, uint tokenAmount, uint timestamp); constructor( - address _priceAggregator, - address payable _SP, address _LUSD, - address _LQTY, + address _cBorrow, uint _maxDiscount, - address payable _feePool, - address _fronEndTag) + address payable _feePool) public - CropJoinAdapter(_LQTY) { - priceAggregator = AggregatorV3Interface(_priceAggregator); LUSD = IERC20(_LUSD); - SP = StabilityPool(_SP); + lusdDecimals = ERC20(_LUSD).decimals(); + cBorrow = ICToken(_cBorrow); feePool = _feePool; maxDiscount = _maxDiscount; - frontEndTag = _fronEndTag; + + IERC20(_LUSD).safeApprove(address(_cBorrow), uint(-1)); + + require(ERC20(_LUSD).decimals() <= 18, "unsupported decimals"); } - function setParams(uint _A, uint _fee) external onlyOwner { + function setParams(uint _A, uint _fee, uint _callerFee) external onlyOwner { require(_fee <= MAX_FEE, "setParams: fee is too big"); + require(_callerFee <= MAX_CALLER_FEE, "setParams: caller fee is too big"); require(_A >= MIN_A, "setParams: A too small"); require(_A <= MAX_A, "setParams: A too big"); fee = _fee; + callerFee = _callerFee; A = _A; - emit ParamsSet(_A, _fee); + emit ParamsSet(_A, _fee, _callerFee); + } + + function addCollateral(ICToken ctoken, AggregatorV3Interface feed) external onlyOwner { + IERC20 token = ctoken.underlying(); + + // validations + require(token != LUSD, "addCollateral: LUSD cannot be collateral"); + require(feed != AggregatorV3Interface(0x0), "addCollateral: invalid feed"); + require(! cTokens[address(ctoken)], "addCollateral: collateral listed"); + require(priceAggregators[address(token)] == AggregatorV3Interface(0x0), "addCollateral: underlying already added"); + + // add the token + collaterals.push(token); + priceAggregators[address(token)] = feed; + collateralDecimals[address(token)] = ERC20(address(token)).decimals(); + cTokens[address(ctoken)] = true; } - function fetchPrice() public view returns(uint) { + function removeCollateral(ICToken ctoken) external onlyOwner { + IERC20 token = ctoken.underlying(); + + for(uint i = 0 ; i < collaterals.length ; i++) { + if(collaterals[i] == token) { + collaterals[i] = collaterals[collaterals.length - 1]; + collaterals.pop(); + priceAggregators[address(token)] = AggregatorV3Interface(0x0); + cTokens[address(ctoken)] = false; + break; + } + } + } + + function fetchPrice(IERC20 token) public view returns(uint) { + AggregatorV3Interface priceAggregator = priceAggregators[address(token)]; + if(priceAggregator == AggregatorV3Interface(address(0x0))) return 0; + uint chainlinkDecimals; uint chainlinkLatestAnswer; uint chainlinkTimestamp; @@ -102,30 +149,53 @@ contract BAMM is CropJoinAdapter, PriceFormula, Ownable { if(chainlinkTimestamp + 1 hours < now) return 0; // price is down - uint chainlinkFactor = 10 ** chainlinkDecimals; - return chainlinkLatestAnswer.mul(PRECISION) / chainlinkFactor; + int chainlinkDecimalFactor = int(chainlinkDecimals + collateralDecimals[address(token)]) - int(lusdDecimals); + if(chainlinkDecimalFactor >= 0) { + return chainlinkLatestAnswer.mul(PRECISION) / (10 ** uint(chainlinkDecimalFactor)); + } + else { + return chainlinkLatestAnswer.mul(PRECISION) * (10 ** uint(-1 * chainlinkDecimalFactor)); + } + } + + function getCollateralValue() public view returns(bool succ, uint value) { + value = 0; + succ = true; + + for(uint i = 0 ; i < collaterals.length ; i++) { + IERC20 token = collaterals[i]; + uint bal = token.balanceOf(address(this)); + if(bal > 0) { + uint price = fetchPrice(token); + if(price == 0) { + succ = false; + break; + } + + value = value.add(bal.mul(price) / PRECISION); + } + } } - function deposit(uint lusdAmount) external { + + function deposit(uint lusdAmount) external nonReentrant { // update share - uint lusdValue = SP.getCompoundedLUSDDeposit(address(this)); - uint ethValue = SP.getDepositorETHGain(address(this)).add(address(this).balance); + uint lusdValue = LUSD.balanceOf(address(this)); + (bool succ, uint colValue) = getCollateralValue(); - uint price = fetchPrice(); - require(ethValue == 0 || price > 0, "deposit: chainlink is down"); + require(succ, "deposit: chainlink is down"); - uint totalValue = lusdValue.add(ethValue.mul(price) / PRECISION); + uint totalValue = lusdValue.add(colValue); // this is in theory not reachable. if it is, better halt deposits - // the condition is equivalent to: (totalValue = 0) ==> (total = 0) - require(totalValue > 0 || total == 0, "deposit: system is rekt"); + // the condition is equivalent to: (totalValue = 0) ==> (totalSupply = 0) + require(totalValue > 0 || totalSupply == 0, "deposit: system is rekt"); uint newShare = PRECISION; - if(total > 0) newShare = total.mul(lusdAmount) / totalValue; + if(totalSupply > 0) newShare = totalSupply.mul(lusdAmount) / totalValue; // deposit - require(LUSD.transferFrom(msg.sender, address(this), lusdAmount), "deposit: transferFrom failed"); - SP.provideToSP(lusdAmount, frontEndTag); + LUSD.safeTransferFrom(msg.sender, address(this), lusdAmount); // update LP token mint(msg.sender, newShare); @@ -133,27 +203,30 @@ contract BAMM is CropJoinAdapter, PriceFormula, Ownable { emit UserDeposit(msg.sender, lusdAmount, newShare); } - function withdraw(uint numShares) external { - uint lusdValue = SP.getCompoundedLUSDDeposit(address(this)); - uint ethValue = SP.getDepositorETHGain(address(this)).add(address(this).balance); + function withdraw(uint numShares) external nonReentrant { + uint supplyBefore = totalSupply; // this is to save gas - uint lusdAmount = lusdValue.mul(numShares).div(total); - uint ethAmount = ethValue.mul(numShares).div(total); + uint lusdBal = LUSD.balanceOf(address(this)); + uint lusdAmount = lusdBal.mul(numShares).div(supplyBefore); - // this withdraws lusd, lqty, and eth - SP.withdrawFromSP(lusdAmount); + uint[] memory collateralAmounts = new uint[](collaterals.length); + IERC20[] memory collateralTypes = collaterals; + + for(uint i = 0 ; i < collateralTypes.length ; i++) { + uint bal = collateralTypes[i].balanceOf(address(this)); + collateralAmounts[i] = bal.mul(numShares).div(supplyBefore); + } // update LP token burn(msg.sender, numShares); - // send lusd and eth - if(lusdAmount > 0) LUSD.transfer(msg.sender, lusdAmount); - if(ethAmount > 0) { - (bool success, ) = msg.sender.call{ value: ethAmount }(""); // re-entry is fine here - require(success, "withdraw: sending ETH failed"); + // send lusd and collateral leftovers + if(lusdAmount > 0) LUSD.safeTransfer(msg.sender, lusdAmount); + for(uint i = 0 ; i < collateralTypes.length ; i++) { + if(collateralAmounts[i] > 0 ) collateralTypes[i].safeTransfer(msg.sender, collateralAmounts[i]); } - emit UserWithdraw(msg.sender, lusdAmount, ethAmount, numShares); + emit UserWithdraw(msg.sender, lusdAmount, numShares); } function addBps(uint n, int bps) internal pure returns(uint) { @@ -163,69 +236,84 @@ contract BAMM is CropJoinAdapter, PriceFormula, Ownable { return n.mul(uint(10000 + bps)) / 10000; } - function getSwapEthAmount(uint lusdQty) public view returns(uint ethAmount, uint feeEthAmount) { - uint lusdBalance = SP.getCompoundedLUSDDeposit(address(this)); - uint ethBalance = SP.getDepositorETHGain(address(this)).add(address(this).balance); + function getSwapAmount(uint lusdQty, IERC20 token) public view returns(uint tokenAmount) { + uint lusdBalance = LUSD.balanceOf(address(this)); + uint tokenBalance = token.balanceOf(address(this)); + + (bool succ, uint collateralValue) = getCollateralValue(); + if(! succ) return 0; // chainlink is down - uint eth2usdPrice = fetchPrice(); - if(eth2usdPrice == 0) return (0, 0); // chainlink is down + uint token2usdPrice = fetchPrice(token); + if(token2usdPrice == 0) return 0; // chainlink is down - uint ethUsdValue = ethBalance.mul(eth2usdPrice) / PRECISION; - uint maxReturn = addBps(lusdQty.mul(PRECISION) / eth2usdPrice, int(maxDiscount)); + uint maxReturn = addBps(lusdQty.mul(PRECISION) / token2usdPrice, int(maxDiscount)); uint xQty = lusdQty; uint xBalance = lusdBalance; - uint yBalance = lusdBalance.add(ethUsdValue.mul(2)); + uint yBalance = lusdBalance.add(collateralValue.mul(2)); uint usdReturn = getReturn(xQty, xBalance, yBalance, A); - uint basicEthReturn = usdReturn.mul(PRECISION) / eth2usdPrice; + uint basicTokenReturn = usdReturn.mul(PRECISION) / token2usdPrice; - if(ethBalance < basicEthReturn) basicEthReturn = ethBalance; // cannot give more than balance - if(maxReturn < basicEthReturn) basicEthReturn = maxReturn; + if(tokenBalance < basicTokenReturn) basicTokenReturn = tokenBalance; // cannot give more than balance + if(maxReturn < basicTokenReturn) basicTokenReturn = maxReturn; - ethAmount = addBps(basicEthReturn, -int(fee)); - feeEthAmount = basicEthReturn.sub(ethAmount); + tokenAmount = basicTokenReturn; } - // get ETH in return to LUSD - function swap(uint lusdAmount, uint minEthReturn, address payable dest) public returns(uint) { - (uint ethAmount, uint feeAmount) = getSwapEthAmount(lusdAmount); + // get token in return to LUSD + function swap(uint lusdAmount, IERC20 returnToken, uint minReturn, address payable dest) public nonReentrant returns(uint) { + require(returnToken != LUSD, "swap: unsupported"); - require(ethAmount >= minEthReturn, "swap: low return"); + uint returnAmount = getSwapAmount(lusdAmount, returnToken); - LUSD.transferFrom(msg.sender, address(this), lusdAmount); - SP.provideToSP(lusdAmount, frontEndTag); + require(returnAmount >= minReturn, "swap: low return"); - if(feeAmount > 0) feePool.transfer(feeAmount); - (bool success, ) = dest.call{ value: ethAmount }(""); // re-entry is fine here - require(success, "swap: sending ETH failed"); + LUSD.safeTransferFrom(msg.sender, address(this), lusdAmount); - emit RebalanceSwap(msg.sender, lusdAmount, ethAmount, now); + uint feeAmount = addBps(lusdAmount, int(fee)).sub(lusdAmount); + if(feeAmount > 0) LUSD.safeTransfer(feePool, feeAmount); - return ethAmount; - } + returnToken.safeTransfer(dest, returnAmount); - // kyber network reserve compatible function - function trade( - IERC20 /* srcToken */, - uint256 srcAmount, - IERC20 /* destToken */, - address payable destAddress, - uint256 /* conversionRate */, - bool /* validate */ - ) external payable returns (bool) { - return swap(srcAmount, 0, destAddress) > 0; - } + emit RebalanceSwap(msg.sender, lusdAmount, returnToken, returnAmount, now); - function getConversionRate( - IERC20 /* src */, - IERC20 /* dest */, - uint256 srcQty, - uint256 /* blockNumber */ - ) external view returns (uint256) { - (uint ethQty, ) = getSwapEthAmount(srcQty); - return ethQty.mul(PRECISION) / srcQty; + return returnAmount; } receive() external payable {} + + function canLiquidate( + ICToken cTokenBorrowed, + ICToken cTokenCollateral, + uint repayAmount + ) + external + view + returns(bool) + { + if(cTokenBorrowed != cBorrow) return false; + if((! cTokens[address(cTokenCollateral)]) && (cTokenCollateral != cTokenBorrowed)) return false; + + return repayAmount <= LUSD.balanceOf(address(this)); + } + + // callable by anyone + function liquidateBorrow(address borrower, uint amount, ICToken collateral) external nonReentrant returns (uint) { + require(cTokens[address(collateral)] || collateral == cBorrow, "liquidateBorrow: invalid collateral"); + + IERC20 colToken = IERC20(collateral.underlying()); + + uint tokenBalBefore = colToken.balanceOf(address(this)); + require(cBorrow.liquidateBorrow(borrower, amount, address(collateral)) == 0, "liquidateBorrow: liquidation failed"); + require(collateral.redeem(collateral.balanceOf(address(this))) == 0, "liquidateBorrow: collateral redeem failed"); + uint tokenBalAfter = colToken.balanceOf(address(this)); + + uint deltaToken = tokenBalAfter.sub(tokenBalBefore); + if(collateral == cBorrow) deltaToken = amount; + + uint feeAmount = addBps(deltaToken, int(callerFee)).sub(deltaToken); + if(feeAmount > 0 ) colToken.safeTransfer(msg.sender, feeAmount); + } } + diff --git a/packages/contracts/contracts/B.Protocol/BLens.sol b/packages/contracts/contracts/B.Protocol/BLens.sol index c7468a046..4f2c1f6b4 100644 --- a/packages/contracts/contracts/B.Protocol/BLens.sol +++ b/packages/contracts/contracts/B.Protocol/BLens.sol @@ -40,25 +40,7 @@ contract BLens { z = mul(x, RAY) / y; } - function getUnclaimedLqty(address user, BAMM bamm, ERC20 token) public returns(uint) { - // trigger bamm (p)lqty claim - bamm.withdraw(0); - - if(bamm.total() == 0) return 0; - - // duplicate harvest logic - uint crop = sub(token.balanceOf(address(bamm)), bamm.stock()); - uint share = add(bamm.share(), rdiv(crop, bamm.total())); - - uint last = bamm.crops(user); - uint curr = rmul(bamm.stake(user), share); - if(curr > last) return curr - last; - return 0; - } - struct UserInfo { - uint unclaimedLqty; - uint bammUserBalance; uint bammTotalSupply; @@ -69,14 +51,12 @@ contract BLens { uint ethTotal; } - function getUserInfo(address user, BAMM bamm, ERC20 lqty) external returns(UserInfo memory info) { - info.unclaimedLqty = getUnclaimedLqty(user, bamm, lqty); + function getUserInfo(address user, BAMM bamm) external view returns(UserInfo memory info) { info.bammUserBalance = bamm.balanceOf(user); info.bammTotalSupply = bamm.totalSupply(); - StabilityPool sp = bamm.SP(); - info.lusdTotal = sp.getCompoundedLUSDDeposit(address(bamm)); - info.ethTotal = sp.getDepositorETHGain(address(bamm)) + address(bamm).balance; + info.lusdTotal = bamm.LUSD().balanceOf(address(bamm)); + info.ethTotal = address(bamm).balance; info.lusdUserBalance = info.lusdTotal * info.bammUserBalance / info.bammTotalSupply; info.ethUserBalance = info.ethTotal * info.bammUserBalance / info.bammTotalSupply; diff --git a/packages/contracts/contracts/B.Protocol/ChainlinkTestnet.sol b/packages/contracts/contracts/B.Protocol/ChainlinkTestnet.sol index c956fe1f3..d19a65ef7 100644 --- a/packages/contracts/contracts/B.Protocol/ChainlinkTestnet.sol +++ b/packages/contracts/contracts/B.Protocol/ChainlinkTestnet.sol @@ -10,15 +10,16 @@ import "./../TestContracts/PriceFeedTestnet.sol"; */ contract ChainlinkTestnet { - PriceFeedTestnet feed; + uint price; uint time = 0; + uint public decimals = 18; - constructor(PriceFeedTestnet _feed) public { - feed = _feed; + function setPrice(uint _price) external { + price = _price; } - function decimals() external pure returns(uint) { - return 18; + function setDecimals(uint _decimals) external { + decimals = _decimals; } function setTimestamp(uint _time) external { @@ -34,8 +35,160 @@ contract ChainlinkTestnet { uint80 /* answeredInRound */ ) { - answer = int(feed.getPrice()); + answer = int(price); if(time == 0 ) timestamp = now; else timestamp = time; } } + +contract FakePriceOracle { + address cETH; + address realOracle; + uint cETHPrice; + + constructor(address _cETH, address _realOracle) public { + cETH = _cETH; + realOracle = _realOracle; + } + + function setCETHPrice(uint _price) public { + cETHPrice = _price; + } + + function getUnderlyingPrice(address ctoken) public returns(uint) { + if(ctoken == cETH) return cETHPrice; + return FakePriceOracle(realOracle).getUnderlyingPrice(ctoken); + } +} + +/** + *Submitted for verification at Etherscan.io on 2021-04-24 +*/ + +/** + *Submitted for verification at Etherscan.io on 2021-04-24 +*/ + +// File: @openzeppelin/contracts/GSN/Context.sol + + +/* + * @dev Provides information about the current execution context, including the + * sender of the transaction and its data. While these are generally available + * via msg.sender and msg.data, they should not be accessed in such a direct + * manner, since when dealing with GSN meta-transactions the account sending and + * paying for execution may not be the actual sender (as far as an application + * is concerned). + * + * This contract is only required for intermediate, library-like contracts. + */ +contract Context { + // Empty internal constructor, to prevent people from mistakenly deploying + // an instance of this contract, which should be used via inheritance. + constructor () internal { } + // solhint-disable-previous-line no-empty-blocks + + function _msgSender() internal view returns (address payable) { + return msg.sender; + } + + function _msgData() internal view returns (bytes memory) { + this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 + return msg.data; + } +} + +// File: @openzeppelin/contracts/ownership/Ownable.sol + + + +/** + * @dev Contract module which provides a basic access control mechanism, where + * there is an account (an owner) that can be granted exclusive access to + * specific functions. + * + * This module is used through inheritance. It will make available the modifier + * `onlyOwner`, which can be applied to your functions to restrict their use to + * the owner. + */ +contract Ownable is 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; + } +} + +// File: contracts/Vault.sol + + + +// initially deployer owns it, and then it moves it to the DAO +contract Vault is Ownable { + constructor(address owner) public { + transferOwnership(owner); + } + + function op(address payable target, bytes calldata data, uint value) onlyOwner external payable { + target.call.value(value)(data); + } + receive() payable external {} +} \ No newline at end of file diff --git a/packages/contracts/contracts/B.Protocol/Comptroller.sol b/packages/contracts/contracts/B.Protocol/Comptroller.sol new file mode 100644 index 000000000..128c50efd --- /dev/null +++ b/packages/contracts/contracts/B.Protocol/Comptroller.sol @@ -0,0 +1,4357 @@ +// Sources flattened with hardhat v2.6.4 https://hardhat.org + +// File contracts/ComptrollerInterface.sol + +pragma solidity ^0.5.16; + +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); +} + + +// File contracts/InterestRateModel.sol + +pragma solidity ^0.5.16; + +/** + * @title Compound's InterestRateModel Interface + * @author Compound + */ +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 amount 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 amount 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); + +} + + +// File contracts/EIP20NonStandardInterface.sol + +pragma solidity ^0.5.16; + +/** + * @title EIP20NonStandardInterface + * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` + * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca + */ +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); +} + + +// File contracts/CTokenInterfaces.sol + +pragma solidity ^0.5.16; + + + +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); + function sweepToken(EIP20NonStandardInterface token) external; + + + /*** 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; +} + + +// File contracts/ErrorReporter.sol + +pragma solidity ^0.5.16; + +contract ComptrollerErrorReporter { + enum Error { + NO_ERROR, + UNAUTHORIZED, + COMPTROLLER_MISMATCH, + INSUFFICIENT_SHORTFALL, + INSUFFICIENT_LIQUIDITY, + INVALID_CLOSE_FACTOR, + INVALID_COLLATERAL_FACTOR, + INVALID_LIQUIDATION_INCENTIVE, + MARKET_NOT_ENTERED, // no longer possible + MARKET_NOT_LISTED, + MARKET_ALREADY_LISTED, + MATH_ERROR, + NONZERO_BORROW_BALANCE, + PRICE_ERROR, + REJECTION, + SNAPSHOT_ERROR, + TOO_MANY_ASSETS, + TOO_MUCH_REPAY + } + + enum FailureInfo { + ACCEPT_ADMIN_PENDING_ADMIN_CHECK, + ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, + EXIT_MARKET_BALANCE_OWED, + EXIT_MARKET_REJECTION, + SET_CLOSE_FACTOR_OWNER_CHECK, + SET_CLOSE_FACTOR_VALIDATION, + SET_COLLATERAL_FACTOR_OWNER_CHECK, + SET_COLLATERAL_FACTOR_NO_EXISTS, + SET_COLLATERAL_FACTOR_VALIDATION, + SET_COLLATERAL_FACTOR_WITHOUT_PRICE, + SET_IMPLEMENTATION_OWNER_CHECK, + SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, + SET_LIQUIDATION_INCENTIVE_VALIDATION, + SET_MAX_ASSETS_OWNER_CHECK, + SET_PENDING_ADMIN_OWNER_CHECK, + SET_PENDING_IMPLEMENTATION_OWNER_CHECK, + SET_PRICE_ORACLE_OWNER_CHECK, + SUPPORT_MARKET_EXISTS, + SUPPORT_MARKET_OWNER_CHECK, + SET_PAUSE_GUARDIAN_OWNER_CHECK + } + + /** + * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary + * contract-specific code that enables us to report opaque error codes from upgradeable contracts. + **/ + event Failure(uint error, uint info, uint detail); + + /** + * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator + */ + function fail(Error err, FailureInfo info) internal returns (uint) { + emit Failure(uint(err), uint(info), 0); + + return uint(err); + } + + /** + * @dev use this when reporting an opaque error from an upgradeable collaborator contract + */ + function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { + emit Failure(uint(err), uint(info), opaqueError); + + return uint(err); + } +} + +contract TokenErrorReporter { + enum Error { + NO_ERROR, + UNAUTHORIZED, + BAD_INPUT, + COMPTROLLER_REJECTION, + COMPTROLLER_CALCULATION_ERROR, + INTEREST_RATE_MODEL_ERROR, + INVALID_ACCOUNT_PAIR, + INVALID_CLOSE_AMOUNT_REQUESTED, + INVALID_COLLATERAL_FACTOR, + MATH_ERROR, + MARKET_NOT_FRESH, + MARKET_NOT_LISTED, + TOKEN_INSUFFICIENT_ALLOWANCE, + TOKEN_INSUFFICIENT_BALANCE, + TOKEN_INSUFFICIENT_CASH, + TOKEN_TRANSFER_IN_FAILED, + TOKEN_TRANSFER_OUT_FAILED + } + + /* + * Note: FailureInfo (but not Error) is kept in alphabetical order + * This is because FailureInfo grows significantly faster, and + * the order of Error has some meaning, while the order of FailureInfo + * is entirely arbitrary. + */ + enum FailureInfo { + ACCEPT_ADMIN_PENDING_ADMIN_CHECK, + ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, + ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, + ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, + ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, + ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, + ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, + BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, + BORROW_ACCRUE_INTEREST_FAILED, + BORROW_CASH_NOT_AVAILABLE, + BORROW_FRESHNESS_CHECK, + BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, + BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, + BORROW_MARKET_NOT_LISTED, + BORROW_COMPTROLLER_REJECTION, + LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, + LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, + LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, + LIQUIDATE_COMPTROLLER_REJECTION, + LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, + LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, + LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, + LIQUIDATE_FRESHNESS_CHECK, + LIQUIDATE_LIQUIDATOR_IS_BORROWER, + LIQUIDATE_REPAY_BORROW_FRESH_FAILED, + LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, + LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, + LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, + LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, + LIQUIDATE_SEIZE_TOO_MUCH, + MINT_ACCRUE_INTEREST_FAILED, + MINT_COMPTROLLER_REJECTION, + MINT_EXCHANGE_CALCULATION_FAILED, + MINT_EXCHANGE_RATE_READ_FAILED, + MINT_FRESHNESS_CHECK, + MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, + MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, + MINT_TRANSFER_IN_FAILED, + MINT_TRANSFER_IN_NOT_POSSIBLE, + REDEEM_ACCRUE_INTEREST_FAILED, + REDEEM_COMPTROLLER_REJECTION, + REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, + REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, + REDEEM_EXCHANGE_RATE_READ_FAILED, + REDEEM_FRESHNESS_CHECK, + REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, + REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, + REDEEM_TRANSFER_OUT_NOT_POSSIBLE, + REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, + REDUCE_RESERVES_ADMIN_CHECK, + REDUCE_RESERVES_CASH_NOT_AVAILABLE, + REDUCE_RESERVES_FRESH_CHECK, + REDUCE_RESERVES_VALIDATION, + REPAY_BEHALF_ACCRUE_INTEREST_FAILED, + REPAY_BORROW_ACCRUE_INTEREST_FAILED, + REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, + REPAY_BORROW_COMPTROLLER_REJECTION, + REPAY_BORROW_FRESHNESS_CHECK, + REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, + REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, + REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, + SET_COLLATERAL_FACTOR_OWNER_CHECK, + SET_COLLATERAL_FACTOR_VALIDATION, + SET_COMPTROLLER_OWNER_CHECK, + SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, + SET_INTEREST_RATE_MODEL_FRESH_CHECK, + SET_INTEREST_RATE_MODEL_OWNER_CHECK, + SET_MAX_ASSETS_OWNER_CHECK, + SET_ORACLE_MARKET_NOT_LISTED, + SET_PENDING_ADMIN_OWNER_CHECK, + SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, + SET_RESERVE_FACTOR_ADMIN_CHECK, + SET_RESERVE_FACTOR_FRESH_CHECK, + SET_RESERVE_FACTOR_BOUNDS_CHECK, + TRANSFER_COMPTROLLER_REJECTION, + TRANSFER_NOT_ALLOWED, + TRANSFER_NOT_ENOUGH, + TRANSFER_TOO_MUCH, + ADD_RESERVES_ACCRUE_INTEREST_FAILED, + ADD_RESERVES_FRESH_CHECK, + ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE + } + + /** + * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary + * contract-specific code that enables us to report opaque error codes from upgradeable contracts. + **/ + event Failure(uint error, uint info, uint detail); + + /** + * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator + */ + function fail(Error err, FailureInfo info) internal returns (uint) { + emit Failure(uint(err), uint(info), 0); + + return uint(err); + } + + /** + * @dev use this when reporting an opaque error from an upgradeable collaborator contract + */ + function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { + emit Failure(uint(err), uint(info), opaqueError); + + return uint(err); + } +} + + +// File contracts/CarefulMath.sol + +pragma solidity ^0.5.16; + +/** + * @title Careful Math + * @author Compound + * @notice Derived from OpenZeppelin's SafeMath library + * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol + */ +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); + } +} + + +// File contracts/ExponentialNoError.sol + +pragma solidity ^0.5.16; + +/** + * @title Exponential module for storing fixed-precision decimals + * @author Compound + * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. + * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: + * `Exp({mantissa: 5100000000000000000})`. + */ +contract ExponentialNoError { + 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 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 Multiply an Exp by a scalar, then truncate to return an unsigned integer. + */ + function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { + Exp memory product = mul_(a, scalar); + return truncate(product); + } + + /** + * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. + */ + function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { + Exp memory product = mul_(a, scalar); + return add_(truncate(product), addend); + } + + /** + * @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)}); + } +} + + +// File contracts/Exponential.sol + +pragma solidity ^0.5.16; + + +/** + * @title Exponential module for storing fixed-precision decimals + * @author Compound + * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError + * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. + * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: + * `Exp({mantissa: 5100000000000000000})`. + */ +contract Exponential is CarefulMath, ExponentialNoError { + /** + * @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); + } +} + + +// File contracts/EIP20Interface.sol + +pragma solidity ^0.5.16; + +/** + * @title ERC 20 Token Standard Interface + * https://eips.ethereum.org/EIPS/eip-20 + */ +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); +} + + +// File contracts/CToken.sol + +pragma solidity ^0.5.16; + + + + + + +/** + * @title Compound's CToken Contract + * @notice Abstract base for CTokens + * @author Compound + */ +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); + + // unused function + // 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 */ + // unused function + // 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 */ + // unused function + // 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 */ + // unused function + // 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 */ + // unused function + // 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 */ + // unused function + // 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 + } +} + + +// File contracts/PriceOracle.sol + +pragma solidity ^0.5.16; + +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 cToken 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 cToken) external view returns (uint); +} + + +// File contracts/IBProtocol.sol + +pragma solidity ^0.5.16; + +interface IBProtocol { + function canLiquidate( + address cTokenBorrowed, + address cTokenCollateral, + uint repayAmount + ) + external + view + returns(bool); +} + + +// File contracts/ComptrollerStorage.sol + +pragma solidity ^0.5.16; + + + +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 implementation; + + /** + * @notice Pending brains of Unitroller + */ + address public pendingImplementation; +} + +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 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; +} + +contract ComptrollerV4Storage is ComptrollerV3Storage { + // @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. + address public borrowCapGuardian; + + // @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. + mapping(address => uint) public borrowCaps; +} + +contract ComptrollerV5Storage is ComptrollerV4Storage { + /// @notice The portion of COMP that each contributor receives per block + mapping(address => uint) public compContributorSpeeds; + + /// @notice Last block at which a contributor's COMP rewards have been allocated + mapping(address => uint) public lastContributorBlock; +} + +contract ComptrollerV6Storage is ComptrollerV5Storage { + /// @notice CToken => IBProtocol (per CToken debt) + mapping(address => address) public bprotocol; +} + + +// File contracts/Unitroller.sol + +pragma solidity ^0.5.16; + + +/** + * @title ComptrollerCore + * @dev Storage for the comptroller is at this address, while execution is delegated to the `implementation`. + * CTokens should reference this contract as their comptroller. + */ +contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { + + /** + * @notice Emitted when pendingImplementation is changed + */ + event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); + + /** + * @notice Emitted when pendingImplementation 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 Hundred Deployer + admin = 0x1001009911e3FE1d5B45FF8Efea7732C33a6C012; + } + + /*** 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 = pendingImplementation; + + pendingImplementation = newPendingImplementation; + + emit NewPendingImplementation(oldPendingImplementation, pendingImplementation); + + 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 != pendingImplementation || pendingImplementation == address(0)) { + return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); + } + + // Save current values for inclusion in log + address oldImplementation = implementation; + address oldPendingImplementation = pendingImplementation; + + implementation = pendingImplementation; + + pendingImplementation = address(0); + + emit NewImplementation(oldImplementation, implementation); + emit NewPendingImplementation(oldPendingImplementation, pendingImplementation); + + 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, ) = 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) } + } + } +} + + +// File contracts/Comptroller.sol + +pragma solidity ^0.5.16; + + + + + + +/** + * @dev Interface of the ERC20 standard as defined in the EIP. + */ +interface IERC20 { + function totalSupply() external view returns (uint256); + function decimals() external view returns (uint8); + function balanceOf(address account) external view returns (uint256); + function transfer(address recipient, uint256 amount) external returns (bool); + function allowance(address owner, address spender) external view returns (uint256); + function approve(address spender, uint256 amount) external returns (bool); + function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); + function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; + function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +/** + * @title Compound's Comptroller Contract + * @author Compound + */ +contract Comptroller is ComptrollerV6Storage, ComptrollerInterface, ComptrollerErrorReporter, ExponentialNoError { + /// @notice Emitted when an admin supports a market + event MarketListed(CToken cToken); + + /// @notice Emitted when an admin removes a market + event MarketRemoved(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 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 ActionPaused(CToken cToken, string action, bool pauseState); + + /// @notice Emitted when a new COMP speed is calculated for a market + event CompSpeedUpdated(CToken indexed cToken, uint newSpeed); + + /// @notice Emitted when a new COMP speed is set for a contributor + event ContributorCompSpeedUpdated(address indexed contributor, uint newSpeed); + + /// @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 Emitted when borrow cap for a cToken is changed + event NewBorrowCap(CToken indexed cToken, uint newBorrowCap); + + /// @notice Emitted when borrow cap guardian is changed + event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); + + /// @notice Emitted when COMP is granted by admin + event CompGranted(address recipient, uint amount); + + /// @notice Emitted when B.Protocol is changed + event NewBProtocol(address indexed cToken, address oldBProtocol, address newBProtocol); + + /// @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 + + constructor() public { + // Set admin to Hundred deployer + admin = 0x1001009911e3FE1d5B45FF8Efea7732C33a6C012; + } + + /*** 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; + } + + // 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); + + 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); + + 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); + } + + + uint borrowCap = borrowCaps[cToken]; + // Borrow cap of 0 corresponds to unlimited borrowing + if (borrowCap != 0) { + uint totalBorrows = CToken(cToken).totalBorrows(); + uint nextTotalBorrows = add_(totalBorrows, borrowAmount); + require(nextTotalBorrows < borrowCap, "market borrow cap reached"); + } + + (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 + // Disabled for borrowers + + 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 + // Disabled for borrowers + + 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) { + + 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); + uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); + if (repayAmount > maxClose) { + return uint(Error.TOO_MUCH_REPAY); + } + + /* Only B.Protocol can liquidate */ + address bLiquidator = bprotocol[address(cTokenBorrowed)]; + if(bLiquidator != address(0) && IBProtocol(bLiquidator).canLiquidate(cTokenBorrowed, cTokenCollateral, repayAmount)) { + require(liquidator == bLiquidator, "only B.Protocol can liquidate"); + } + + 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); + distributeSupplierComp(cTokenCollateral, liquidator); + + 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); + distributeSupplierComp(cToken, dst); + + 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; + + // 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) + vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); + + // sumCollateral += tokensToDenom * cTokenBalance + vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); + + // sumBorrowPlusEffects += oraclePrice * borrowBalance + vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); + + // Calculate effects of interacting with cTokenModify + if (asset == cTokenModify) { + // redeem effect + // sumBorrowPlusEffects += tokensToDenom * redeemTokens + vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); + + // borrow effect + // sumBorrowPlusEffects += oraclePrice * borrowAmount + vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); + } + } + + // 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; + + numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa})); + denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); + ratio = div_(numerator, denominator); + + seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); + + 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 + */ + function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { + // Check caller is admin + require(msg.sender == admin, "only admin can set close factor"); + + 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 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); + } + + // 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 + + // Note that isComped is not in active use anymore + markets[address(cToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0}); + + _addMarketInternal(address(cToken)); + + 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)); + } + + function _disableMarket(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 + + require(CToken(cToken).totalBorrowsCurrent() == 0, "market has borrows"); + + require(CToken(cToken).totalSupply() == 0, "market has supply"); + + _removeMarketInternal(address(cToken)); + + emit MarketRemoved(cToken); + + return uint(Error.NO_ERROR); + } + + function _removeMarketInternal(address cToken) internal { + for (uint i = 0; i < allMarkets.length; i ++) { + if (allMarkets[i] == CToken(cToken)) { + allMarkets[i] = allMarkets[allMarkets.length - 1]; + allMarkets.length--; + break; + } + } + delete markets[cToken]; + } + + /** + * @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. + * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. + * @param cTokens The addresses of the markets (tokens) to change the borrow caps for + * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. + */ + function _setMarketBorrowCaps(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external { + require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps"); + + uint numMarkets = cTokens.length; + uint numBorrowCaps = newBorrowCaps.length; + + require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); + + for(uint i = 0; i < numMarkets; i++) { + borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; + emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); + } + } + + /** + * @notice Admin function to change the Borrow Cap Guardian + * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian + */ + function _setBorrowCapGuardian(address newBorrowCapGuardian) external { + require(msg.sender == admin, "only admin can set borrow cap guardian"); + + // Save current value for inclusion in log + address oldBorrowCapGuardian = borrowCapGuardian; + + // Store borrowCapGuardian with value newBorrowCapGuardian + borrowCapGuardian = newBorrowCapGuardian; + + // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) + emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); + } + + /** + * @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 ActionPaused(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 ActionPaused(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 == implementation; + } + + /*** Comp Distribution ***/ + + /** + * @notice Set COMP speed for a single market + * @param cToken The market whose COMP speed to update + * @param compSpeed New COMP speed for market + */ + function setCompSpeedInternal(CToken cToken, uint compSpeed) internal { + uint currentCompSpeed = compSpeeds[address(cToken)]; + if (currentCompSpeed != 0) { + // note that COMP speed could be set to 0 to halt liquidity rewards for a market + updateCompSupplyIndex(address(cToken)); + } else if (compSpeed != 0) { + // Add the COMP market + Market storage market = markets[address(cToken)]; + require(market.isListed == true, "comp market is not listed"); + + if (compSupplyState[address(cToken)].index == 0 && compSupplyState[address(cToken)].block == 0) { + compSupplyState[address(cToken)] = CompMarketState({ + index: compInitialIndex, + block: safe32(getBlockNumber(), "block number exceeds 32 bits") + }); + } + + if (compBorrowState[address(cToken)].index == 0 && compBorrowState[address(cToken)].block == 0) { + compBorrowState[address(cToken)] = CompMarketState({ + index: compInitialIndex, + block: safe32(getBlockNumber(), "block number exceeds 32 bits") + }); + } + } + + if (currentCompSpeed != compSpeed) { + compSpeeds[address(cToken)] = compSpeed; + emit CompSpeedUpdated(cToken, compSpeed); + } + } + + /** + * @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 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) 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] = supplierAccrued; + emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa); + } + + /** + * @notice Calculate additional accrued COMP for a contributor since last accrual + * @param contributor The address to calculate contributor rewards for + */ + function updateContributorRewards(address contributor) public { + uint compSpeed = compContributorSpeeds[contributor]; + uint blockNumber = getBlockNumber(); + uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]); + if (deltaBlocks > 0 && compSpeed > 0) { + uint newAccrued = mul_(deltaBlocks, compSpeed); + uint contributorAccrued = add_(compAccrued[contributor], newAccrued); + + compAccrued[contributor] = contributorAccrued; + lastContributorBlock[contributor] = blockNumber; + } + } + + /** + * @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); + } + + /** + * @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 + */ + function claimComp(address[] memory holders, CToken[] memory cTokens) public { + for (uint i = 0; i < cTokens.length; i++) { + CToken cToken = cTokens[i]; + require(markets[address(cToken)].isListed, "market must be listed"); + updateCompSupplyIndex(address(cToken)); + for (uint j = 0; j < holders.length; j++) { + distributeSupplierComp(address(cToken), holders[j]); + compAccrued[holders[j]] = grantCompInternal(holders[j], compAccrued[holders[j]]); + } + } + } + + /** + * @notice Transfer COMP to the user + * @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 amount The amount of COMP to (possibly) transfer + * @return The amount of COMP which was NOT transferred to the user + */ + function grantCompInternal(address user, uint amount) internal returns (uint) { + IERC20 comp = IERC20(getCompAddress()); + uint compRemaining = comp.balanceOf(address(this)); + if (amount > 0 && amount <= compRemaining) { + comp.transfer(user, amount); + return 0; + } + return amount; + } + + /*** Comp Distribution Admin ***/ + + /** + * @notice Transfer COMP to the recipient + * @dev Note: If there is not enough COMP, we do not perform the transfer all. + * @param recipient The address of the recipient to transfer COMP to + * @param amount The amount of COMP to (possibly) transfer + */ + function _grantComp(address recipient, uint amount) public { + require(adminOrInitializing(), "only admin can grant comp"); + uint amountLeft = grantCompInternal(recipient, amount); + require(amountLeft == 0, "insufficient comp for grant"); + emit CompGranted(recipient, amount); + } + + /** + * @notice Set COMP speed for a single market + * @param cToken The market whose COMP speed to update + * @param compSpeed New COMP speed for market + */ + function _setCompSpeed(CToken cToken, uint compSpeed) public { + require(adminOrInitializing(), "only admin can set comp speed"); + setCompSpeedInternal(cToken, compSpeed); + } + + /** + * @notice Set COMP speed for a single contributor + * @param contributor The contributor whose COMP speed to update + * @param compSpeed New COMP speed for contributor + */ + function _setContributorCompSpeed(address contributor, uint compSpeed) public { + require(adminOrInitializing(), "only admin can set comp speed"); + + // note that COMP speed could be set to 0 to halt liquidity rewards for a contributor + updateContributorRewards(contributor); + if (compSpeed == 0) { + // release storage + delete lastContributorBlock[contributor]; + } else { + lastContributorBlock[contributor] = getBlockNumber(); + } + compContributorSpeeds[contributor] = compSpeed; + + emit ContributorCompSpeedUpdated(contributor, compSpeed); + } + + function _setBProtocol(address cToken, address newBProtocol) public returns (uint) { + require(adminOrInitializing(), "only admin can set B.Protocol"); + + emit NewBProtocol(cToken, bprotocol[cToken], newBProtocol); + bprotocol[cToken] = newBProtocol; + + return uint(Error.NO_ERROR); + } + + /** + * @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 getCompAddress() public pure returns (address) { + return 0x10010078a54396F62c96dF8532dc2B4847d47ED3; + } +} + +contract CETH { + function mint() external returns (uint); + function transfer(address dst, uint256 amount) external returns (bool success); +} \ No newline at end of file diff --git a/packages/contracts/contracts/B.Protocol/CropJoinAdapter.sol b/packages/contracts/contracts/B.Protocol/CropJoinAdapter.sol deleted file mode 100644 index f2f982f74..000000000 --- a/packages/contracts/contracts/B.Protocol/CropJoinAdapter.sol +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity 0.6.11; - -import "./crop.sol"; -import "./../StabilityPool.sol"; - -// NOTE! - this is not an ERC20 token. transfer is not supported. -contract CropJoinAdapter is CropJoin { - string constant public name = "B.AMM LUSD-ETH"; - string constant public symbol = "LUSDETH"; - uint constant public decimals = 18; - - event Transfer(address indexed _from, address indexed _to, uint256 _value); - - constructor(address _lqty) public - CropJoin(address(new Dummy()), "B.AMM", address(new DummyGem()), _lqty) - { - } - - // adapter to cropjoin - function nav() public override returns (uint256) { - return total; - } - - function totalSupply() public view returns (uint256) { - return total; - } - - function balanceOf(address owner) public view returns (uint256 balance) { - balance = stake[owner]; - } - - function mint(address to, uint value) virtual internal { - join(to, value); - emit Transfer(address(0), to, value); - } - - function burn(address owner, uint value) virtual internal { - exit(owner, value); - emit Transfer(owner, address(0), value); - } -} - -contract Dummy { - fallback() external {} -} - -contract DummyGem is Dummy { - function transfer(address, uint) external pure returns(bool) { - return true; - } - - function transferFrom(address, address, uint) external pure returns(bool) { - return true; - } - - function decimals() external pure returns(uint) { - return 18; - } -} \ No newline at end of file diff --git a/packages/contracts/contracts/B.Protocol/Keeper/Arb.sol_ b/packages/contracts/contracts/B.Protocol/Keeper/Arb.sol_ new file mode 100644 index 000000000..39f1de2d6 --- /dev/null +++ b/packages/contracts/contracts/B.Protocol/Keeper/Arb.sol_ @@ -0,0 +1,310 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.6.11; +pragma experimental ABIEncoderV2; + + +interface UniswapReserve { + function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; +} + +interface UniswapV2Router01 { + function getAmountsOut(uint amountIn, address[] memory path) external view returns (uint[] memory amounts); +} + +interface ERC20Like { + function approve(address spender, uint value) external returns(bool); + function transfer(address to, uint value) external returns(bool); + function balanceOf(address a) external view returns(uint); +} + +interface WethLike is ERC20Like { + function deposit() external payable; +} + +interface BAMMLike { + function swap(uint lusdAmount, uint minEthReturn, address payable dest) external returns(uint); + function LUSD() external view returns(address); +} + +contract Arb { + UniswapV2Router01 immutable router; + ERC20Like immutable WETH; + + constructor(address _router, address _WETH) public { + router = UniswapV2Router01(_router); + WETH = ERC20Like(_WETH); + } + + function approve(address dst, ERC20Like token) external { + // callable by anyone, but the contract will never hold funds + token.approve(address(dst), uint(-1)); + } + + function getPrice(uint wethQty, address destToken) public returns(uint) { + address[] memory path = new address[](2); + path[0] = WETH; + path[1] = destToken; + address[] memory amounts = router.getAmountsOut(wethQty, path); + return amounts[1]; + } + + function swap(uint ethQty, address bamm, address USD, address USDETH) external payable returns(uint) { + uint usdQty = getPrice(ethQty, USD); + bytes memory data = abi.encode(bamm, ethQty, usdQty); + USDETH.swap(0, usdQty, address(this), data); + + uint retVal = address(this).balance; + msg.sender.transfer(retVal); + + return retVal; + } + + function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external { + (address bamm, uint ethQty, uint usdQty) = abi.decode(data, (address, uint, uint)); + + BAMMLike.swap(usdQty, 1, address(this)); + WethLike(WETH).deposit{value: ethQty}(); + WethLike(WETH).transfer(msg.sender, ethQty); + } + + receive() external payable {} +} + +contract ArbChecker { + Arb immutable public arb; + constructor(Arb _arb) public { + arb = _arb; + } + + function checkProfitableArb(uint ethQty, uint minProfit, address bamm, address USD, address USDETH) public { // revert on failure + uint balanceBefore = address(this).balance; + arb.swap(ethQty, bamm, USD, USDETH); + uint balanceAfter = address(this).balance; + require((balanceAfter - balanceBefore) >= minProfit, "min profit was not reached"); + } + + receive() external payable {} +} + +contract BKeeper { + address public masterCopy; + ArbChecker immutable public arbChecker; + Arb immutable public arb; + uint maxEthQty; // = 1000 ether; + uint minQty; // = 1e10; + uint minProfitInBps; // = 100; + + address public admin; + address[] public bamms; + mapping(address => address) public USD; // bamm to usd address + mapping(address => address) public router; // bamm to router + + event KeepOperation(bool succ); + + constructor(Arb _arb, ArbChecker _arbChecker) public { + arbChecker = ArbChecker(_arbChecker); + arb = _arb; + } + + function findSmallestQty() public returns(uint, address) { + for(uint i = 0 ; i < bamms.length ; i++) { + address bamm = bamms[i]; + for(uint qty = maxEthQty ; qty > minQty ; qty = qty / 2) { + uint minProfit = qty * minProfitInBps / 10000; + try arbChecker.checkProfitableArb(qty, minProfit, bamm, LUSD[bamm], router[bamm]) { + return (qty, bamm); + } catch { + + } + } + } + + return (0, address(0)); + } + + function checkUpkeep(bytes calldata /*checkData*/) external returns (bool upkeepNeeded, bytes memory performData) { + uint[] memory balances = new uint[](bamms.length); + for(uint i = 0 ; i < bamms.length ; i++) { + balances[i] = bamms[i].balance; + } + + (uint qty, address bamm) = findSmallestQty(); + + uint bammBalance; + for(uint i = 0 ; i < bamms.length ; i++) { + if(bamms[i] == bamm) bammBalance = balances[i]; + } + + upkeepNeeded = qty > 0; + performData = abi.encode(qty, bamm, bammBalance); + } + + function performUpkeep(bytes calldata performData) external { + (uint qty, address bamm, uint bammBalance) = abi.decode(performData, (uint, address, uint)); + require(bammBalance == bamm.balance, "performUpkeep: front runned"); + require(qty > 0, "0 qty"); + arb.swap(qty, bamm, LUSD[bamm], router[bamm]); + + emit KeepOperation(true); + } + + function performUpkeepSafe(bytes calldata performData) external { + try this.performUpkeep(performData) { + emit KeepOperation(true); + } + catch { + emit KeepOperation(false); + } + } + + receive() external payable {} + + // admin stuff + function transferAdmin(address newAdmin) external { + require(msg.sender == admin, "!admin"); + admin = newAdmin; + } + + function initParams(uint _maxEthQty, uint _minEthQty, uint _minProfit) external { + require(admin == address(0), "already init"); + maxEthQty = _maxEthQty; + minQty = _minEthQty; + minProfitInBps = _minProfit; + + admin = msg.sender; + } + + function setMaxEthQty(uint newVal) external { + require(msg.sender == admin, "!admin"); + maxEthQty = newVal; + } + + function setMinEthQty(uint newVal) external { + require(msg.sender == admin, "!admin"); + minQty = newVal; + } + + function setMinProfit(uint newVal) external { + require(msg.sender == admin, "!admin"); + minProfitInBps = newVal; + } + + function addBamm(address newBamm, address newRouter) external { + require(msg.sender == admin, "!admin"); + arb.approve(newBamm); + bamms.push(newBamm); + + LUSD[newBamm] = BAMMLike(newBamm).LUSD(); + router[newBamm] = newRouter; + } + + function removeBamm(address bamm) external { + require(msg.sender == admin, "!admin"); + for(uint i = 0 ; i < bamms.length ; i++) { + if(bamms[i] == bamm) { + bamms[i] = bamms[bamms.length - 1]; + bamms.pop(); + + return; + } + } + + revert("bamm does not exist"); + } + + function withdrawEth() external { + require(msg.sender == admin, "!admin"); + msg.sender.transfer(address(this).balance); + } + + function upgrade(address newMaster) public { + require(msg.sender == admin, "!admin"); + masterCopy = newMaster; + } +} + +contract KeeperProxy { + + // masterCopy always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated. + // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt` + address public masterCopy; + + /// @dev Constructor function sets address of master copy contract. + /// @param _masterCopy Master copy address. + constructor(address _masterCopy) + public + { + require(_masterCopy != address(0), "Invalid master copy address provided"); + masterCopy = _masterCopy; + } + + /// @dev Fallback function forwards all transactions and returns all received return data. + fallback() external payable + { + // solium-disable-next-line security/no-inline-assembly + address impl = masterCopy; + + assembly { + // Copy msg.data. We take full control of memory in this inline assembly + // block because it will not return to Solidity code. We overwrite the + // Solidity scratch pad at memory position 0. + calldatacopy(0, 0, calldatasize()) + + // Call the implementation. + // out and outsize are 0 because we don't know the size yet. + let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0) + + // Copy the returned data. + returndatacopy(0, 0, returndatasize()) + + switch result + // delegatecall returns 0 on error. + case 0 { + revert(0, returndatasize()) + } + default { + return(0, returndatasize()) + } + } + } +} + +interface KeeperLike { + function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData); + function performUpkeepSafe(bytes calldata performData) external; + function performUpkeep(bytes calldata performData) external; +} + +contract BGelato { + KeeperLike immutable public proxy; + + constructor(KeeperLike _proxy) public { + proxy = _proxy; + } + + function checker() + external + returns (bool canExec, bytes memory execPayload) + { + (bool upkeepNeeded, bytes memory performData) = proxy.checkUpkeep(bytes("")); + canExec = upkeepNeeded; + + execPayload = abi.encodeWithSelector( + BGelato.doer.selector, + performData + ); + } + + function doer(bytes calldata performData) external { + proxy.performUpkeepSafe(performData); + } + + function test(bytes calldata input) external { + address(this).call(input); + } +} + + +// sushi router 0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506 +// \ No newline at end of file diff --git a/packages/contracts/contracts/B.Protocol/Keeper/ArbFantom.sol b/packages/contracts/contracts/B.Protocol/Keeper/ArbFantom.sol new file mode 100644 index 000000000..d0f27c0e7 --- /dev/null +++ b/packages/contracts/contracts/B.Protocol/Keeper/ArbFantom.sol @@ -0,0 +1,253 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.6.11; +pragma experimental ABIEncoderV2; + + +interface IERC20 { + function balanceOf(address _owner) external view returns (uint256 balance); + function transfer(address _to, uint256 _value) external returns (bool success); + function approve(address _spender, uint256 _value) external returns (bool success); + function decimals() external view returns(uint8); +} + +interface IFlashloanReceiver { + function onFlashLoan(address initiator, address underlying, uint amount, uint fee, bytes calldata params) external; +} + +interface ICTokenFlashloan { + function flashLoan( + address receiver, + address initiator, + uint256 amount, + bytes calldata data + ) external; +} + +interface SpiritRouter { + function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] memory path, address to, uint256 deadline) external; +} + +interface BAMMInterface { + function swap(uint lusdAmount, IERC20 returnToken, uint minReturn, address payable dest) external returns(uint); + function LUSD() external view returns(address); + function collaterals(uint i) external view returns(address); +} + +interface CurveInterface { + function exchange(int128 i, int128 j, uint256 _dx, uint256 _min_dy) external returns(uint); +} + +contract CreamArb { + IERC20 constant public WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83); + SpiritRouter constant public ROUTER = SpiritRouter(0x16327E3FbDaCA3bcF7E38F5Af2599D2DDc33aE52); + CurveInterface constant public CURVE = CurveInterface(0x27E611FD27b276ACbd5Ffd632E5eAEBEC9761E40); + IERC20 constant public DAI = IERC20(0x8D11eC38a3EB5E956B052f67Da8Bdc9bef8Abf3E); + IERC20 constant public USDC = IERC20(0x04068DA6C83AFCFA0e13ba15A6696662335D5B75); + + function onFlashLoan(address initiator, address underlying, uint amount, uint fee, bytes calldata params) external returns(bytes32) { + IERC20(underlying).approve(initiator, amount + fee); + + (BAMMInterface bamm, address[] memory path, IERC20 dest) = abi.decode(params, (BAMMInterface, address[], IERC20)); + // swap on the bamm + IERC20(underlying).approve(address(bamm), amount); + uint destAmount = bamm.swap(amount, dest, 1, address(this)); + + dest.approve(address(ROUTER), destAmount); + if(dest != USDC) { + ROUTER.swapExactTokensForTokens(destAmount, 1, path, address(this), now); + } + + if(underlying == address(DAI)) { + uint usdcAmount = USDC.balanceOf(address(this)); + USDC.approve(address(CURVE), usdcAmount); + CURVE.exchange(1, 0, usdcAmount, 1); + } + + return keccak256("ERC3156FlashBorrowerInterface.onFlashLoan"); + } + + function arb(BAMMInterface bamm, uint srcAmount, address dest) public { + IERC20 src = IERC20(bamm.LUSD()); + + ICTokenFlashloan creamToken; + if(src == DAI) { + creamToken = ICTokenFlashloan(0x04c762a5dF2Fa02FE868F25359E0C259fB811CfE); + } + else if(src == USDC) { + creamToken = ICTokenFlashloan(0x328A7b4d538A2b3942653a9983fdA3C12c571141); + } + else revert("arb: unsupported src"); + + address[] memory path = new address[](3); + path[0] = dest; + path[1] = address(WFTM); + path[2] = address(USDC); + + bytes memory data = abi.encode(bamm, path, dest); + creamToken.flashLoan(address(this), address(creamToken), srcAmount, data); + + src.transfer(msg.sender, src.balanceOf(address(this))); + } + + // revert on failure + function checkProfitableArb(uint usdQty, uint minProfit, BAMMInterface bamm, address dest) external returns(bool){ + IERC20 src = IERC20(bamm.LUSD()); + uint balanceBefore = src.balanceOf(address(this)); + this.arb(bamm, usdQty, dest); + uint balanceAfter = src.balanceOf(address(this)); + require((balanceAfter - balanceBefore) >= minProfit, "min profit was not reached"); + + return true; + } + + fallback() payable external { + + } +} + +contract BFantomKeeper { + CreamArb public arb; + uint maxUsdQty = 100000e18; // = 100k usd; + uint minUsdQty = 1e16; // 1 cent + uint minProfitInBps = 0; // = 100; + + address public admin; + address[] public bamms; + mapping(address => address[]) bammTokens; // bamm => array of underlying + + event KeepOperation(bool succ); + + + constructor(CreamArb _arb) public { + arb = _arb; + admin = msg.sender; + } + + function findSmallestQty() public returns(uint, address, address) { + for(uint i = 0 ; i < bamms.length ; i++) { + address bamm = bamms[i]; + address[] memory dests = bammTokens[bamm]; + IERC20 src = IERC20(BAMMInterface(bamm).LUSD()); + uint decimals = src.decimals(); + uint factor = 10 ** decimals; + + for(uint qty = maxUsdQty ; qty > minUsdQty ; qty = qty / 10) { + uint normalizedQty = qty * factor / 1e18; + uint minProfit = normalizedQty * minProfitInBps / 10000; + for(uint d = 0 ; d < dests.length ; d++) { + try arb.checkProfitableArb(normalizedQty, minProfit, BAMMInterface(bamm), dests[d]) returns(bool /*retVal*/) { + return (normalizedQty, bamm, dests[d]); + } catch { + + } + } + } + } + + return (0, address(0), address(0)); + } + + function checkUpkeep(bytes calldata /*checkData*/) external returns (bool upkeepNeeded, bytes memory performData) { + (uint qty, address bamm, address dest) = findSmallestQty(); + + upkeepNeeded = qty > 0; + performData = abi.encode(qty, bamm, dest); + } + + function performUpkeep(bytes calldata performData) external { + (uint qty, address bamm, address dest) = abi.decode(performData, (uint, address, address)); + require(qty > 0, "0 qty"); + + arb.arb(BAMMInterface(bamm), qty, dest); + + emit KeepOperation(true); + } + + function performUpkeepSafe(bytes calldata performData) external { + try this.performUpkeep(performData) { + emit KeepOperation(true); + } + catch { + emit KeepOperation(false); + } + } + + function checker() + external + returns (bool canExec, bytes memory execPayload) + { + (bool upkeepNeeded, bytes memory performData) = this.checkUpkeep(bytes("")); + canExec = upkeepNeeded; + + execPayload = abi.encodeWithSelector( + BFantomKeeper.doer.selector, + performData + ); + } + + function doer(bytes calldata performData) external { + this.performUpkeepSafe(performData); + } + + receive() external payable {} + + // admin stuff + function transferAdmin(address newAdmin) external { + require(msg.sender == admin, "!admin"); + admin = newAdmin; + } + + function setArb(CreamArb _arb) external { + require(msg.sender == admin, "!admin"); + arb = _arb; + } + + function setMaxQty(uint newVal) external { + require(msg.sender == admin, "!admin"); + maxUsdQty = newVal; + } + + function setMinQty(uint newVal) external { + require(msg.sender == admin, "!admin"); + minUsdQty = newVal; + } + + function setMinProfit(uint newVal) external { + require(msg.sender == admin, "!admin"); + minProfitInBps = newVal; + } + + function addBamm(address newBamm) external { + require(msg.sender == admin, "!admin"); + bamms.push(newBamm); + + for(uint i = 0 ; true ; i++) { + try BAMMInterface(newBamm).collaterals(i) returns(address collat) { + bammTokens[newBamm].push(collat); + } + catch { + break; + } + } + } + + function removeBamm(address bamm) external { + require(msg.sender == admin, "!admin"); + for(uint i = 0 ; i < bamms.length ; i++) { + if(bamms[i] == bamm) { + bamms[i] = bamms[bamms.length - 1]; + bamms.pop(); + + return; + } + } + + revert("bamm does not exist"); + } + + function withdrawToken(IERC20 token, address to, uint qty) external { + require(msg.sender == admin, "!admin"); + token.transfer(to, qty); + } +} diff --git a/packages/contracts/contracts/B.Protocol/Keeper/ArbV3.sol b/packages/contracts/contracts/B.Protocol/Keeper/ArbV3.sol new file mode 100644 index 000000000..508118a7a --- /dev/null +++ b/packages/contracts/contracts/B.Protocol/Keeper/ArbV3.sol @@ -0,0 +1,340 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.6.11; +pragma experimental ABIEncoderV2; + +interface UniswapLens { + function quoteExactInputSingle( + address tokenIn, + address tokenOut, + uint24 fee, + uint256 amountIn, + uint160 sqrtPriceLimitX96 + ) external returns (uint256 amountOut); +} + +interface UniswapFactory { + function getPool(address token0, address token1, uint24 fee) external returns(address); +} + +interface UniswapReserve { + function swap( + address recipient, + bool zeroForOne, + int256 amountSpecified, + uint160 sqrtPriceLimitX96, + bytes calldata data + ) external returns (int256 amount0, int256 amount1); + + function token0() external view returns(address); + function token1() external view returns(address); +} + +interface ERC20Like { + function approve(address spender, uint value) external returns(bool); + function transfer(address to, uint value) external returns(bool); + function balanceOf(address a) external view returns(uint); +} + +interface WethLike is ERC20Like { + function deposit() external payable; +} + +interface CurveLike { + function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns(uint); +} + +interface BAMMLike { + function swap(uint lusdAmount, uint minEthReturn, address payable dest) external returns(uint); + function LUSD() external view returns(address); +} + +contract Arb { + address constant WETH = 0x82aF49447D8a07e3bd95BD0d56f35241523fBab1; + + UniswapLens constant public LENS = UniswapLens(0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6); + UniswapFactory constant FACTORY = UniswapFactory(0x1F98431c8aD98523631AE4a59f267346ea31F984); + uint160 constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; + uint160 constant MIN_SQRT_RATIO = 4295128739; + + // callable by anyone, but it does not suppose to hold funds anw + function approve(address bamm) external { + address token = BAMMLike(bamm).LUSD(); + ERC20Like(token).approve(address(bamm), uint(-1)); + } + + function getPrice(uint wethQty, address bamm) external returns(uint) { + return LENS.quoteExactInputSingle(WETH, BAMMLike(bamm).LUSD(), 500, wethQty, 0); + } + + function swap(uint ethQty, address bamm, uint uniFee) external payable returns(uint) { + bytes memory data = abi.encode(bamm, uniFee); + address reserve = FACTORY.getPool(WETH, BAMMLike(bamm).LUSD(), uint24(uniFee)); + UniswapReserve(reserve).swap(address(this), true, int256(ethQty), MIN_SQRT_RATIO + 1, data); + + uint retVal = address(this).balance; + msg.sender.transfer(retVal); + + return retVal; + } + + function uniswapV3SwapCallback( + int256 amount0Delta, + int256 amount1Delta, + bytes calldata data + ) external { + //require(msg.sender == address(USDCETH), "uniswapV3SwapCallback: invalid sender"); + // swap USDC to LUSD + uint USDCAmount = uint(-1 * amount1Delta); + uint LUSDReturn = USDCAmount; + + address bamm = abi.decode(data, (address)); + BAMMLike(bamm).swap(LUSDReturn, 1, address(this)); + + if(amount0Delta > 0) { + WethLike(WETH).deposit{value: uint(amount0Delta)}(); + if(amount0Delta > 0) WethLike(WETH).transfer(msg.sender, uint(amount0Delta)); + } + } + + function checkProfitableArb(uint ethQty, uint minProfit, address bamm, uint uniFee) external { // revert on failure + uint balanceBefore = address(this).balance; + this.swap(ethQty, bamm, uniFee); + uint balanceAfter = address(this).balance; + require((balanceAfter - balanceBefore) >= minProfit, "min profit was not reached"); + } + + receive() external payable {} +} + +contract BKeeper { + Arb public arb; + uint maxEthQty; // = 1000 ether; + uint minQty; // = 1e10; + uint minProfitInBps; // = 100; + + address public admin; + address[] public bamms; + + event KeepOperation(bool succ); + + constructor(Arb _arb) public { + arb = _arb; + } + + function findSmallestQty() public returns(uint, address, uint) { + for(uint j = 0 ; j < 2 ; j++) + { + uint uniFee = (j == 0) ? 500 : 3000; + + for(uint i = 0 ; i < bamms.length ; i++) { + address bamm = bamms[i]; + for(uint qty = maxEthQty ; qty > minQty ; qty = qty / 2) { + uint minProfit = qty * minProfitInBps / 10000; + try arb.checkProfitableArb(qty, minProfit, bamm, uniFee) { + return (qty, bamm, uniFee); + } catch { + + } + } + } + } + + return (0, address(0), 0); + } + + function checkUpkeep(bytes calldata /*checkData*/) external returns (bool upkeepNeeded, bytes memory performData) { + uint[] memory balances = new uint[](bamms.length); + for(uint i = 0 ; i < bamms.length ; i++) { + balances[i] = bamms[i].balance; + } + + (uint qty, address bamm, uint uniFee) = findSmallestQty(); + + uint bammBalance; + for(uint i = 0 ; i < bamms.length ; i++) { + if(bamms[i] == bamm) bammBalance = balances[i]; + } + + upkeepNeeded = qty > 0; + performData = abi.encode(qty, bamm, bammBalance, uniFee); + } + + function performUpkeep(bytes calldata performData) external { + (uint qty, address bamm, uint bammBalance, uint uniFee) = abi.decode(performData, (uint, address, uint, uint)); + require(bammBalance == bamm.balance, "performUpkeep: front runned"); + require(qty > 0, "0 qty"); + arb.swap(qty, bamm, uniFee); + + emit KeepOperation(true); + } + + function performUpkeepSafe(bytes calldata performData) external { + try this.performUpkeep(performData) { + emit KeepOperation(true); + } + catch { + emit KeepOperation(false); + } + } + + function checker() + external + returns (bool canExec, bytes memory execPayload) + { + (bool upkeepNeeded, bytes memory performData) = this.checkUpkeep(bytes("")); + canExec = upkeepNeeded; + + execPayload = abi.encodeWithSelector( + BKeeper.doer.selector, + performData + ); + } + + function doer(bytes calldata performData) external { + this.performUpkeepSafe(performData); + } + + receive() external payable {} + + // admin stuff + function transferAdmin(address newAdmin) external { + require(msg.sender == admin, "!admin"); + admin = newAdmin; + } + + function initParams(uint _maxEthQty, uint _minEthQty, uint _minProfit) external { + require(admin == address(0), "already init"); + maxEthQty = _maxEthQty; + minQty = _minEthQty; + minProfitInBps = _minProfit; + + admin = msg.sender; + } + + function setArb(Arb _arb) external { + require(msg.sender == admin, "!admin"); + arb = _arb; + } + + function setMaxEthQty(uint newVal) external { + require(msg.sender == admin, "!admin"); + maxEthQty = newVal; + } + + function setMinEthQty(uint newVal) external { + require(msg.sender == admin, "!admin"); + minQty = newVal; + } + + function setMinProfit(uint newVal) external { + require(msg.sender == admin, "!admin"); + minProfitInBps = newVal; + } + + function addBamm(address newBamm) external { + require(msg.sender == admin, "!admin"); + arb.approve(newBamm); + bamms.push(newBamm); + } + + function removeBamm(address bamm) external { + require(msg.sender == admin, "!admin"); + for(uint i = 0 ; i < bamms.length ; i++) { + if(bamms[i] == bamm) { + bamms[i] = bamms[bamms.length - 1]; + bamms.pop(); + + return; + } + } + + revert("bamm does not exist"); + } + + function withdrawEth() external { + require(msg.sender == admin, "!admin"); + msg.sender.transfer(address(this).balance); + } +} + +contract KeeperProxy { + + // masterCopy always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated. + // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt` + address public masterCopy; + + /// @dev Constructor function sets address of master copy contract. + /// @param _masterCopy Master copy address. + constructor(address _masterCopy) + public + { + require(_masterCopy != address(0), "Invalid master copy address provided"); + masterCopy = _masterCopy; + } + + /// @dev Fallback function forwards all transactions and returns all received return data. + fallback() external payable + { + // solium-disable-next-line security/no-inline-assembly + address impl = masterCopy; + + assembly { + // Copy msg.data. We take full control of memory in this inline assembly + // block because it will not return to Solidity code. We overwrite the + // Solidity scratch pad at memory position 0. + calldatacopy(0, 0, calldatasize()) + + // Call the implementation. + // out and outsize are 0 because we don't know the size yet. + let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0) + + // Copy the returned data. + returndatacopy(0, 0, returndatasize()) + + switch result + // delegatecall returns 0 on error. + case 0 { + revert(0, returndatasize()) + } + default { + return(0, returndatasize()) + } + } + } +} + +interface KeeperLike { + function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData); + function performUpkeepSafe(bytes calldata performData) external; + function performUpkeep(bytes calldata performData) external; +} + +contract BGelato { + KeeperLike immutable public proxy; + + constructor(KeeperLike _proxy) public { + proxy = _proxy; + } + + function checker() + external + returns (bool canExec, bytes memory execPayload) + { + (bool upkeepNeeded, bytes memory performData) = proxy.checkUpkeep(bytes("")); + canExec = upkeepNeeded; + + execPayload = abi.encodeWithSelector( + BGelato.doer.selector, + performData + ); + } + + function doer(bytes calldata performData) external { + proxy.performUpkeepSafe(performData); + } + + function test(bytes calldata input) external { + address(this).call(input); + } +} \ No newline at end of file diff --git a/packages/contracts/contracts/B.Protocol/Keeper/LiquidationBot.sol b/packages/contracts/contracts/B.Protocol/Keeper/LiquidationBot.sol new file mode 100644 index 000000000..603c85883 --- /dev/null +++ b/packages/contracts/contracts/B.Protocol/Keeper/LiquidationBot.sol @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.6.11; +pragma experimental ABIEncoderV2; + +interface IComptroller { + function getAccountLiquidity(address account) view external returns (uint error, uint liquidity, uint shortfall); + function closeFactorMantissa() view external returns (uint); + function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) + external view returns (uint error , uint ctokenAmount); + function getAssetsIn(address account) view external returns(address[] memory); +} + +interface CToken { + function borrowBalanceStored(address account) external view returns (uint); + function balanceOf(address account) view external returns (uint); + function underlying() view external returns(address); + function decimals() view external returns(uint8); +} + +interface BAMMLike { + function LUSD() view external returns(uint); + function cBorrow() view external returns(address); + function cTokens(address a) view external returns(bool); +} + +contract LiquidationBotHelper { + struct Account { + address account; + address bamm; + address ctoken; + uint repayAmount; + bool underwater; + } + + function getAccountInfo(address account, IComptroller comptroller, BAMMLike bamm) public view returns(Account memory a) { + address[] memory ctokens = comptroller.getAssetsIn(account); + + CToken cBorrow = CToken(bamm.cBorrow()); + uint repayAmount = cBorrow.borrowBalanceStored(account) * comptroller.closeFactorMantissa() / 1e18; + uint bammBalance = CToken(cBorrow.underlying()).balanceOf(address(bamm)); + uint decimals = CToken(cBorrow.underlying()).decimals(); + if(repayAmount > bammBalance) repayAmount = bammBalance; + if(repayAmount == 0) return a; + + a.account = account; + a.bamm = address(bamm); + a.repayAmount = 0; + + uint orgRepayAmount = repayAmount; + + for(uint i = 0; i < ctokens.length ; i++) { + repayAmount = orgRepayAmount; + + address ctoken = ctokens[i]; + + if((! bamm.cTokens(ctoken)) && (ctoken != address(cBorrow))) continue; + CToken cETH = CToken(ctoken); + + uint cETHBalance = cETH.balanceOf(account); + if(cETHBalance == 0) continue; + + (uint err, uint cETHAmount) = comptroller.liquidateCalculateSeizeTokens(address(cBorrow), address(cETH), repayAmount); + + if(cETHAmount == 0 || err != 0) continue; + + if(cETHBalance < cETHAmount) { + repayAmount = cETHBalance * repayAmount / cETHAmount; + } + + // dust + if(repayAmount < (10 ** (decimals - 1))) continue; + + // get the collateral with the highest deposits + if(repayAmount > a.repayAmount) { + a.repayAmount = repayAmount; + a.ctoken = ctoken; + } + } + } + + function getInfo(address[] memory accounts, address comptroller, address[] memory bamms) public view returns(Account[] memory unsafeAccounts) { + if(accounts.length == 0) return unsafeAccounts; + + Account[] memory actions = new Account[](accounts.length); + uint numUnsafe = 0; + + for(uint i = 0 ; i < accounts.length ; i++) { + (uint err,, uint shortfall) = IComptroller(comptroller).getAccountLiquidity(accounts[i]); + if(shortfall == 0 || err != 0) continue; + + Account memory a; + + for(uint j = 0 ; j < bamms.length ; j++) { + a = getAccountInfo(accounts[i], IComptroller(comptroller), BAMMLike(bamms[j])); + if(a.repayAmount > 0) { + actions[numUnsafe++] = a; + break; + } + + a.underwater = true; + } + } + + unsafeAccounts = new Account[](numUnsafe); + for(uint k = 0 ; k < numUnsafe ; k++) { + unsafeAccounts[k] = actions[k]; + } + } +} diff --git a/packages/contracts/contracts/B.Protocol/MockCToken.sol b/packages/contracts/contracts/B.Protocol/MockCToken.sol new file mode 100644 index 000000000..45afeab13 --- /dev/null +++ b/packages/contracts/contracts/B.Protocol/MockCToken.sol @@ -0,0 +1,59 @@ + +// SPDX-License-Identifier: MIT + +pragma solidity 0.6.11; + +import "./../Dependencies/IERC20.sol"; + +contract MockCToken { + IERC20 token; + bool isEth; + mapping(address => uint) public balanceOf; + uint price; + + constructor (IERC20 _token, bool _isETH) public { + token = _token; + isEth = _isETH; + } + + function underlying() external view returns(IERC20) { + require(! isEth, "underlying: unsupported"); + return token; + } + + function redeem(uint redeemTokens) external returns (uint) { + require(balanceOf[msg.sender] >= redeemTokens, "redeem: insufficient ballance"); + + if(isEth) msg.sender.transfer(redeemTokens); + else token.transfer(msg.sender, redeemTokens); + + balanceOf[msg.sender] -= redeemTokens; + } + + function depositToken(uint amount) public { + require(!isEth, "depositToken: failed only ETH can be deposited use depositEther"); + token.transferFrom(msg.sender, address(this), amount); + balanceOf[msg.sender] += amount; + } + + function depositEther() public payable { + require(isEth, "depositEther: failed only ERC20 can be deposited use depositToken"); + balanceOf[msg.sender] += msg.value; + } + + function transfer(address from, address to, uint amount) public { + require(balanceOf[from] >= amount, "transfer: insufficient ballance"); + balanceOf[from] -= amount; + balanceOf[to] += amount; + } + + function setPrice(uint _price) public { + price = _price; + } + + function liquidateBorrow(address borrower, uint amount, MockCToken collateral) external returns (uint) { + require(isEth == false, "can't liquidate ETH"); + token.transferFrom(msg.sender, address(this), amount); + collateral.transfer(borrower, msg.sender, amount * price / 1e18); + } +} \ No newline at end of file diff --git a/packages/contracts/contracts/B.Protocol/MockToken.sol b/packages/contracts/contracts/B.Protocol/MockToken.sol new file mode 100644 index 000000000..d36ff3a7d --- /dev/null +++ b/packages/contracts/contracts/B.Protocol/MockToken.sol @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.6.11; + +import "./../Dependencies/SafeMath.sol"; + + +contract TokenAdapter2 { + using SafeMath for uint256; + + string constant public name = "B.AMM"; + string constant public symbol = "BAMM"; + uint public decimals = 18; + + uint public totalSupply; + + event Transfer(address indexed from, address indexed to, uint tokens); + event Approval(address indexed tokenOwner, address indexed spender, uint tokens); + + // balanceOf for each account + mapping(address => uint256) public balanceOf; + + // Owner of account approves the transfer of an amount to another account + mapping(address => mapping (address => uint256)) public allowance; + + // Transfer the balance from owner's account to another account + function transfer(address to, uint tokens) public returns (bool success) { + balanceOf[msg.sender] = balanceOf[msg.sender].sub(tokens); + balanceOf[to] = balanceOf[to].add(tokens); + emit Transfer(msg.sender, to, tokens); + return true; + } + + // Send `tokens` amount of tokens from address `from` to address `to` + // The transferFrom method is used for a withdraw workflow, allowing contracts to send + // tokens on your behalf, for example to "deposit" to a contract address and/or to charge + // fees in sub-currencies; the command should fail unless the _from account has + // deliberately authorized the sender of the message via some mechanism; we propose + // these standardized APIs for approval: + function transferFrom(address from, address to, uint tokens) public returns (bool success) { + balanceOf[from] = balanceOf[from].sub(tokens); + allowance[from][msg.sender] = allowance[from][msg.sender].sub(tokens); + balanceOf[to] = balanceOf[to].add(tokens); + emit Transfer(from, to, tokens); + return true; + } + + // Allow `spender` to withdraw from your account, multiple times, up to the `tokens` amount. + // If this function is called again it overwrites the current allowance with _value. + function approve(address spender, uint tokens) public returns (bool success) { + allowance[msg.sender][spender] = tokens; + emit Approval(msg.sender, spender, tokens); + return true; + } + + function mint(address to, uint tokens) internal { + balanceOf[to] = balanceOf[to].add(tokens); + totalSupply = totalSupply.add(tokens); + + emit Transfer(address(0), to, tokens); + } + + function burn(address owner, uint tokens) internal { + balanceOf[owner] = balanceOf[owner].sub(tokens); + totalSupply = totalSupply.sub(tokens); + + emit Transfer(owner, address(0), tokens); + } +} + + + +contract MockToken is TokenAdapter2 { + constructor(uint _decimals) public { + decimals = _decimals; + } + + function mintToken(address to, uint tokens) public { + mint(to, tokens); + } +} + +/* +contract MockCETH { + +}*/ \ No newline at end of file diff --git a/packages/contracts/contracts/B.Protocol/MockWithAdmin.sol b/packages/contracts/contracts/B.Protocol/MockWithAdmin.sol new file mode 100644 index 000000000..39787c30c --- /dev/null +++ b/packages/contracts/contracts/B.Protocol/MockWithAdmin.sol @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.6.11; + +contract MockWithAdmin { + address public admin; + + function setAdmin(address _admin) public { + admin = _admin; + } +} \ No newline at end of file diff --git a/packages/contracts/contracts/B.Protocol/MockePickle.sol b/packages/contracts/contracts/B.Protocol/MockePickle.sol deleted file mode 100644 index dc32e7210..000000000 --- a/packages/contracts/contracts/B.Protocol/MockePickle.sol +++ /dev/null @@ -1,93 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity 0.6.11; - -contract EIP20 { - - event Transfer(address indexed _from, address indexed _to, uint256 _value); - event Approval(address indexed _owner, address indexed _spender, uint256 _value); - - uint256 public totalSupply; - 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 - - constructor ( - uint256 _initialAmount, - string memory _tokenName, - uint8 _decimalUnits, - string memory _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]; - } - - // only for mock - function mint(address _to, uint _qty) public { - balances[_to] += _qty; - } -} - -contract PickleJar { - EIP20 public token; - EIP20 public pToken; - - constructor(EIP20 _token, EIP20 _ptoken) public { - token = _token; - pToken = _ptoken; - } - - function depositAll() external { - uint userBalance = token.balanceOf(msg.sender); - require(token.transferFrom(msg.sender, address(this), userBalance), "depositAll: transferFrom failed"); - pToken.mint(msg.sender, userBalance / 2); // 1 share = 2 token - } -} - - diff --git a/packages/contracts/contracts/B.Protocol/PBAMM.sol b/packages/contracts/contracts/B.Protocol/PBAMM.sol deleted file mode 100644 index 50d2c371f..000000000 --- a/packages/contracts/contracts/B.Protocol/PBAMM.sol +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity 0.6.11; - -import "./BAMM.sol"; - -interface PickleJarLike { - function depositAll() external; -} - -contract PBAMM is BAMM { - PickleJarLike public immutable pickleJar; - - constructor( - address _priceAggregator, - address payable _SP, - address _LUSD, - address _LQTY, - uint _maxDiscount, - address payable _feePool, - address _frontEndTag, - address _pLQTY, - address _pickleJar) - public - BAMM(_priceAggregator, _SP, _LUSD, _pLQTY, _maxDiscount, _feePool, _frontEndTag) - { - pickleJar = PickleJarLike(_pickleJar); - - require(IERC20(_LQTY).approve(_pickleJar, type(uint).max), "constructor: approve failed"); - } - - // callable by anyone - function depositLqty() external { - SP.withdrawFromSP(0); - pickleJar.depositAll(); - } - - function mint(address to, uint value) override internal { - pickleJar.depositAll(); - super.mint(to, value); - } - - function burn(address owner, uint value) override internal { - pickleJar.depositAll(); - super.burn(owner, value); - } -} diff --git a/packages/contracts/contracts/B.Protocol/StableOracle.sol b/packages/contracts/contracts/B.Protocol/StableOracle.sol new file mode 100644 index 000000000..47997d811 --- /dev/null +++ b/packages/contracts/contracts/B.Protocol/StableOracle.sol @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.6.11; + +import "./../Dependencies/AggregatorV3Interface.sol"; + +contract StableOralce { + AggregatorV3Interface immutable oracle; + + constructor(AggregatorV3Interface _oracle) public { + oracle = _oracle; + } + + function decimals() public view returns (uint8) { + return oracle.decimals(); + } + + function latestRoundData() public view + returns + ( + uint80 roundId, + int256 answer, + uint256 startedAt, + uint256 timestamp, + uint80 answeredInRound + ) + { + (roundId, answer, startedAt, timestamp, answeredInRound) = oracle.latestRoundData(); + timestamp = now; // override timestamp + } +} + +contract NonUSDOracle { + AggregatorV3Interface immutable public srcOracle; + AggregatorV3Interface immutable public targetOracle; + + constructor(AggregatorV3Interface _srcOracle, AggregatorV3Interface _targetOracle) public { + srcOracle = _srcOracle; + targetOracle = _targetOracle; + } + + function decimals() public view returns (uint8) { + return targetOracle.decimals(); + } + + function latestRoundData() public view + returns + ( + uint80 roundId, + int256 answer, + uint256 startedAt, + uint256 timestamp, + uint80 answeredInRound + ) + { + int targetAnswer; + int srcAnswer; + uint targetTimestamp; + uint srcTimestamp; + + (roundId, targetAnswer, startedAt, targetTimestamp, answeredInRound) = targetOracle.latestRoundData(); + (, srcAnswer, , srcTimestamp,) = srcOracle.latestRoundData(); + + uint srcDecimals = srcOracle.decimals(); + + answer = targetAnswer * int(10 ** srcDecimals) / srcAnswer; + timestamp = srcTimestamp > targetTimestamp ? targetTimestamp : srcTimestamp; // take the minimum + + // check if there was an overflow in calculation - if there was, return 0 timestamp and answer + bool overflow = false; + if(targetAnswer > type(int128).max) overflow = true; + if(srcDecimals > 18) overflow = true; + + if(overflow) { + timestamp = 0; + answer = 0; + } + } +} + +contract FixedOracle { + function decimals() public pure returns (uint8) { + return 8; + } + + function latestRoundData() public view + returns + ( + uint80 roundId, + int256 answer, + uint256 startedAt, + uint256 timestamp, + uint80 answeredInRound + ) + { + roundId = 5; + answer = 1e8; + startedAt = now; + timestamp = now; + answeredInRound = 5; + } +} \ No newline at end of file diff --git a/packages/contracts/contracts/B.Protocol/TokenAdapter.sol b/packages/contracts/contracts/B.Protocol/TokenAdapter.sol new file mode 100644 index 000000000..1072a75c8 --- /dev/null +++ b/packages/contracts/contracts/B.Protocol/TokenAdapter.sol @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.6.11; + +import "./../Dependencies/SafeMath.sol"; + + +contract TokenAdapter { + using SafeMath for uint256; + + string constant public name = "B.AMM"; + string constant public symbol = "BAMM"; + uint8 constant public decimals = 18; + + uint public totalSupply; + + event Transfer(address indexed from, address indexed to, uint tokens); + event Approval(address indexed tokenOwner, address indexed spender, uint tokens); + + // balanceOf for each account + mapping(address => uint256) public balanceOf; + + // Owner of account approves the transfer of an amount to another account + mapping(address => mapping (address => uint256)) public allowance; + + // Transfer the balance from owner's account to another account + function transfer(address to, uint tokens) public returns (bool success) { + balanceOf[msg.sender] = balanceOf[msg.sender].sub(tokens); + balanceOf[to] = balanceOf[to].add(tokens); + emit Transfer(msg.sender, to, tokens); + return true; + } + + // Send `tokens` amount of tokens from address `from` to address `to` + // The transferFrom method is used for a withdraw workflow, allowing contracts to send + // tokens on your behalf, for example to "deposit" to a contract address and/or to charge + // fees in sub-currencies; the command should fail unless the _from account has + // deliberately authorized the sender of the message via some mechanism; we propose + // these standardized APIs for approval: + function transferFrom(address from, address to, uint tokens) public returns (bool success) { + balanceOf[from] = balanceOf[from].sub(tokens); + if(allowance[from][msg.sender] != type(uint256).max) { + allowance[from][msg.sender] = allowance[from][msg.sender].sub(tokens); + } + balanceOf[to] = balanceOf[to].add(tokens); + emit Transfer(from, to, tokens); + return true; + } + + // Allow `spender` to withdraw from your account, multiple times, up to the `tokens` amount. + // If this function is called again it overwrites the current allowance with _value. + function approve(address spender, uint tokens) public returns (bool success) { + allowance[msg.sender][spender] = tokens; + emit Approval(msg.sender, spender, tokens); + return true; + } + + function mint(address to, uint tokens) internal { + balanceOf[to] = balanceOf[to].add(tokens); + totalSupply = totalSupply.add(tokens); + + emit Transfer(address(0), to, tokens); + } + + function burn(address owner, uint tokens) internal { + balanceOf[owner] = balanceOf[owner].sub(tokens); + totalSupply = totalSupply.sub(tokens); + + emit Transfer(owner, address(0), tokens); + } +} + diff --git a/packages/contracts/contracts/B.Protocol/crop.sol b/packages/contracts/contracts/B.Protocol/crop.sol deleted file mode 100644 index 8eb279ef0..000000000 --- a/packages/contracts/contracts/B.Protocol/crop.sol +++ /dev/null @@ -1,167 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -// Copyright (C) 2021 Dai Foundation -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -pragma solidity 0.6.11; - -interface VatLike { - function urns(bytes32, address) external view returns (uint256, uint256); - function gem(bytes32, address) external view returns (uint256); - function slip(bytes32, address, int256) external; -} - -interface ERC20 { - function balanceOf(address owner) external view returns (uint256); - function transfer(address dst, uint256 amount) external returns (bool); - function transferFrom(address src, address dst, uint256 amount) external returns (bool); - function approve(address spender, uint256 amount) external returns (bool); - function allowance(address owner, address spender) external view returns (uint256); - function decimals() external returns (uint8); -} - -// receives tokens and shares them among holders -contract CropJoin { - - VatLike public immutable vat; // cdp engine - bytes32 public immutable ilk; // collateral type - ERC20 public immutable gem; // collateral token - uint256 public immutable dec; // gem decimals - ERC20 public immutable bonus; // rewards token - - uint256 public share; // crops per gem [ray] - uint256 public total; // total gems [wad] - uint256 public stock; // crop balance [wad] - - mapping (address => uint256) public crops; // crops per user [wad] - mapping (address => uint256) public stake; // gems per user [wad] - - uint256 immutable internal to18ConversionFactor; - uint256 immutable internal toGemConversionFactor; - - // --- Events --- - event Join(uint256 val); - event Exit(uint256 val); - event Flee(); - event Tack(address indexed src, address indexed dst, uint256 wad); - - constructor(address vat_, bytes32 ilk_, address gem_, address bonus_) public { - vat = VatLike(vat_); - ilk = ilk_; - gem = ERC20(gem_); - uint256 dec_ = ERC20(gem_).decimals(); - require(dec_ <= 18); - dec = dec_; - to18ConversionFactor = 10 ** (18 - dec_); - toGemConversionFactor = 10 ** dec_; - - bonus = ERC20(bonus_); - } - - function add(uint256 x, uint256 y) public pure returns (uint256 z) { - require((z = x + y) >= x, "ds-math-add-overflow"); - } - function sub(uint256 x, uint256 y) public pure returns (uint256 z) { - require((z = x - y) <= x, "ds-math-sub-underflow"); - } - function mul(uint256 x, uint256 y) public pure returns (uint256 z) { - require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); - } - function divup(uint256 x, uint256 y) internal pure returns (uint256 z) { - z = add(x, sub(y, 1)) / y; - } - uint256 constant WAD = 10 ** 18; - function wmul(uint256 x, uint256 y) public pure returns (uint256 z) { - z = mul(x, y) / WAD; - } - function wdiv(uint256 x, uint256 y) public pure returns (uint256 z) { - z = mul(x, WAD) / y; - } - function wdivup(uint256 x, uint256 y) public pure returns (uint256 z) { - z = divup(mul(x, WAD), y); - } - uint256 constant RAY = 10 ** 27; - function rmul(uint256 x, uint256 y) public pure returns (uint256 z) { - z = mul(x, y) / RAY; - } - function rmulup(uint256 x, uint256 y) public pure returns (uint256 z) { - z = divup(mul(x, y), RAY); - } - function rdiv(uint256 x, uint256 y) public pure returns (uint256 z) { - z = mul(x, RAY) / y; - } - - // Net Asset Valuation [wad] - function nav() public virtual returns (uint256) { - uint256 _nav = gem.balanceOf(address(this)); - return mul(_nav, to18ConversionFactor); - } - - // Net Assets per Share [wad] - function nps() public returns (uint256) { - if (total == 0) return WAD; - else return wdiv(nav(), total); - } - - function crop() internal virtual returns (uint256) { - return sub(bonus.balanceOf(address(this)), stock); - } - - function harvest(address from, address to) internal { - if (total > 0) share = add(share, rdiv(crop(), total)); - - uint256 last = crops[from]; - uint256 curr = rmul(stake[from], share); - if (curr > last) require(bonus.transfer(to, curr - last)); - stock = bonus.balanceOf(address(this)); - } - - function join(address urn, uint256 val) internal virtual { - harvest(urn, urn); - if (val > 0) { - uint256 wad = wdiv(mul(val, to18ConversionFactor), nps()); - - // Overflow check for int256(wad) cast below - // Also enforces a non-zero wad - require(int256(wad) > 0); - - require(gem.transferFrom(msg.sender, address(this), val)); - vat.slip(ilk, urn, int256(wad)); - - total = add(total, wad); - stake[urn] = add(stake[urn], wad); - } - crops[urn] = rmulup(stake[urn], share); - emit Join(val); - } - - function exit(address guy, uint256 val) internal virtual { - harvest(msg.sender, guy); - if (val > 0) { - uint256 wad = wdivup(mul(val, to18ConversionFactor), nps()); - - // Overflow check for int256(wad) cast below - // Also enforces a non-zero wad - require(int256(wad) > 0); - - require(gem.transfer(guy, val)); - vat.slip(ilk, msg.sender, -int256(wad)); - - total = sub(total, wad); - stake[msg.sender] = sub(stake[msg.sender], wad); - } - crops[msg.sender] = rmulup(stake[msg.sender], share); - emit Exit(val); - } -} diff --git a/packages/contracts/hardhat.config.js b/packages/contracts/hardhat.config.js index 15e9e76c0..8da49d43e 100644 --- a/packages/contracts/hardhat.config.js +++ b/packages/contracts/hardhat.config.js @@ -63,12 +63,22 @@ module.exports = { ] }, networks: { + hardhat: { accounts: accountsList, gas: 10000000, // tx gas limit blockGasLimit: 12500000, gasPrice: 20000000000, }, +/* + hardhat: { + forking: { + //url: "https://arb1.arbitrum.io/rpc" + url: "https://rpc.ftm.tools" + } + },*/ + + mainnet: { url: alchemyUrl(), gasPrice: process.env.GAS_PRICE ? parseInt(process.env.GAS_PRICE) : 20000000000, diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 9e89963bd..72e2551ea 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -31,7 +31,7 @@ "@nomiclabs/hardhat-etherscan": "^2.1.2", "@nomiclabs/hardhat-truffle5": "^2.0.0", "@nomiclabs/hardhat-web3": "^2.0.0", - "@openzeppelin/contracts": "^3.3.0", + "@openzeppelin/contracts": "3.2.0", "@openzeppelin/test-helpers": "^0.5.10", "eth-gas-reporter": "^0.2.22", "hardhat": "^2.1.1", diff --git a/packages/contracts/scripts/bKeeper-test.js b/packages/contracts/scripts/bKeeper-test.js new file mode 100644 index 000000000..f51918aff --- /dev/null +++ b/packages/contracts/scripts/bKeeper-test.js @@ -0,0 +1,32 @@ +// todo transefer 1000 ETH to bamm +const hre = require("hardhat"); + +const send1000ETH = async () => { + + const to = "0x04208f296039f482810b550ae0d68c3e1a5eb719" + const from = "0x8e15a22853A0A60a0FBB0d875055A8E66cff0235" + const value = web3.utils.toWei("1000") + await hre.network.provider.request({ + method: "hardhat_impersonateAccount", + params: [from], + }) + var send = await web3.eth.sendTransaction({ from, to, value }); + return send +} + +const {run} = require("../../liquidator/bKeeper") + +const init = async () =>{ + try{ + await send1000ETH() + let balance = await web3.eth.getBalance("0x04208f296039f482810b550ae0d68c3e1a5eb719"); //Will give value in. + console.log(balance.toString()) + await run() + balance = await web3.eth.getBalance("0x04208f296039f482810b550ae0d68c3e1a5eb719"); //Will give value in. + console.log(balance.toString()) + } catch (err){ + console.error(err) + } +} + +init() \ No newline at end of file diff --git a/packages/contracts/test/B.Protocol/ArbTest.js b/packages/contracts/test/B.Protocol/ArbTest.js new file mode 100644 index 000000000..f0dde3657 --- /dev/null +++ b/packages/contracts/test/B.Protocol/ArbTest.js @@ -0,0 +1,174 @@ +const { artifacts } = require("hardhat") +const deploymentHelper = require("./../../utils/deploymentHelpers.js") +const testHelpers = require("./../../utils/testHelpers.js") +const th = testHelpers.TestHelper +const dec = th.dec +const toBN = th.toBN +const mv = testHelpers.MoneyValues +const timeValues = testHelpers.TimeValues + +const TroveManagerTester = artifacts.require("TroveManagerTester") +const MockToken = artifacts.require("MockToken") +const MockCToken = artifacts.require("MockCToken") +const NonPayable = artifacts.require('NonPayable.sol') +const BAMM = artifacts.require("BAMM.sol") +const BLens = artifacts.require("BLens.sol") +const ChainlinkTestnet = artifacts.require("ChainlinkTestnet.sol") +const Arb = artifacts.require("Arb.sol") + + +const ZERO = toBN('0') +const ZERO_ADDRESS = th.ZERO_ADDRESS +const maxBytes32 = th.maxBytes32 + +const getFrontEndTag = async (stabilityPool, depositor) => { + return (await stabilityPool.deposits(depositor))[1] +} + + + +contract('BAMM', async accounts => { + const [owner, + defaulter_1, defaulter_2, defaulter_3, + alice, bob, carol, dennis, erin, flyn, + A, B, C, D, E, F, + u1, u2, u3, u4, u5, + v1, v2, v3, v4, v5, + frontEnd_1, frontEnd_2, frontEnd_3, + bammOwner, + shmuel, yaron, eitan + ] = accounts; + + const [bountyAddress, lpRewardsAddress, multisig] = accounts.slice(997, 1000) + + const frontEnds = [frontEnd_1, frontEnd_2, frontEnd_3] + let contracts + let priceFeed + let lusdToken + let bamm + let lens + let chainlink + + let gasPriceInWei + + let cETH + let cLUSD + + const feePool = "0x1000000000000000000000000000000000000001" + + const isWithin99Percent = (onePercent, b)=> { + return (b.gte(onePercent.mul(toBN(99))) && b.lte(onePercent.mul(toBN(100)))) + } + + //const assertRevert = th.assertRevert + + describe("BAMM", async () => { + + before(async () => { + gasPriceInWei = await web3.eth.getGasPrice() + }) + + beforeEach(async () => { + }) + + it.only("Arb", async () => { + const whale = "0x23cBF6d1b738423365c6930F075Ed6feEF7d14f3" // has eth and usdt +/* + await hre.network.provider.request({ + method: "hardhat_impersonateAccount", + params: [whale], + }) + + const cusdc = await MockToken.at("0x04068DA6C83AFCFA0e13ba15A6696662335D5B75") + const creamArb = await artifacts.require("CreamArb").new() + console.log("cream", creamArb.address) + + //const isProf = await creamArb.checkProfitableArb.call(dec(1,17), 0, "0x6d62d6Af9b82CDfA3A7d16601DDbCF8970634d22", cusdc.address) + //console.log({isProf}) + + + console.log("sending usdc") + //await cusdc.transfer(creamArb.address, dec(3,6), {from: whale}) +*/ + const keeper = await artifacts.require("BFantomKeeper").at("0xb5CDc43cefd1826A669Dbd3A8D6180a3B623aef7")//(creamArb.address, {from: whale}) + + const bammUsdc = "0xEDC7905a491fF335685e2F2F1552541705138A3D" + const bammDai = "0x6d62d6Af9b82CDfA3A7d16601DDbCF8970634d22" +/* + console.log("setting min") + await keeper.setMinQty(dec(1,16), {from: whale}) + console.log("setting max") + await keeper.setMaxQty(dec(100000,18), {from: whale}) + console.log("adding bamm usdc") + await keeper.addBamm(bammUsdc, {from: whale}) + console.log("adding bamm dai") + await keeper.addBamm(bammDai, {from: whale}) +*/ + console.log("find qty") + console.log(keeper.address) + const result = await keeper.findSmallestQty.call({gas: 100000000}) + console.log(result[0].toString()) + console.log({result}) + + console.log("check upkeep") + const up = await keeper.checkUpkeep.call("0x", {gas: 100000000}) + console.log({up}) + console.log("do upkeep") + console.log("before", (await cusdc.balanceOf(keeper.address)).toString()) + await keeper.performUpkeep(up.performData) + console.log("after", (await cusdc.balanceOf(keeper.address)).toString()) + + const res = await keeper.checker.call({gas: 100000000}) + console.log({res}) + + const bamm = "0xEDC7905a491fF335685e2F2F1552541705138A3D" + const dest = "0x29b0Da86e484E1C0029B56e817912d778aC0EC69" + const creamUSDC = "0x328A7b4d538A2b3942653a9983fdA3C12c571141" + + /* + console.log("whale", (await cusdc.balanceOf(whale)).toString()) + await creamArb.arb(bamm, creamUSDC, dec(1,5), dest, {from: whale}) + + console.log((await cusdc.balanceOf(creamArb.address)).toString()) + console.log("whale", (await cusdc.balanceOf(whale)).toString()) + //const tx = await creamArb.f() + */ + }) + }) +}) + + +function almostTheSame(n1, n2) { + n1 = Number(web3.utils.fromWei(n1)) + n2 = Number(web3.utils.fromWei(n2)) + //console.log(n1,n2) + + if(n1 * 1000 > n2 * 1001) return false + if(n2 * 1000 > n1 * 1001) return false + return true +} + +function in100WeiRadius(n1, n2) { + const x = toBN(n1) + const y = toBN(n2) + + if(x.add(toBN(100)).lt(y)) return false + if(y.add(toBN(100)).lt(x)) return false + + return true +} + +async function assertRevert(txPromise, message = undefined) { + try { + const tx = await txPromise + // console.log("tx succeeded") + assert.isFalse(tx.receipt.status) // when this assert fails, the expected revert didn't occur, i.e. the tx succeeded + } catch (err) { + // console.log("tx failed") + assert.include(err.message, "revert") + + if (message) { + assert.include(err.message, message) + } + } +} \ No newline at end of file diff --git a/packages/contracts/test/B.Protocol/BAMMTest.js b/packages/contracts/test/B.Protocol/BAMMTest.js index c7b409e0c..64651286e 100644 --- a/packages/contracts/test/B.Protocol/BAMMTest.js +++ b/packages/contracts/test/B.Protocol/BAMMTest.js @@ -1,3 +1,4 @@ +const { assert } = require("hardhat") const deploymentHelper = require("./../../utils/deploymentHelpers.js") const testHelpers = require("./../../utils/testHelpers.js") const th = testHelpers.TestHelper @@ -7,9 +8,12 @@ const mv = testHelpers.MoneyValues const timeValues = testHelpers.TimeValues const TroveManagerTester = artifacts.require("TroveManagerTester") -const LUSDToken = artifacts.require("LUSDToken") +const MockToken = artifacts.require("MockToken") +const MockCToken = artifacts.require("MockCToken") const NonPayable = artifacts.require('NonPayable.sol') const BAMM = artifacts.require("BAMM.sol") +const Admin = artifacts.require("Admin") +const MockWithAdmin = artifacts.require("MockWithAdmin") const BLens = artifacts.require("BLens.sol") const ChainlinkTestnet = artifacts.require("ChainlinkTestnet.sol") @@ -30,33 +34,41 @@ contract('BAMM', async accounts => { u1, u2, u3, u4, u5, v1, v2, v3, v4, v5, frontEnd_1, frontEnd_2, frontEnd_3, - bammOwner + bammOwner, + shmuel, yaron, eitan ] = accounts; const [bountyAddress, lpRewardsAddress, multisig] = accounts.slice(997, 1000) const frontEnds = [frontEnd_1, frontEnd_2, frontEnd_3] let contracts - let priceFeed + + let priceFeed0 + let priceFeed1 + let priceFeed2 + let lusdToken - let sortedTroves - let troveManager - let activePool - let stabilityPool let bamm let lens let chainlink - let defaultPool - let borrowerOperations - let lqtyToken - let communityIssuance let gasPriceInWei + let cLUSD + + let token0 + let token1 + let token2 + + let cToken0 + let cToken1 + let cToken2 const feePool = "0x1000000000000000000000000000000000000001" - const getOpenTroveLUSDAmount = async (totalDebt) => th.getOpenTroveLUSDAmount(contracts, totalDebt) - const openTrove = async (params) => th.openTrove(contracts, params) + const isWithin99Percent = (onePercent, b)=> { + return (b.gte(onePercent.mul(toBN(99))) && b.lte(onePercent.mul(toBN(100)))) + } + //const assertRevert = th.assertRevert describe("BAMM", async () => { @@ -66,66 +78,140 @@ contract('BAMM', async accounts => { }) beforeEach(async () => { - contracts = await deploymentHelper.deployLiquityCore() - contracts.troveManager = await TroveManagerTester.new() - contracts.lusdToken = await LUSDToken.new( - contracts.troveManager.address, - contracts.stabilityPool.address, - contracts.borrowerOperations.address - ) - const LQTYContracts = await deploymentHelper.deployLQTYContracts(bountyAddress, lpRewardsAddress, multisig) - - priceFeed = contracts.priceFeedTestnet - lusdToken = contracts.lusdToken - sortedTroves = contracts.sortedTroves - troveManager = contracts.troveManager - activePool = contracts.activePool - stabilityPool = contracts.stabilityPool - defaultPool = contracts.defaultPool - borrowerOperations = contracts.borrowerOperations - hintHelpers = contracts.hintHelpers - - lqtyToken = LQTYContracts.lqtyToken - communityIssuance = LQTYContracts.communityIssuance - - await deploymentHelper.connectLQTYContracts(LQTYContracts) - await deploymentHelper.connectCoreContracts(contracts, LQTYContracts) - await deploymentHelper.connectLQTYContractsToCore(LQTYContracts, contracts) - - // Register 3 front ends - //await th.registerFrontEnds(frontEnds, stabilityPool) - // deploy BAMM - chainlink = await ChainlinkTestnet.new(priceFeed.address) + lusdToken = await MockToken.new(7) + cLUSD = await MockCToken.new(lusdToken.address, false) + + token0 = await MockToken.new(12) + token1 = await MockToken.new(13) + token2 = await MockToken.new(4) + + cToken0 = await MockCToken.new(token0.address, false) + cToken1 = await MockCToken.new(token1.address, false) + cToken2 = await MockCToken.new(token2.address, false) + + priceFeed0 = await ChainlinkTestnet.new() + priceFeed1 = await ChainlinkTestnet.new() + priceFeed2 = await ChainlinkTestnet.new() + + bamm = await BAMM.new(lusdToken.address, + cLUSD.address, + 400, + feePool, + {from: bammOwner}) + + await bamm.addCollateral(cToken0.address, priceFeed0.address, {from: bammOwner}) + await bamm.addCollateral(cToken1.address, priceFeed1.address, {from: bammOwner}) + await bamm.addCollateral(cToken2.address, priceFeed2.address, {from: bammOwner}) + }) + + it("liquidateBorrow bamm", async () => { + await bamm.setParams(20, 100, 50, {from: bammOwner}) + const liquidationAmount = toBN(dec(1000, 7)) + const collateralAmount = toBN(dec(3000, 12)) + await lusdToken.mintToken(shmuel, liquidationAmount, {from: shmuel}) + await lusdToken.approve(bamm.address, liquidationAmount, {from: shmuel}) + await bamm.deposit(liquidationAmount, {from: shmuel}) + + await token0.mintToken(yaron, collateralAmount) + await token0.approve(cToken0.address, collateralAmount, {from: yaron}) + await cToken0.depositToken(collateralAmount, {from: yaron}) + + const callerToken0BalanceBefore = toBN(await token0.balanceOf(shmuel)) + + const expectedCallerFee = collateralAmount.div(toBN(200)) // 0.5% + await cLUSD.setPrice(toBN(dec(3, 18 + 12 - 7))) + + await bamm.liquidateBorrow(yaron, liquidationAmount, cToken0.address, {from: shmuel}) + + const callerToken0BalanceAfter = toBN(await token0.balanceOf(shmuel)) + const bammToken0Balance = await token0.balanceOf(bamm.address) + const expectdToken0Balance = collateralAmount.sub(expectedCallerFee) + assert.equal(expectdToken0Balance.toString(), bammToken0Balance.toString()) + const bammLusdBalance = await lusdToken.balanceOf(bamm.address) + assert.equal(bammLusdBalance.toString(), "0") + const callerToken0Delta = callerToken0BalanceAfter.sub(callerToken0BalanceBefore) + assert.equal(expectedCallerFee.toString(), callerToken0Delta.toString()) + }) - const kickbackRate_F1 = toBN(dec(5, 17)) // F1 kicks 50% back to depositor - await stabilityPool.registerFrontEnd(kickbackRate_F1, { from: frontEnd_1 }) + it("liquidateLUSD with LUSD", async () => { + await bamm.setParams(20, 100, 50, {from: bammOwner}) + const liquidationAmount = toBN(dec(1000, 7)) + const collateralAmount = toBN(dec(2000, 7)) + await lusdToken.mintToken(shmuel, liquidationAmount, {from: shmuel}) + await lusdToken.approve(bamm.address, liquidationAmount, {from: shmuel}) + await bamm.deposit(liquidationAmount, {from: shmuel}) - bamm = await BAMM.new(chainlink.address, stabilityPool.address, lusdToken.address, lqtyToken.address, 400, feePool, frontEnd_1, {from: bammOwner}) - lens = await BLens.new() + await lusdToken.mintToken(yaron, collateralAmount) + await lusdToken.approve(cLUSD.address, collateralAmount, {from: yaron}) + await cLUSD.depositToken(collateralAmount, {from: yaron}) + + // in LUSD <> LUSD the fee is from the + const expectedCallerFee = liquidationAmount.div(toBN(200)) // 0.5% + await cLUSD.setPrice(toBN(dec(2, 18))) + + const shmuelLusdBefore = await lusdToken.balanceOf(shmuel) + await bamm.liquidateBorrow(yaron, liquidationAmount, cLUSD.address, {from: shmuel}) + const shmuelLusdAfter = await lusdToken.balanceOf(shmuel) + + assert.equal(expectedCallerFee.toString(), shmuelLusdAfter.sub(shmuelLusdBefore).toString()) + + const bammLusdBalance = await lusdToken.balanceOf(bamm.address) + const expectdLusdBalance = collateralAmount.sub(expectedCallerFee) + assert.equal(expectdLusdBalance.toString(), bammLusdBalance.toString()) + }) + + it("canLiquidate", async ()=> { + const liquidationAmount = toBN(dec(1000, 7)) + + await lusdToken.mintToken(shmuel, liquidationAmount, {from: shmuel}) + await lusdToken.approve(bamm.address, liquidationAmount, {from: shmuel}) + await bamm.deposit(liquidationAmount, {from: shmuel}) + + // valid liquidations + let canLiquidate = await bamm.canLiquidate(cLUSD.address, cToken0.address, liquidationAmount) + assert.equal(canLiquidate, true) + canLiquidate = await bamm.canLiquidate(cLUSD.address, cToken1.address, liquidationAmount) + assert.equal(canLiquidate, true) + canLiquidate = await bamm.canLiquidate(cLUSD.address, cToken2.address, liquidationAmount) + assert.equal(canLiquidate, true) + + // invalid ctoken + const cToken3 = await MockCToken.new((await MockToken.new(1)).address, false) + + canLiquidate = await bamm.canLiquidate(cLUSD.address, cToken3.address, liquidationAmount) + assert.equal(canLiquidate, false) + + // amount exceeded + canLiquidate = await bamm.canLiquidate(cLUSD.address, cToken2.address, liquidationAmount.add(toBN(1))) + assert.equal(canLiquidate, false) + + // borrow = collateral + canLiquidate = await bamm.canLiquidate(cLUSD.address, cLUSD.address, liquidationAmount) + assert.equal(canLiquidate, true) }) // --- provideToSP() --- // increases recorded LUSD at Stability Pool it("deposit(): increases the Stability Pool LUSD balance", async () => { // --- SETUP --- Give Alice a least 200 - await openTrove({ extraLUSDAmount: toBN(200), ICR: toBN(dec(2, 18)), extraParams: { from: alice } }) + await lusdToken.mintToken(alice, toBN(200), {from: alice}) // --- TEST --- await lusdToken.approve(bamm.address, toBN(200), { from: alice }) await bamm.deposit(toBN(200), { from: alice }) // check LUSD balances after - const stabilityPool_LUSD_After = await stabilityPool.getTotalLUSDDeposits() - assert.equal(stabilityPool_LUSD_After, 200) + const bamm_LUSD_After = await lusdToken.balanceOf(bamm.address) + assert.equal(bamm_LUSD_After, 200) }) // --- provideToSP() --- // increases recorded LUSD at Stability Pool it("deposit(): two users deposit, check their share", async () => { - // --- SETUP --- Give Alice a least 200 - await openTrove({ extraLUSDAmount: toBN(200), ICR: toBN(dec(2, 18)), extraParams: { from: alice } }) - await openTrove({ extraLUSDAmount: toBN(200), ICR: toBN(dec(2, 18)), extraParams: { from: whale } }) + // --- SETUP --- Give Alice and whale at least 200 + await lusdToken.mintToken(alice, toBN(200), {from: alice}) + await lusdToken.mintToken(whale, toBN(200), {from: alice}) // --- TEST --- await lusdToken.approve(bamm.address, toBN(200), { from: alice }) @@ -134,8 +220,8 @@ contract('BAMM', async accounts => { await bamm.deposit(toBN(200), { from: whale }) // check LUSD balances after1 - const whaleShare = await bamm.stake(whale) - const aliceShare = await bamm.stake(alice) + const whaleShare = await bamm.balanceOf(whale) + const aliceShare = await bamm.balanceOf(alice) assert.equal(whaleShare.toString(), aliceShare.toString()) }) @@ -143,9 +229,9 @@ contract('BAMM', async accounts => { // --- provideToSP() --- // increases recorded LUSD at Stability Pool it("deposit(): two users deposit, one withdraw. check their share", async () => { - // --- SETUP --- Give Alice a least 200 - await openTrove({ extraLUSDAmount: toBN(200), ICR: toBN(dec(2, 18)), extraParams: { from: alice } }) - await openTrove({ extraLUSDAmount: toBN(200), ICR: toBN(dec(2, 18)), extraParams: { from: whale } }) + // --- SETUP --- Give Alice and whale at least 200 + await lusdToken.mintToken(alice, toBN(200), {from: alice}) + await lusdToken.mintToken(whale, toBN(200), {from: alice}) // --- TEST --- await lusdToken.approve(bamm.address, toBN(200), { from: alice }) @@ -154,8 +240,8 @@ contract('BAMM', async accounts => { await bamm.deposit(toBN(100), { from: whale }) // check LUSD balances after1 - const whaleShare = await bamm.stake(whale) - const aliceShare = await bamm.stake(alice) + const whaleShare = await bamm.balanceOf(whale) + const aliceShare = await bamm.balanceOf(alice) assert.equal(whaleShare.mul(toBN(2)).toString(), aliceShare.toString()) @@ -163,619 +249,479 @@ contract('BAMM', async accounts => { const shareToWithdraw = whaleShare.div(toBN(2)); await bamm.withdraw(shareToWithdraw, { from: whale }); - const newWhaleShare = await bamm.stake(whale) + const newWhaleShare = await bamm.balanceOf(whale) assert.equal(newWhaleShare.mul(toBN(2)).toString(), whaleShare.toString()) const whaleBalanceAfter = await lusdToken.balanceOf(whale) assert.equal(whaleBalanceAfter.sub(whaleBalanceBefore).toString(), 50) }) - it('rebalance scenario', async () => { + it('test share with collateral', async () => { // --- SETUP --- - // Whale opens Trove and deposits to SP - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(2, 18)), extraParams: { from: whale, value: dec(50, 'ether') } }) + await lusdToken.mintToken(whale, toBN(dec(100000, 7)), {from: whale}) + await lusdToken.mintToken(A, toBN(dec(100000, 7)), {from: A}) + await lusdToken.mintToken(B, toBN(dec(100000, 7)), {from: B}) + const whaleLUSD = await lusdToken.balanceOf(whale) await lusdToken.approve(bamm.address, whaleLUSD, { from: whale }) - bamm.deposit(whaleLUSD, { from: whale } ) + await lusdToken.approve(bamm.address, toBN(dec(6000, 7)), { from: A }) + await bamm.deposit(toBN(dec(6000, 7)), { from: A } ) - // 2 Troves opened, each withdraws minimum debt - await openTrove({ extraLUSDAmount: 0, ICR: toBN(dec(2, 18)), extraParams: { from: defaulter_1, } }) - await openTrove({ extraLUSDAmount: 0, ICR: toBN(dec(2, 18)), extraParams: { from: defaulter_2, } }) + // send $6k collateral to bamm, mimics liquidations + await token0.mintToken(bamm.address, toBN(dec(1000, 12))) // $3k + await token1.mintToken(bamm.address, toBN(dec(200, 13))) // $1k + await token2.mintToken(bamm.address, toBN(dec(500, 4))) // $2k - // Alice makes Trove and withdraws 100 LUSD - await openTrove({ extraLUSDAmount: toBN(dec(100, 18)), ICR: toBN(dec(5, 18)), extraParams: { from: alice, value: dec(50, 'ether') } }) + // price set so that total collateral is $6k + await priceFeed0.setPrice(dec(3, 18)); + await priceFeed1.setPrice(dec(5, 18)); + await priceFeed2.setPrice(dec(4, 18)); - // price drops: defaulter's Troves fall below MCR, whale doesn't - await priceFeed.setPrice(dec(105, 18)); - console.log("rebalance", (await bamm.fetchPrice()).toString()) + assert.equal(toBN(dec(6000, 7)).toString(), (await lusdToken.balanceOf(bamm.address)).toString()) + const collateralValue = await bamm.getCollateralValue() + assert.equal((collateralValue.value).toString(), toBN(dec(6000, 7)).toString(), "unexpected collateral value") - const SPLUSD_Before = await stabilityPool.getTotalLUSDDeposits() + const totalUsd = toBN(dec(6000 * 2, 7)) - // Troves are closed - await troveManager.liquidate(defaulter_1, { from: owner }) - await troveManager.liquidate(defaulter_2, { from: owner }) + await lusdToken.approve(bamm.address, totalUsd, { from: B }) + await bamm.deposit(totalUsd, { from: B } ) - // Confirm SP has decreased - const SPLUSD_After = await stabilityPool.getTotalLUSDDeposits() - assert.isTrue(SPLUSD_After.lt(SPLUSD_Before)) + assert.equal((await bamm.balanceOf(A)).toString(), (await bamm.balanceOf(B)).toString()) - console.log((await stabilityPool.getCompoundedLUSDDeposit(bamm.address)).toString()) - console.log((await stabilityPool.getDepositorETHGain(bamm.address)).toString()) - const price = await priceFeed.fetchPrice.call() - console.log(price.toString()) + const token0BalBefore = toBN(await token0.balanceOf(A)) + const token1BalBefore = toBN(await token1.balanceOf(A)) + const token2BalBefore = toBN(await token2.balanceOf(A)) - const ammExpectedEth = await bamm.getSwapEthAmount.call(toBN(dec(1, 18))) + const LUSDBefore = await lusdToken.balanceOf(A) - console.log("expected eth amount", ammExpectedEth.ethAmount.toString()) + await bamm.withdraw(await bamm.balanceOf(A), {from: A}) - const rate = await bamm.getConversionRate(lusdToken.address, "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", toBN(dec(1, 18)), 0) - assert.equal(rate.toString(), ammExpectedEth.ethAmount.toString()) + const LUSDAfter = await lusdToken.balanceOf(A) - await lusdToken.approve(bamm.address, toBN(dec(1, 18)), { from: alice }) + const token0BalAfter = toBN(await token0.balanceOf(A)) + const token1BalAfter = toBN(await token1.balanceOf(A)) + const token2BalAfter = toBN(await token2.balanceOf(A)) - const dest = "0xe1A587Ac322da1611DF55b11A6bC8c6052D896cE" // dummy address - //await bamm.swap(toBN(dec(1, 18)), dest, { from: alice }) - await bamm.trade(lusdToken.address, toBN(dec(1, 18)), "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", dest, rate, true, { from: alice }); - const swapBalance = await web3.eth.getBalance(dest) + // LUSD + assert.equal(toBN(dec((6000 + 6000 * 2) / 2, 7)).toString(), LUSDAfter.sub(LUSDBefore).toString()) - assert.equal(swapBalance, ammExpectedEth.ethAmount) + // token 0-2 + assert.equal(toBN(dec(500, 12)).toString(), token0BalAfter.sub(token0BalBefore).toString()) + assert.equal(toBN(dec(100, 13)).toString(), token1BalAfter.sub(token1BalBefore).toString()) + assert.equal(toBN(dec(250, 4)).toString(), token2BalAfter.sub(token2BalBefore).toString()) }) - it("test basic LQTY allocation", async () => { - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(10, 18)), extraParams: { from: whale } }) + it('price exceed max dicount and/or collateral balance', async () => { + await lusdToken.mintToken(A, toBN(dec(100000, 7)), {from: whale}) + await lusdToken.approve(bamm.address, toBN(dec(10000, 7)), { from: A }) + await bamm.deposit(toBN(dec(6000, 7)), { from: A } ) - // A, B, C, open troves - await openTrove({ extraLUSDAmount: toBN(dec(1000, 18)), ICR: toBN(dec(2, 18)), extraParams: { from: A } }) - await openTrove({ extraLUSDAmount: toBN(dec(2000, 18)), ICR: toBN(dec(2, 18)), extraParams: { from: B } }) - await openTrove({ extraLUSDAmount: toBN(dec(3000, 18)), ICR: toBN(dec(2, 18)), extraParams: { from: C } }) - await openTrove({ extraLUSDAmount: toBN(dec(1000, 18)), ICR: toBN(dec(2, 18)), extraParams: { from: D } }) - await openTrove({ extraLUSDAmount: toBN(dec(2000, 18)), ICR: toBN(dec(2, 18)), extraParams: { from: E } }) - await openTrove({ extraLUSDAmount: toBN(dec(3000, 18)), ICR: toBN(dec(2, 18)), extraParams: { from: F } }) - - // D, E provide to bamm, F provide to SP - await lusdToken.approve(bamm.address, dec(1000, 18), { from: D }) - await lusdToken.approve(bamm.address, dec(2000, 18), { from: E }) - await bamm.deposit(dec(1000, 18), { from: D }) - await bamm.deposit(dec(2000, 18), { from: E }) - await stabilityPool.provideToSP(dec(3000, 18), frontEnd_1, { from: F }) - - // Get F1, F2, F3 LQTY balances before, and confirm they're zero - const D_LQTYBalance_Before = await lqtyToken.balanceOf(D) - const E_LQTYBalance_Before = await lqtyToken.balanceOf(E) - const F_LQTYBalance_Before = await lqtyToken.balanceOf(F) - - assert.equal(D_LQTYBalance_Before, '0') - assert.equal(E_LQTYBalance_Before, '0') - assert.equal(F_LQTYBalance_Before, '0') - - await th.fastForwardTime(timeValues.SECONDS_IN_ONE_HOUR, web3.currentProvider) - - const expectdDLqtyDelta = await lens.getUnclaimedLqty.call(D, bamm.address, lqtyToken.address) - const expectdELqtyDelta = await lens.getUnclaimedLqty.call(E, bamm.address, lqtyToken.address) - - // test get user info - // send eth to get non zero eth - await web3.eth.sendTransaction({from: whale, to: bamm.address, value: toBN(dec(3, 18))}) - const userInfo = await lens.getUserInfo.call(D, bamm.address, lqtyToken.address) - //console.log({userInfo}) - assert.equal(userInfo.unclaimedLqty.toString(), expectdDLqtyDelta.toString()) - assert.equal(userInfo.bammUserBalance.toString(), (await bamm.balanceOf(D)).toString()) - assert.equal(userInfo.lusdUserBalance.toString(), dec(1000, 18).toString()) - assert.equal(userInfo.ethUserBalance.toString(), dec(1, 18).toString()) - assert.equal(userInfo.lusdTotal.toString(), dec(3000, 18).toString()) - assert.equal(userInfo.ethTotal.toString(), dec(3, 18).toString()) - - await stabilityPool.withdrawFromSP(0, { from: F }) - await bamm.withdraw(0, { from: D }) - await bamm.withdraw(0, { from: E }) - - // Get F1, F2, F3 LQTY balances after, and confirm they have increased - const D_LQTYBalance_After = await lqtyToken.balanceOf(D) - const E_LQTYBalance_After = await lqtyToken.balanceOf(E) - const F_LQTYBalance_After = await lqtyToken.balanceOf(F) - - assert((await lqtyToken.balanceOf(frontEnd_1)).gt(toBN(0))) - assert.equal(D_LQTYBalance_After.sub(D_LQTYBalance_Before).toString(), expectdDLqtyDelta.toString()) - assert.equal(E_LQTYBalance_After.sub(E_LQTYBalance_Before).toString(), expectdELqtyDelta.toString()) - - assert.equal(D_LQTYBalance_After.add(E_LQTYBalance_After).toString(), F_LQTYBalance_After.toString()) - }) - - it("test share + LQTY fuzzy", async () => { - const ammUsers = [u1, u2, u3, u4, u5] - const userBalance = [0, 0, 0, 0, 0] - const nonAmmUsers = [v1, v2, v3, v4, v5] - - let totalDeposits = 0 - - // test almost equal - assert(almostTheSame(web3.utils.toWei("9999"), web3.utils.toWei("9999"))) - assert(! almostTheSame(web3.utils.toWei("9989"), web3.utils.toWei("9999"))) - - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(10, 18)), extraParams: { from: whale } }) - for(let i = 0 ; i < ammUsers.length ; i++) { - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(10, 18)), extraParams: { from: ammUsers[i] } }) - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(10, 18)), extraParams: { from: nonAmmUsers[i] } }) - - await lusdToken.approve(bamm.address, dec(1000000, 18), { from: ammUsers[i] }) - - const qty = toBN(20000) - totalDeposits += Number(qty.toString()) - userBalance[i] += Number(qty.toString()) - await bamm.deposit(qty, { from: ammUsers[i] }) - await stabilityPool.provideToSP(qty, frontEnd_1, { from: nonAmmUsers[i] }) - } - - for(n = 0 ; n < 10 ; n++) { - for(let i = 0 ; i < ammUsers.length ; i++) { - await th.fastForwardTime(timeValues.SECONDS_IN_ONE_HOUR * (i + n + 1), web3.currentProvider) - assert(almostTheSame((await lqtyToken.balanceOf(ammUsers[i])).toString(), (await lqtyToken.balanceOf(nonAmmUsers[i])).toString())) - assert.equal((await lusdToken.balanceOf(ammUsers[i])).toString(), (await lusdToken.balanceOf(nonAmmUsers[i])).toString()) - - const qty = (i+1) * 1000 + (n+1)*1000 // small number as 0 decimals - if((n*7 + i*3) % 2 === 0) { - const share = (await bamm.total()).mul(toBN(qty)).div(toBN(totalDeposits)) - console.log("withdraw", i, {qty}, {totalDeposits}, share.toString()) - await bamm.withdraw(share.toString(), { from: ammUsers[i] }) - await stabilityPool.withdrawFromSP(qty, { from: nonAmmUsers[i] }) - - totalDeposits -= qty - userBalance[i] -= qty - } - else { - console.log("deposit", i) - await bamm.deposit(qty, { from: ammUsers[i]} ) - await stabilityPool.provideToSP(qty, frontEnd_1, { from: nonAmmUsers[i] }) - - totalDeposits += qty - userBalance[i] += qty - } - - const totalSupply = await bamm.totalSupply() - const userSupply = await bamm.balanceOf(ammUsers[i]) - // userSup / totalSupply = userBalance / totalDeposits - assert.equal(userSupply.mul(toBN(totalDeposits)).toString(), toBN(userBalance[i]).mul(totalSupply).toString()) - - await th.fastForwardTime(timeValues.SECONDS_IN_ONE_HOUR * (i + n + 1), web3.currentProvider) - - await bamm.withdraw(0, { from: ammUsers[i] }) - await stabilityPool.withdrawFromSP(0, { from: nonAmmUsers[i] }) - - await bamm.withdraw(0, { from: ammUsers[0] }) - await stabilityPool.withdrawFromSP(0, { from: nonAmmUsers[0] }) - - assert.equal((await lusdToken.balanceOf(ammUsers[i])).toString(), (await lusdToken.balanceOf(nonAmmUsers[i])).toString()) - assert(almostTheSame((await lqtyToken.balanceOf(ammUsers[i])).toString(), (await lqtyToken.balanceOf(nonAmmUsers[i])).toString())) - assert(almostTheSame((await lqtyToken.balanceOf(ammUsers[0])).toString(), (await lqtyToken.balanceOf(nonAmmUsers[0])).toString())) - } - } - - console.log("get all lqty") - for(let i = 0 ; i < ammUsers.length ; i++) { - await bamm.withdraw(0, { from: ammUsers[i] }) - await stabilityPool.withdrawFromSP(0, { from: nonAmmUsers[i] }) - } - - for(let i = 0 ; i < ammUsers.length ; i++) { - assert(almostTheSame((await lqtyToken.balanceOf(ammUsers[i])).toString(), (await lqtyToken.balanceOf(nonAmmUsers[i])).toString())) - } - }) - - it("test complex LQTY allocation", async () => { - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(10, 18)), extraParams: { from: whale } }) - - // A, B, C, open troves - await openTrove({ extraLUSDAmount: toBN(dec(1000, 18)), ICR: toBN(dec(2, 18)), extraParams: { from: A } }) - await openTrove({ extraLUSDAmount: toBN(dec(3000, 18)), ICR: toBN(dec(2, 18)), extraParams: { from: B } }) - await openTrove({ extraLUSDAmount: toBN(dec(3000, 18)), ICR: toBN(dec(2, 18)), extraParams: { from: C } }) - await openTrove({ extraLUSDAmount: toBN(dec(1000, 18)), ICR: toBN(dec(2, 18)), extraParams: { from: D } }) - await openTrove({ extraLUSDAmount: toBN(dec(2000, 18)), ICR: toBN(dec(2, 18)), extraParams: { from: E } }) - await openTrove({ extraLUSDAmount: toBN(dec(3000, 18)), ICR: toBN(dec(2, 18)), extraParams: { from: F } }) - - const A_LQTYBalance_Before = await lqtyToken.balanceOf(A) - const D_LQTYBalance_Before = await lqtyToken.balanceOf(D) - const E_LQTYBalance_Before = await lqtyToken.balanceOf(E) - const F_LQTYBalance_Before = await lqtyToken.balanceOf(F) - - assert.equal(A_LQTYBalance_Before, '0') - assert.equal(D_LQTYBalance_Before, '0') - assert.equal(E_LQTYBalance_Before, '0') - assert.equal(F_LQTYBalance_Before, '0') - - // D, E provide to bamm, F provide to SP - await lusdToken.approve(bamm.address, dec(1000, 18), { from: D }) - await lusdToken.approve(bamm.address, dec(2000, 18), { from: E }) - await lusdToken.approve(bamm.address, dec(3000, 18), { from: F }) - - await bamm.deposit(dec(1000, 18), { from: D }) - await bamm.deposit(dec(2000, 18), { from: E }) - //await bamm.deposit(dec(3000, 18), { from: F }) - - await bamm.withdraw(0, { from: D }) - console.log((await lqtyToken.balanceOf(D)).toString()) - - console.log("share:", (await bamm.share.call()).toString()) - console.log("stake D:", (await bamm.stake(D)).toString()) - console.log("stake E:", (await bamm.stake(E)).toString()) + // price drops: defaulter's Troves fall below MCR, whale doesn't + await priceFeed0.setPrice(dec(105, 18)); - await stabilityPool.provideToSP(dec(1000, 18), frontEnd_1, { from: A }) + // 4k liquidations + assert.equal(toBN(dec(6000, 7)).toString(), (await lusdToken.balanceOf(bamm.address)).toString()) - await th.fastForwardTime(timeValues.SECONDS_IN_ONE_HOUR, web3.currentProvider) + // send ETH to bamm, mimics liquidations + const ethGains = web3.utils.toBN("39799999999999") + await token0.mintToken(bamm.address, ethGains) - await bamm.deposit(dec(3000, 18), { from: F }) - await stabilityPool.provideToSP(dec(3000, 18), frontEnd_1, { from: B }) + // without fee + await bamm.setParams(20, 0, 0, {from: bammOwner}) + const price = await bamm.getSwapAmount(dec(105, 7), token0.address) + assert.equal(price.toString(), dec(104, 12 - 2).toString()) - await stabilityPool.withdrawFromSP(0, { from: A }) - console.log("lqty A", (await lqtyToken.balanceOf(A)).toString()) + // with fee - should be the same, as fee is on the lusd + await bamm.setParams(20, 100, 0, {from: bammOwner}) + const priceWithFee = await bamm.getSwapAmount(dec(105, 7), token0.address) + assert.equal(price.toString(), dec(104, 12 - 2).toString()) - await th.fastForwardTime(timeValues.SECONDS_IN_ONE_HOUR, web3.currentProvider) + // without fee + await bamm.setParams(20, 0, 0, {from: bammOwner}) + const priceDepleted = await bamm.getSwapAmount(dec(1050000000000000, 7), token0.address) + assert.equal(priceDepleted.toString(), ethGains.toString()) + + // with fee - should be the same + await bamm.setParams(20, 100, 0, {from: bammOwner}) + const priceDepletedWithFee = await bamm.getSwapAmount(dec(1050000000000000, 7), token0.address) + assert.equal(priceDepletedWithFee.toString(), ethGains.toString()) + }) - console.log("share:", (await bamm.share()).toString()) - console.log("stake D:", (await bamm.stake(D)).toString()) - console.log("stake E:", (await bamm.stake(E)).toString()) - console.log("stake F:", (await bamm.stake(F)).toString()) + it('test getSwapAmount', async () => { + await lusdToken.mintToken(A, toBN(dec(100000, 7)), {from: whale}) + await lusdToken.approve(bamm.address, toBN(dec(10000, 7)), { from: A }) + await bamm.deposit(toBN(dec(6000, 7)), { from: A } ) - await stabilityPool.withdrawFromSP(0, { from: A }) - console.log("lqty A", (await lqtyToken.balanceOf(A)).toString()) + await priceFeed0.setPrice(dec(105, 18), {from: bammOwner}); + await priceFeed1.setPrice(dec(90, 18), {from: bammOwner}); + await priceFeed2.setPrice(dec(120, 18), {from: bammOwner}); - await stabilityPool.withdrawFromSP(0, { from: A }) - await stabilityPool.withdrawFromSP(0, { from: B }) - await bamm.withdraw(0, { from: D }) - await bamm.withdraw(0, { from: E }) - await bamm.withdraw(0, { from: F }) + assert.equal(toBN(dec(6000, 7)).toString(), (await lusdToken.balanceOf(bamm.address)).toString()) - console.log("lqty D", (await lqtyToken.balanceOf(D)).toString()) - console.log("lqty E", (await lqtyToken.balanceOf(E)).toString()) - console.log("lqty F", (await lqtyToken.balanceOf(F)).toString()) + // send ETH to bamm, mimics liquidations. total of 420 usd + await token0.mintToken(bamm.address, toBN(dec(2, 12))) + await token1.mintToken(bamm.address, toBN(dec(1, 13))) + await token2.mintToken(bamm.address, toBN(dec(1, 4))) - console.log("share:", (await bamm.share()).toString()) - console.log("stake D:", (await bamm.stake(D)).toString()) - console.log("stake E:", (await bamm.stake(E)).toString()) - console.log("stake F:", (await bamm.stake(F)).toString()) - - // Get F1, F2, F3 LQTY balances after, and confirm they have increased - const A_LQTYBalance_After = await lqtyToken.balanceOf(A) - const B_LQTYBalance_After = await lqtyToken.balanceOf(B) - const D_LQTYBalance_After = await lqtyToken.balanceOf(D) - const E_LQTYBalance_After = await lqtyToken.balanceOf(E) - const F_LQTYBalance_After = await lqtyToken.balanceOf(F) - - assert.equal(D_LQTYBalance_After.toString(), A_LQTYBalance_After.toString()) - assert.equal(E_LQTYBalance_After.toString(), A_LQTYBalance_After.mul(toBN(2)).toString()) - assert.equal(F_LQTYBalance_After.toString(), B_LQTYBalance_After.toString()) - }) + const lusdQty = dec(105, 7) + const expectedReturn = await bamm.getReturn(lusdQty, dec(6000, 7), toBN(dec(6000, 7)).add(toBN(dec(2 * 420, 7))), 200) - it('test share with ether', async () => { - // --- SETUP --- + // without fee + await bamm.setParams(200, 0, 0, {from: bammOwner}) + const priceWithoutFee = await bamm.getSwapAmount(lusdQty, token0.address) + assert.equal(priceWithoutFee.toString(), expectedReturn.mul(toBN(dec(1,12 - 7))).div(toBN(105)).toString()) + }) - // Whale opens Trove and deposits to SP - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: whale, value: dec(50, 'ether') } }) - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: A } }) - await openTrove({ extraLUSDAmount: toBN(dec(20000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: B } }) + it('test fetch price', async () => { + await priceFeed0.setPrice(dec(666, 18)); + await priceFeed1.setPrice(dec(333, 18)); + await priceFeed2.setPrice(dec(111, 18)); - const whaleLUSD = await lusdToken.balanceOf(whale) - await lusdToken.approve(bamm.address, whaleLUSD, { from: whale }) - await lusdToken.approve(bamm.address, toBN(dec(10000, 18)), { from: A }) - await bamm.deposit(toBN(dec(10000, 18)), { from: A } ) + assert.equal((await bamm.fetchPrice(token0.address)).toString(), dec(666, 18 - (12 - 7))) + assert.equal((await bamm.fetchPrice(token1.address)).toString(), dec(333, 18 - (13 - 7))) + assert.equal((await bamm.fetchPrice(token2.address)).toString(), dec(111, 18 - ( 4 - 7))) + + await priceFeed2.setDecimals(2) + await priceFeed2.setPrice(dec(111, 2)); + assert.equal((await bamm.fetchPrice(token2.address)).toString(), dec(111, 18 - ( 4 - 7))) - // 2 Troves opened, each withdraws minimum debt - await openTrove({ extraLUSDAmount: 0, ICR: toBN(dec(2, 18)), extraParams: { from: defaulter_1, } }) - await openTrove({ extraLUSDAmount: 0, ICR: toBN(dec(2, 18)), extraParams: { from: defaulter_2, } }) + await priceFeed0.setTimestamp(888) + assert.equal((await bamm.fetchPrice(token0.address)).toString(), "0") + }) - // price drops: defaulter's Troves fall below MCR, whale doesn't - await priceFeed.setPrice(dec(105, 18)); + it('test swap 12 decimals', async () => { + await lusdToken.mintToken(A, toBN(dec(100000, 7)), {from: whale}) + await lusdToken.mintToken(whale, toBN(dec(100000, 7)), {from: whale}) - // Troves are closed - await troveManager.liquidate(defaulter_1, { from: owner }) - await troveManager.liquidate(defaulter_2, { from: owner }) + await lusdToken.approve(bamm.address, toBN(dec(10000, 7)), { from: A }) + await lusdToken.approve(bamm.address, toBN(dec(10000, 7)), { from: whale }) - // 4k liquidations - assert.equal(toBN(dec(6000, 18)).toString(), (await stabilityPool.getCompoundedLUSDDeposit(bamm.address)).toString()) - const ethGains = web3.utils.toBN("39799999999999999975") - //console.log(ethGains.toString(), (await stabilityPool.getDepositorETHGain(bamm.address)).toString()) + await bamm.deposit(toBN(dec(6000, 7)), { from: A } ) + assert.equal(toBN(dec(6000, 7)).toString(), (await lusdToken.balanceOf(bamm.address)).toString()) - // send some ETH to simulate partial rebalance - await web3.eth.sendTransaction({from: whale, to: bamm.address, value: toBN(dec(1, 18))}) - assert.equal(toBN(await web3.eth.getBalance(bamm.address)).toString(), toBN(dec(1, 18)).toString()) + // send ETH to bamm, mimics liquidations. total of 420 usd + await priceFeed0.setPrice(dec(105, 18), {from: bammOwner}); + await priceFeed1.setPrice(dec(90, 18), {from: bammOwner}); + await priceFeed2.setPrice(dec(120, 18), {from: bammOwner}); + + await token0.mintToken(bamm.address, toBN(dec(2, 12))) + await token1.mintToken(bamm.address, toBN(dec(1, 13))) + await token2.mintToken(bamm.address, toBN(dec(1, 4))) - const totalEth = ethGains.add(toBN(dec(1, 18))) - const totalUsd = toBN(dec(6000, 18)).add(totalEth.mul(toBN(105))) + // with fee + await bamm.setParams(20, 100, 0, {from: bammOwner}) + const priceWithFee = await bamm.getSwapAmount(dec(105, 7), token0.address) - await lusdToken.approve(bamm.address, totalUsd, { from: B }) - await bamm.deposit(totalUsd, { from: B } ) + await lusdToken.approve(bamm.address, dec(105,7), {from: whale}) + const dest = "0xdEADBEEF00AA81bBCF694bC5c05A397F5E5658D5" - assert.equal((await bamm.balanceOf(A)).toString(), (await bamm.balanceOf(B)).toString()) + await assertRevert(bamm.swap(dec(105,7), token0.address, priceWithFee.add(toBN(1)), dest, {from: whale}), 'swap: low return') + await bamm.swap(dec(105,7), token0.address, priceWithFee, dest, {from: whale}) - const ethBalanceBefore = toBN(await web3.eth.getBalance(A)) - const LUSDBefore = await lusdToken.balanceOf(A) - await bamm.withdraw(await bamm.balanceOf(A), {from: A, gasPrice: 0}) - const ethBalanceAfter = toBN(await web3.eth.getBalance(A)) - const LUSDAfter = await lusdToken.balanceOf(A) + const fees = toBN(dec(105,7)).div(toBN(100)) + + // check lusd balance + assert.equal(toBN(dec(6105, 7)).toString(), (await lusdToken.balanceOf(bamm.address)).add(fees).toString()) - const withdrawUsdValue = LUSDAfter.sub(LUSDBefore).add((ethBalanceAfter.sub(ethBalanceBefore)).mul(toBN(105))) - assert(in100WeiRadius(withdrawUsdValue.toString(), totalUsd.toString())) + // check eth balance + assert.equal((await token0.balanceOf(dest)).toString(), priceWithFee.toString()) + assert.equal("1005498373333", priceWithFee.toString()) - assert(in100WeiRadius("10283999999999999997375", "10283999999999999997322")) - assert(! in100WeiRadius("10283999999999999996375", "10283999999999999997322")) + // check fees + assert.equal((await lusdToken.balanceOf(await bamm.feePool())).toString(), fees) }) - it('price exceed max dicount and/or eth balance', async () => { - // --- SETUP --- + it('test swap 4 decimals', async () => { + await lusdToken.mintToken(A, toBN(dec(100000, 7)), {from: whale}) + await lusdToken.mintToken(whale, toBN(dec(100000, 7)), {from: whale}) - // Whale opens Trove and deposits to SP - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: whale, value: dec(50, 'ether') } }) - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: A } }) - await openTrove({ extraLUSDAmount: toBN(dec(20000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: B } }) - - const whaleLUSD = await lusdToken.balanceOf(whale) - await lusdToken.approve(bamm.address, whaleLUSD, { from: whale }) - await lusdToken.approve(bamm.address, toBN(dec(10000, 18)), { from: A }) - await bamm.deposit(toBN(dec(10000, 18)), { from: A } ) + await lusdToken.approve(bamm.address, toBN(dec(10000, 7)), { from: A }) + await lusdToken.approve(bamm.address, toBN(dec(10000, 7)), { from: whale }) - // 2 Troves opened, each withdraws minimum debt - await openTrove({ extraLUSDAmount: 0, ICR: toBN(dec(2, 18)), extraParams: { from: defaulter_1, } }) - await openTrove({ extraLUSDAmount: 0, ICR: toBN(dec(2, 18)), extraParams: { from: defaulter_2, } }) + await bamm.deposit(toBN(dec(6000, 7)), { from: A } ) + assert.equal(toBN(dec(6000, 7)).toString(), (await lusdToken.balanceOf(bamm.address)).toString()) + // send ETH to bamm, mimics liquidations. total of 420 usd + await priceFeed0.setPrice(dec(20, 18), {from: bammOwner}); + await priceFeed1.setPrice(dec(85, 18), {from: bammOwner}); + await priceFeed2.setPrice(dec(105, 18), {from: bammOwner}); + + await token0.mintToken(bamm.address, toBN(dec(1, 12))) + await token1.mintToken(bamm.address, toBN(dec(1, 13))) + await token2.mintToken(bamm.address, toBN(dec(3, 4))) - // price drops: defaulter's Troves fall below MCR, whale doesn't - await priceFeed.setPrice(dec(105, 18)); + // with fee + await bamm.setParams(20, 100, 0, {from: bammOwner}) + const priceWithFee = await bamm.getSwapAmount(dec(105, 7), token2.address) - // Troves are closed - await troveManager.liquidate(defaulter_1, { from: owner }) - await troveManager.liquidate(defaulter_2, { from: owner }) + await lusdToken.approve(bamm.address, dec(105,7), {from: whale}) + const dest = "0xdEADBEEF00AA81bBCF694bC5c05A397F5E5658D5" - // 4k liquidations - assert.equal(toBN(dec(6000, 18)).toString(), (await stabilityPool.getCompoundedLUSDDeposit(bamm.address)).toString()) - const ethGains = web3.utils.toBN("39799999999999999975") + await assertRevert(bamm.swap(dec(105,7), token2.address, priceWithFee.add(toBN(1)), dest, {from: whale}), 'swap: low return') + await bamm.swap(dec(105,7), token2.address, priceWithFee, dest, {from: whale}) - // without fee - await bamm.setParams(20, 0, {from: bammOwner}) - const price = await bamm.getSwapEthAmount(dec(105, 18)) - assert.equal(price.ethAmount.toString(), dec(104, 18-2).toString()) + const fees = toBN(dec(105,7)).div(toBN(100)) - // with fee - await bamm.setParams(20, 100, {from: bammOwner}) - const priceWithFee = await bamm.getSwapEthAmount(dec(105, 18)) - assert.equal(priceWithFee.ethAmount.toString(), dec(10296, 18-4).toString()) + // check lusd balance + assert.equal(toBN(dec(6105, 7)).toString(), (await lusdToken.balanceOf(bamm.address)).add(fees).toString()) - // without fee - await bamm.setParams(20, 0, {from: bammOwner}) - const priceDepleted = await bamm.getSwapEthAmount(dec(1050000000000000, 18)) - assert.equal(priceDepleted.ethAmount.toString(), ethGains.toString()) + // check eth balance + assert.equal((await token2.balanceOf(dest)).toString(), priceWithFee.toString()) + assert.equal("10054", priceWithFee.toString()) - // with fee - await bamm.setParams(20, 100, {from: bammOwner}) - const priceDepletedWithFee = await bamm.getSwapEthAmount(dec(1050000000000000, 18)) - assert.equal(priceDepletedWithFee.ethAmount.toString(), ethGains.mul(toBN(99)).div(toBN(100))) - }) + // check fees + assert.equal((await lusdToken.balanceOf(await bamm.feePool())).toString(), fees) + }) - it('test getSwapEthAmount', async () => { + it('test set params happy path', async () => { // --- SETUP --- - // Whale opens Trove and deposits to SP - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: whale, value: dec(50, 'ether') } }) - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: A } }) - await openTrove({ extraLUSDAmount: toBN(dec(20000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: B } }) - - const whaleLUSD = await lusdToken.balanceOf(whale) - await lusdToken.approve(bamm.address, whaleLUSD, { from: whale }) - await lusdToken.approve(bamm.address, toBN(dec(10000, 18)), { from: A }) - await bamm.deposit(toBN(dec(10000, 18)), { from: A } ) + await lusdToken.mintToken(A, toBN(dec(100000, 7)), {from: whale}) + await lusdToken.mintToken(whale, toBN(dec(100000, 7)), {from: whale}) - // 2 Troves opened, each withdraws minimum debt - await openTrove({ extraLUSDAmount: 0, ICR: toBN(dec(2, 18)), extraParams: { from: defaulter_1, } }) - await openTrove({ extraLUSDAmount: 0, ICR: toBN(dec(2, 18)), extraParams: { from: defaulter_2, } }) + await lusdToken.approve(bamm.address, toBN(dec(10000, 7)), { from: A }) + await lusdToken.approve(bamm.address, toBN(dec(10000, 7)), { from: whale }) + await bamm.deposit(toBN(dec(6000, 7)), { from: A } ) - // price drops: defaulter's Troves fall below MCR, whale doesn't - await priceFeed.setPrice(dec(105, 18)); + // send ETH to bamm, mimics liquidations. total of 420 usd + await priceFeed0.setPrice(dec(105, 18), {from: bammOwner}); + await priceFeed1.setPrice(dec(90, 18), {from: bammOwner}); + await priceFeed2.setPrice(dec(120, 18), {from: bammOwner}); + + await token0.mintToken(bamm.address, toBN(dec(2, 12))) + await token1.mintToken(bamm.address, toBN(dec(1, 13))) + await token2.mintToken(bamm.address, toBN(dec(1, 4))) - // Troves are closed - await troveManager.liquidate(defaulter_1, { from: owner }) - await troveManager.liquidate(defaulter_2, { from: owner }) + const ethGains = toBN(dec(420,7)) - // 4k liquidations - assert.equal(toBN(dec(6000, 18)).toString(), (await stabilityPool.getCompoundedLUSDDeposit(bamm.address)).toString()) - const ethGains = web3.utils.toBN("39799999999999999975") + const lusdQty = dec(105, 7) + const expectedReturn200 = await bamm.getReturn(lusdQty, dec(6000, 7), toBN(dec(6000, 7)).add(ethGains.mul(toBN(2))), 200) + const expectedReturn190 = await bamm.getReturn(lusdQty, dec(6000, 7), toBN(dec(6000, 7)).add(ethGains.mul(toBN(2))), 190) - const lusdQty = dec(105, 18) - const expectedReturn = await bamm.getReturn(lusdQty, dec(6000, 18), toBN(dec(6000, 18)).add(ethGains.mul(toBN(2 * 105))), 200) + assert(expectedReturn200.toString() !== expectedReturn190.toString()) // without fee - await bamm.setParams(200, 0, {from: bammOwner}) - const priceWithoutFee = await bamm.getSwapEthAmount(lusdQty) - assert.equal(priceWithoutFee.ethAmount.toString(), expectedReturn.mul(toBN(100)).div(toBN(100 * 105)).toString()) + await bamm.setParams(200, 0, 0, {from: bammOwner}) + const priceWithoutFee = await bamm.getSwapAmount(lusdQty, token0.address) + assert.equal(priceWithoutFee.toString(), expectedReturn200.mul(toBN(dec(1,12-7))).div(toBN(105)).toString()) // with fee - await bamm.setParams(200, 100, {from: bammOwner}) - const priceWithFee = await bamm.getSwapEthAmount(lusdQty) - assert.equal(priceWithFee.ethAmount.toString(), expectedReturn.mul(toBN(99)).div(toBN(100 * 105)).toString()) + await bamm.setParams(190, 100, 0, {from: bammOwner}) + const priceWithFee = await bamm.getSwapAmount(lusdQty, token0.address) + assert.equal(priceWithFee.toString(), expectedReturn190.mul(toBN(dec(1,12-7))).div(toBN(105)).toString()) }) - - it('test fetch price', async () => { - await priceFeed.setPrice(dec(666, 18)); - assert.equal(await bamm.fetchPrice(), dec(666, 18)) - - await chainlink.setTimestamp(888) - assert.equal((await bamm.fetchPrice()).toString(), "0") + + it('test set params sad path', async () => { + await assertRevert(bamm.setParams(210, 100, 50, {from: bammOwner}), 'setParams: A too big') + await assertRevert(bamm.setParams(10, 100, 50, {from: bammOwner}), 'setParams: A too small') + await assertRevert(bamm.setParams(10, 101, 50, {from: bammOwner}), 'setParams: fee is too big') + await assertRevert(bamm.setParams(10, 100, 150, {from: bammOwner}), 'setParams: caller fee is too big') + await assertRevert(bamm.setParams(20, 100, 50, {from: B}), 'Ownable: caller is not the owner') }) - it('test swap', async () => { - // --- SETUP --- - - // Whale opens Trove and deposits to SP - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: whale, value: dec(50, 'ether') } }) - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: A } }) - await openTrove({ extraLUSDAmount: toBN(dec(20000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: B } }) + it('ERC20 test', async () => { // transfer is not supported anymore + await lusdToken.mintToken(A, toBN(dec(100000, 7)), {from: A}) + await lusdToken.approve(bamm.address, toBN(dec(100000, 7)), { from: A }) + await bamm.deposit(toBN(dec(100000, 7)), {from: A}) - const whaleLUSD = await lusdToken.balanceOf(whale) - await lusdToken.approve(bamm.address, whaleLUSD, { from: whale }) - await lusdToken.approve(bamm.address, toBN(dec(10000, 18)), { from: A }) - await bamm.deposit(toBN(dec(10000, 18)), { from: A } ) + assert.equal((await bamm.balanceOf(A)).toString(), dec(1,18), "uncexpected bamm balance") - // 2 Troves opened, each withdraws minimum debt - await openTrove({ extraLUSDAmount: 0, ICR: toBN(dec(2, 18)), extraParams: { from: defaulter_1, } }) - await openTrove({ extraLUSDAmount: 0, ICR: toBN(dec(2, 18)), extraParams: { from: defaulter_2, } }) + // try to send bigger qty than balance + await assertRevert(bamm.transfer(B, dec(2,18), {from: A}), "SafeMath: subtraction overflow") + await bamm.transfer(B, dec(4, 17), {from: A}) + assert.equal((await bamm.balanceOf(A)).toString(), dec(6,17)) + assert.equal((await bamm.balanceOf(B)).toString(), dec(4,17)) - // price drops: defaulter's Troves fall below MCR, whale doesn't - await priceFeed.setPrice(dec(105, 18)); + await bamm.approve(C, dec(1,17), {from: A}) + assert.equal((await bamm.allowance(A, C)).toString(), dec(1,17), "unexpected allowance") - // Troves are closed - await troveManager.liquidate(defaulter_1, { from: owner }) - await troveManager.liquidate(defaulter_2, { from: owner }) + await bamm.transferFrom(A, D, dec(4,16), {from: C}) + assert.equal((await bamm.balanceOf(D)).toString(), dec(4,16)) + assert.equal((await bamm.balanceOf(A)).toString(), dec(60 - 4,16)) + assert.equal((await bamm.allowance(A, C)).toString(), dec(6,16), "unexpected allowance") - // 4k liquidations - assert.equal(toBN(dec(6000, 18)).toString(), (await stabilityPool.getCompoundedLUSDDeposit(bamm.address)).toString()) - const ethGains = web3.utils.toBN("39799999999999999975") + // try to send bigger qty than allowance + await assertRevert(bamm.transferFrom(A, B, dec(1,17), {from: C}), "SafeMath: subtraction overflow") - // with fee - await bamm.setParams(20, 100, {from: bammOwner}) - const priceWithFee = await bamm.getSwapEthAmount(dec(105, 18)) - assert.equal(priceWithFee.ethAmount.toString(), dec(10296, 18-4).toString()) - assert.equal(priceWithFee.feeEthAmount.toString(), dec(10400 - 10296, 18-4).toString()) + // make sure that balances are as expected + assert.equal((await bamm.balanceOf(A)).toString(), dec(56,16)) + assert.equal((await bamm.balanceOf(B)).toString(), dec(4,17)) + assert.equal((await bamm.balanceOf(C)).toString(), "0") + assert.equal((await bamm.balanceOf(D)).toString(), dec(4,16)) - await lusdToken.approve(bamm.address, dec(105,18), {from: whale}) - const dest = "0xdEADBEEF00AA81bBCF694bC5c05A397F5E5658D5" + await bamm.withdraw(dec(56, 16), {from: A}) + await bamm.withdraw(dec(4, 17), {from: B}) + await bamm.withdraw(dec(4, 16), {from: D}) - await assertRevert(bamm.swap(dec(105,18), priceWithFee.ethAmount.add(toBN(1)), dest, {from: whale}), 'swap: low return') - await bamm.swap(dec(105,18), priceWithFee.ethAmount, dest, {from: whale}) // TODO - check once with higher value so it will revert + assert.equal((await lusdToken.balanceOf(A)).toString(), dec(100000 * 56 / 100, 7)) + assert.equal((await lusdToken.balanceOf(B)).toString(), dec(100000 * 4 / 10, 7)) + assert.equal((await lusdToken.balanceOf(D)).toString(), dec(100000 * 4 / 100, 7)) + }) - // check lusd balance - assert.equal(toBN(dec(6105, 18)).toString(), (await stabilityPool.getCompoundedLUSDDeposit(bamm.address)).toString()) + it('test remove collateral', async () => { + await priceFeed0.setPrice(dec(1, 18), {from: bammOwner}); + await priceFeed1.setPrice(dec(2, 18), {from: bammOwner}); + await priceFeed2.setPrice(dec(3, 18), {from: bammOwner}); - // check eth balance - assert.equal(await web3.eth.getBalance(dest), priceWithFee.ethAmount) + await token0.mintToken(bamm.address, dec(1,12)) + await token1.mintToken(bamm.address, dec(1,13)) + await token2.mintToken(bamm.address, dec(1,4)) + + assert.equal((await bamm.getCollateralValue()).value.toString(), dec(6, 7)) + assert(await bamm.cTokens(cToken0.address)) + assert(await bamm.cTokens(cToken1.address)) + assert(await bamm.cTokens(cToken2.address)) + assert((await bamm.priceAggregators(token0.address)).toString() !== ZERO_ADDRESS) + assert((await bamm.priceAggregators(token1.address)).toString() !== ZERO_ADDRESS) + assert((await bamm.priceAggregators(token2.address)).toString() !== ZERO_ADDRESS) + + + await bamm.removeCollateral(cToken1.address, {from: bammOwner}) + assert.equal((await bamm.getCollateralValue()).value.toString(), dec(4, 7)) + assert(! await bamm.cTokens(cToken1.address)) + assert.equal((await bamm.priceAggregators(token1.address)).toString(), ZERO_ADDRESS) + + await bamm.removeCollateral(cToken0.address, {from: bammOwner}) + assert.equal((await bamm.getCollateralValue()).value.toString(), dec(3, 7)) + assert(! await bamm.cTokens(cToken0.address)) + assert.equal((await bamm.priceAggregators(token0.address)).toString(), ZERO_ADDRESS) + + await bamm.removeCollateral(cToken2.address, {from: bammOwner}) + assert.equal((await bamm.getCollateralValue()).value.toString(), "0") + assert(! await bamm.cTokens(cToken2.address)) + assert.equal((await bamm.priceAggregators(token2.address)).toString(), ZERO_ADDRESS) + }) - // check fees - assert.equal(await web3.eth.getBalance(feePool), priceWithFee.feeEthAmount) - }) + it('test add collateral sad paths', async () => { + // try to add lusd collateral + await assertRevert(bamm.addCollateral(cLUSD.address, priceFeed0.address, {from: bammOwner}), "addCollateral: LUSD cannot be collateral") - it('test set params happy path', async () => { - // --- SETUP --- + // try to add a token with null price feed + const newToken = await MockToken.new(18) + const newCToken = await MockCToken.new(newToken.address, false) + await assertRevert(bamm.addCollateral(newCToken.address, ZERO_ADDRESS, {from: bammOwner}), "addCollateral: invalid feed") - // Whale opens Trove and deposits to SP - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: whale, value: dec(50, 'ether') } }) - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: A } }) - await openTrove({ extraLUSDAmount: toBN(dec(20000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: B } }) + // try to add existng collateral + await assertRevert(bamm.addCollateral(cToken0.address, priceFeed0.address, {from: bammOwner}), "addCollateral: collateral listed") - const whaleLUSD = await lusdToken.balanceOf(whale) - await lusdToken.approve(bamm.address, whaleLUSD, { from: whale }) - await lusdToken.approve(bamm.address, toBN(dec(10000, 18)), { from: A }) - await bamm.deposit(toBN(dec(10000, 18)), { from: A } ) + // try to add existng underlying + const newCToken2 = await MockCToken.new(token1.address, false) + await assertRevert(bamm.addCollateral(newCToken2.address, priceFeed1.address, {from: bammOwner}), "addCollateral: underlying already added") - // 2 Troves opened, each withdraws minimum debt - await openTrove({ extraLUSDAmount: 0, ICR: toBN(dec(2, 18)), extraParams: { from: defaulter_1, } }) - await openTrove({ extraLUSDAmount: 0, ICR: toBN(dec(2, 18)), extraParams: { from: defaulter_2, } }) + // try to add as non owner + await assertRevert(bamm.addCollateral(newCToken.address, priceFeed0.address, {from: shmuel}), "Ownable: caller is not the owner") + }) + it('test get collateral value sad paths', async () => { + await priceFeed0.setPrice(dec(1, 18), {from: bammOwner}); + await priceFeed1.setPrice(dec(2, 18), {from: bammOwner}); + await priceFeed2.setPrice(dec(3, 18), {from: bammOwner}); - // price drops: defaulter's Troves fall below MCR, whale doesn't - await priceFeed.setPrice(dec(105, 18)); + await token0.mintToken(bamm.address, dec(1,12)) + await token1.mintToken(bamm.address, dec(1,13)) + await token2.mintToken(bamm.address, dec(1,4)) - // Troves are closed - await troveManager.liquidate(defaulter_1, { from: owner }) - await troveManager.liquidate(defaulter_2, { from: owner }) + assert((await bamm.getCollateralValue()).succ, "getCollateralValue should not fail") - // 4k liquidations - assert.equal(toBN(dec(6000, 18)).toString(), (await stabilityPool.getCompoundedLUSDDeposit(bamm.address)).toString()) - const ethGains = web3.utils.toBN("39799999999999999975") + // nullify price feed 1 + await priceFeed1.setTimestamp(888) // now price expired - const lusdQty = dec(105, 18) - const expectedReturn200 = await bamm.getReturn(lusdQty, dec(6000, 18), toBN(dec(6000, 18)).add(ethGains.mul(toBN(2 * 105))), 200) - const expectedReturn190 = await bamm.getReturn(lusdQty, dec(6000, 18), toBN(dec(6000, 18)).add(ethGains.mul(toBN(2 * 105))), 190) + assert(! (await bamm.getCollateralValue()).succ, "getCollateralValue should fail") + }) - assert(expectedReturn200.toString() !== expectedReturn190.toString()) + it('test deposit when chainlink is down', async () => { + await priceFeed0.setPrice(dec(1, 18), {from: bammOwner}); + await priceFeed1.setPrice(dec(2, 18), {from: bammOwner}); + await priceFeed2.setPrice(dec(3, 18), {from: bammOwner}); - // without fee - await bamm.setParams(200, 0, {from: bammOwner}) - const priceWithoutFee = await bamm.getSwapEthAmount(lusdQty) - assert.equal(priceWithoutFee.ethAmount.toString(), expectedReturn200.mul(toBN(100)).div(toBN(100 * 105)).toString()) + await token0.mintToken(bamm.address, dec(1,12)) + await token1.mintToken(bamm.address, dec(1,13)) + await token2.mintToken(bamm.address, dec(1,4)) - // with fee - await bamm.setParams(190, 100, {from: bammOwner}) - const priceWithFee = await bamm.getSwapEthAmount(lusdQty) - assert.equal(priceWithFee.ethAmount.toString(), expectedReturn190.mul(toBN(99)).div(toBN(100 * 105)).toString()) - }) - - it('test set params sad path', async () => { - await assertRevert(bamm.setParams(210, 100, {from: bammOwner}), 'setParams: A too big') - await assertRevert(bamm.setParams(10, 100, {from: bammOwner}), 'setParams: A too small') - await assertRevert(bamm.setParams(10, 101, {from: bammOwner}), 'setParams: fee is too big') - await assertRevert(bamm.setParams(20, 100, {from: B}), 'Ownable: caller is not the owner') + await lusdToken.mintToken(A, toBN(dec(100000, 7))) + await lusdToken.approve(bamm.address, toBN(dec(10000, 7)), { from: A }) + + // nullify price feed 1 + await priceFeed1.setTimestamp(888) // now price expired + + await assertRevert(bamm.deposit(toBN(dec(6000, 7)), { from: A } ), "deposit: chainlink is down") }) - it.skip('transfer happy test', async () => { // transfer is not supported anymore - // --- SETUP --- + it('swap sad paths', async () => { + await priceFeed0.setPrice(dec(1, 18), {from: bammOwner}); + await priceFeed1.setPrice(dec(2, 18), {from: bammOwner}); + await priceFeed2.setPrice(dec(3, 18), {from: bammOwner}); - // Whale opens Trove and deposits to SP - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: whale, value: dec(50, 'ether') } }) - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: A } }) - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: C } }) - await openTrove({ extraLUSDAmount: toBN(dec(10000, 18)), ICR: toBN(dec(20, 18)), extraParams: { from: D } }) - - const whaleLUSD = await lusdToken.balanceOf(whale) - await lusdToken.approve(bamm.address, whaleLUSD, { from: whale }) - await lusdToken.approve(bamm.address, toBN(dec(10000, 18)), { from: A }) - await bamm.deposit(toBN(dec(10000, 18)), { from: A } ) - await stabilityPool.provideToSP(toBN(dec(10000, 18)), frontEnd_1, {from: C}) + await token0.mintToken(bamm.address, dec(1,12)) + await token1.mintToken(bamm.address, dec(1,13)) + await token2.mintToken(bamm.address, dec(1,4)) + + await lusdToken.mintToken(A, toBN(dec(100000, 7))) + await lusdToken.approve(bamm.address, toBN(dec(10000, 7)), { from: A }) - assert.equal(await bamm.balanceOf(A), dec(1, 18)) + // call getSwapAmount and get non 0 value + let price = await bamm.getSwapAmount(dec(1, 7), token1.address) + assert(price.gt(toBN(0)), "expecting price > 0, and got " + price.toString()) - await th.fastForwardTime(timeValues.SECONDS_IN_ONE_HOUR, web3.currentProvider) + // nullify price feed 1 + await priceFeed1.setTimestamp(888) // now price expired - await stabilityPool.provideToSP(toBN(dec(5000, 18)), frontEnd_1, {from: D}) + // call getSwapAmount and get non 0 value + price = await bamm.getSwapAmount(dec(1, 7), token1.address) + assert.equal(price.toString(), "0") + + await assertRevert(bamm.swap(1, lusdToken.address, 0, ZERO_ADDRESS, { from: A } ), "swap: unsupported") + }) - await bamm.transfer(B, dec(5, 17), {from: A}) - assert.equal(await bamm.balanceOf(A), dec(5, 17)) - assert.equal(await bamm.balanceOf(B), dec(5, 17)) + it('liquidateBorrow sad path', async () => { + const newCToken = await MockCToken.new(token0.address, false) + await assertRevert(bamm.liquidateBorrow(shmuel, 1, newCToken.address, { from: A } ), "liquidateBorrow: invalid collateral") + }) - await stabilityPool.withdrawFromSP(toBN(dec(5000, 18)), { from: C }) - assert.equal(await lqtyToken.balanceOf(B), "0") - await bamm.withdraw(0, {from: A}) - assert.equal((await lqtyToken.balanceOf(A)).toString(), (await lqtyToken.balanceOf(C)).toString()) + it('with admin', async () => { + const withAdmin = await MockWithAdmin.new() + await withAdmin.setAdmin(shmuel) + const adminContract = await Admin.new(withAdmin.address, bamm.address, {from: A}) - // reset A's usd balance - await lusdToken.transfer(C, await lusdToken.balanceOf(A), {from: A}) - assert.equal(await lusdToken.balanceOf(A), "0") + await bamm.transferOwnership(adminContract.address, {from: bammOwner}) - await th.fastForwardTime(timeValues.SECONDS_IN_ONE_HOUR, web3.currentProvider) + // test set params + await adminContract.setParams(25, 66, 77, {from: A}) + assert.equal((await bamm.A()).toString(), "25") + assert.equal((await bamm.fee()).toString(), "66") + assert.equal((await bamm.callerFee()).toString(), "77") + + // test set params not from owner + await assertRevert(adminContract.setParams(25, 66, 77, {from: shmuel}), "Ownable: caller is not the owner") - await bamm.withdraw(toBN(dec(5, 17)), {from: A}) // check balance - await bamm.withdraw(toBN(dec(5, 17)), {from: B}) // check balance - await stabilityPool.withdrawFromSP(toBN(dec(5000, 18)), { from: C }) - await stabilityPool.withdrawFromSP(toBN(dec(5000, 18)), { from: D }) + // test new admin not from compoud admin + await assertRevert(adminContract.setBAMMPendingOwnership(B, {from: A}), "only market admin can change ownership") - assert.equal((await lqtyToken.balanceOf(B)).toString(), (await lqtyToken.balanceOf(D)).toString()) - assert.equal((await lqtyToken.balanceOf(A)).toString(), (await lqtyToken.balanceOf(C)).toString()) + // try to set new admin before pending was set + await assertRevert(adminContract.transferBAMMOwnership({from: A}), "pending owner is 0") - assert.equal((await lusdToken.balanceOf(B)).toString(), dec(5000, 18)) - assert.equal((await lusdToken.balanceOf(A)).toString(), dec(5000, 18)) - }) + // test new admin from compoud admin + await adminContract.setBAMMPendingOwnership(B, {from: shmuel}) + assert.equal(await adminContract.pendingOwner(), B) + // try to set new admin before 14 days elapse + await assertRevert(adminContract.transferBAMMOwnership({from: A}), "too early") - // tests: - // 1. complex lqty staking + share V - // 2. share test with ether V - // 3. basic share with liquidation (withdraw after liquidation) V - // 4. price that exceeds max discount V - // 5. price that exceeds balance V - // 5.5 test fees and return V - // 5.6 test swap v - // 6.1 test fetch price V - // 6. set params V - // 7. test with front end v - // 8. formula V - // 9. lp token - transfer sad test - // 11. pickle V - // 10. cleanups - compilation warnings. cropjoin - revoke changes and maybe make internal. V - // 12 - linter. events + // move two weeks into the future and change admin + await th.fastForwardTime(60 * 60 * 24 * 14 + 1, web3.currentProvider) + await adminContract.transferBAMMOwnership({from: A}) + assert.equal(await bamm.owner(), B) + }) }) }) +// TODO - test infinite allowane function almostTheSame(n1, n2) { n1 = Number(web3.utils.fromWei(n1)) diff --git a/packages/contracts/test/B.Protocol/ForkTestFantom.js b/packages/contracts/test/B.Protocol/ForkTestFantom.js new file mode 100644 index 000000000..573367551 --- /dev/null +++ b/packages/contracts/test/B.Protocol/ForkTestFantom.js @@ -0,0 +1,272 @@ +const { assert } = require("hardhat") +const deploymentHelper = require("./../../utils/deploymentHelpers.js") +const testHelpers = require("./../../utils/testHelpers.js") +const th = testHelpers.TestHelper +const dec = th.dec +const toBN = th.toBN +const mv = testHelpers.MoneyValues +const timeValues = testHelpers.TimeValues + +const TroveManagerTester = artifacts.require("TroveManagerTester") +const MockToken = artifacts.require("MockToken") +const MockCToken = artifacts.require("MockCToken") +const NonPayable = artifacts.require('NonPayable.sol') +const BAMM = artifacts.require("BAMM.sol") +const BLens = artifacts.require("BLens.sol") +const Comptroller = artifacts.require("Comptroller.sol") +const Unitroller = artifacts.require("Unitroller.sol") +const ChainlinkTestnet = artifacts.require("ChainlinkTestnet.sol") +const CErc20Interface = artifacts.require("CErc20Interface.sol") +const CETH = artifacts.require("CETH.sol") +const FakePrice = artifacts.require("FakePriceOracle.sol") + +const ZERO = toBN('0') +const ZERO_ADDRESS = th.ZERO_ADDRESS +const maxBytes32 = th.maxBytes32 + +const getFrontEndTag = async (stabilityPool, depositor) => { + return (await stabilityPool.deposits(depositor))[1] +} + +contract('BAMM', async accounts => { + const [owner, + defaulter_1, defaulter_2, defaulter_3, + alice, bob, carol, dennis, erin, flyn, + A, B, C, D, E, F, + u1, u2, u3, u4, u5, + v1, v2, v3, v4, v5, + frontEnd_1, frontEnd_2, frontEnd_3, + bammOwner, + shmuel, yaron, eitan + ] = accounts; + + const fvat = "0xD0Bb8e4E4Dd5FDCD5D54f78263F5Ec8f33da4C95" + const whale = "0x2400BB4D7221bA530Daee061D5Afe219E9223Eae" // has eth and usdt + const fish = "0x23cBF6d1b738423365c6930F075Ed6feEF7d14f3" // has cETH and usdt debt + + const [bountyAddress, lpRewardsAddress, multisig] = accounts.slice(997, 1000) + + const frontEnds = [frontEnd_1, frontEnd_2, frontEnd_3] + let contracts + let priceFeed + let lusdToken + let bamm + let lens + let chainlink + let usdc + let btc + let cBTC + let cUSDC + let fakePrice + + let gasPriceInWei + + const cBTCAddress = "0xa8236EaFBAF1C3D39396DE566cEEa6F320E3db00" + const BTCAddress = "0x321162Cd933E2Be498Cd2267a90534A804051b11" + const cUSDCAddress = "0x243E33aa7f6787154a8E59d3C27a66db3F8818ee" + const USDCAddress = "0x04068DA6C83AFCFA0e13ba15A6696662335D5B75" + + //const assertRevert = th.assertRevert + + describe("BAMM", async () => { + + before(async () => { + await hre.network.provider.request({ + method: "hardhat_impersonateAccount", + params: [fvat], + }) + + await hre.network.provider.request({ + method: "hardhat_impersonateAccount", + params: [whale], + }) + + await hre.network.provider.request({ + method: "hardhat_impersonateAccount", + params: [fish], + }) + + usdc = await MockToken.at(USDCAddress) + btc = await MockToken.at(BTCAddress) + cBTC = await CErc20Interface.at(cBTCAddress) + cUSDC = await CErc20Interface.at(cUSDCAddress) + + console.log("send eth to fish") + await web3.eth.sendTransaction({from: whale, to: fish, value: toBN(dec(1, 18))}) + + console.log("send ust to fish") + await usdc.transfer(fish, dec(1000,6), {from: whale, block: "latest"}) + + bamm = await BAMM.at("0xEDC7905a491fF335685e2F2F1552541705138A3D") + }) + + beforeEach(async () => { + + }) + + it("liquidate with b.protocol happy path", async () => { + const unicomptroller = await Comptroller.at("0x0F390559F258eB8591C8e31Cf0905E97cf36ACE2") + const unitroller = await Unitroller.at("0x0F390559F258eB8591C8e31Cf0905E97cf36ACE2") + + console.log("enter market") + await unicomptroller.enterMarkets([cBTC.address], {from: whale, block: "latest"}) + console.log("give wbtc allowance") + await btc.approve(cBTC.address, dec(1, 8), {from: whale, block: "latest"}) + console.log("deposit cWBTC") + await cBTC.mint(dec(1,8), {from: whale, block: "latest"}) + console.log("whale balance:", (await usdc.balanceOf(whale)).toString()) + await cUSDC.borrow(dec(20000,6), {from: whale, block: "latest"}) + console.log("whale balance:", (await usdc.balanceOf(whale)).toString()) + + console.log("deploying fake price") + fakePrice = await FakePrice.new(cBTCAddress, "0x10010069DE6bD5408A6dEd075Cf6ae2498073c73", {from: fvat}) + + console.log("setting new price oracle") + await unicomptroller._setPriceOracle(fakePrice.address, {from: fvat, block: "latest"}) + + console.log("setting new eth price") + await fakePrice.setCETHPrice(dec(1000, 28), {from: fvat}) + + console.log((await web3.eth.getBlockNumber()).toString()) + + console.log("deploying impl") + const comptrollerImpl = await Comptroller.new({from: fvat, block: "latest"}) + console.log("deploying impl done") + + + console.log("setting new pending impl") + await unitroller._setPendingImplementation(comptrollerImpl.address, {from: fvat, block: "latest"}) + console.log("setting new pending impl done") + + console.log("accept new implementation") + await comptrollerImpl._become(unitroller.address, {from: fvat, block: "latest"}) + console.log("accept new implementation done") + + console.log("bamm address", bamm.address) + + console.log("set b.protocol") + await unicomptroller._setBProtocol(cUSDCAddress, bamm.address, {from: fvat, block: "latest"}) + console.log("set b.protocol - done") + + console.log("give allowance to bamm") + await usdc.approve(bamm.address, dec(1000, 6), {from: whale, block: "latest"}) + + console.log("whale balance:", (await usdc.balanceOf(whale)).toString()) + + console.log("deposit usdt to bamm") + await bamm.deposit(dec(1000, 6), {from: whale, block: "latest"}) + console.log("deposit done") + + console.log("liquidate") + const ethBalBefore = await btc.balanceOf(bamm.address) + const usdtBalBefore = await usdc.balanceOf(bamm.address) + + console.log("eth balance before", ethBalBefore.toString()) + console.log("ust balance before", (await usdc.balanceOf(bamm.address)).toString()) + + await assertRevert(cUSDC.liquidateBorrow(whale, dec(100,6), cBTCAddress, {from: fish, block: "latest"}), 'only B.Protocol can liquidate') + + await bamm.liquidateBorrow(whale, dec(100,6), cBTCAddress, {from: whale, block: "latest"}) + + const ethBalAfter = await btc.balanceOf(bamm.address) + const usdtBalAfter = await usdc.balanceOf(bamm.address) + + console.log("eth balance after", ethBalAfter.toString()) + console.log("ust balance before", (await usdc.balanceOf(bamm.address)).toString()) + + assert.equal(usdtBalBefore.sub(usdtBalAfter).toString(), dec(100,6), "unexpect ust bal diff") + assert.equal(ethBalAfter.sub(ethBalBefore).toString(), (10691307 - 258), "unexpect ust btc diff") + }) + + it("try to set bprotocol from non owner", async () => { + const unicomptroller = await Comptroller.at("0x0F390559F258eB8591C8e31Cf0905E97cf36ACE2") + await assertRevert(unicomptroller._setBProtocol(cUSDCAddress, bamm.address, {from: fish}), "only admin can set B.Protocol") + }) + + it("liquidate without b.protocol - b.protocol not set", async () => { + const unicomptroller = await Comptroller.at("0x0F390559F258eB8591C8e31Cf0905E97cf36ACE2") + const unitroller = await Unitroller.at("0x0F390559F258eB8591C8e31Cf0905E97cf36ACE2") + + console.log("set b.protocol") + await unicomptroller._setBProtocol(cUSDCAddress, "0x0000000000000000000000000000000000000000", {from: fvat, block: "latest"}) + // set something but not for this ctoken + await unicomptroller._setBProtocol(fvat, fvat, {from: fvat, block: "latest"}) + console.log("set b.protocol - done") + + console.log("whale balance:", (await usdc.balanceOf(whale)).toString()) + + console.log("liquidate") + const usdtBalBefore = await usdc.balanceOf(fish) + console.log("ust balance before", (await usdc.balanceOf(fish)).toString()) + await usdc.approve(cUSDC.address, dec(1,6), {from: fish, block: "latest"}) + console.log((await cUSDC.liquidateBorrow.call(whale, dec(1,6), cBTCAddress, {from: fish, block: "latest"})).toString()) + await cUSDC.liquidateBorrow(whale, dec(1,6), cBTCAddress, {from: fish, block: "latest"}) + const usdtBalAfter = await usdc.balanceOf(fish) + console.log("ust balance after", (await usdc.balanceOf(fish)).toString()) + + assert.equal(usdtBalBefore.sub(usdtBalAfter).toString(), dec(1,6), "unexpect ust bal diff") + }) + + it.skip("liquidate without b.protocol - b.protocol can liquidate return false", async () => { + const unicomptroller = await Comptroller.at("0x0F390559F258eB8591C8e31Cf0905E97cf36ACE2") + const unitroller = await Unitroller.at("0x0F390559F258eB8591C8e31Cf0905E97cf36ACE2") + + console.log("set b.protocol") + await unicomptroller._setBProtocol(cUSDCAddress, bamm.address, {from: fvat, block: "latest"}) + assert.equal(await unicomptroller.bprotocol(cUSDCAddress), bamm.address, "unexpected b.protocol address") + console.log("set b.protocol - done") + + console.log("withdraw all bamm balance") + await bamm.withdraw(await bamm.balanceOf(whale), {from: whale, block: "latest"}) + + assert(! await bamm.canLiquidate(cUSDC.address, cBTCAddress, dec(1,6)), "expected can liquidate to return false") + + console.log("liquidate") + const usdcBalBefore = await usdt.balanceOf(fish) + console.log("ust balance before", (await usdc.balanceOf(fish)).toString()) + await usdt.approve(cUSDC.address, dec(1,6), {from: fish, block: "latest"}) + console.log((await cUSDT.liquidateBorrow.call(whale, dec(1,6), cETHAddress, {from: fish, block: "latest"})).toString()) + await cUSDT.liquidateBorrow(whale, dec(1,6), cETHAddress, {from: fish, block: "latest"}) + const usdtBalAfter = await usdt.balanceOf(fish) + console.log("ust balance after", (await usdt.balanceOf(fish)).toString()) + + assert.equal(usdtBalBefore.sub(usdtBalAfter).toString(), dec(1,6), "unexpect ust bal diff") + }) + }) +}) + + +function almostTheSame(n1, n2) { + n1 = Number(web3.utils.fromWei(n1)) + n2 = Number(web3.utils.fromWei(n2)) + //console.log(n1,n2) + + if(n1 * 1000 > n2 * 1001) return false + if(n2 * 1000 > n1 * 1001) return false + return true +} + +function in100WeiRadius(n1, n2) { + const x = toBN(n1) + const y = toBN(n2) + + if(x.add(toBN(100)).lt(y)) return false + if(y.add(toBN(100)).lt(x)) return false + + return true +} + +async function assertRevert(txPromise, message = undefined) { + try { + const tx = await txPromise + // console.log("tx succeeded") + assert.isFalse(tx.receipt.status) // when this assert fails, the expected revert didn't occur, i.e. the tx succeeded + } catch (err) { + // console.log("tx failed") + assert.include(err.message, "revert") + + if (message) { + assert.include(err.message, message) + } + } +} \ No newline at end of file diff --git a/packages/lib-ethers/abi/BLens.json b/packages/lib-ethers/abi/BLens.json index 72da28dc8..59cc257cf 100644 --- a/packages/lib-ethers/abi/BLens.json +++ b/packages/lib-ethers/abi/BLens.json @@ -52,6 +52,72 @@ "stateMutability": "nonpayable", "type": "function" }, + { + "inputs": [ + { + "internalType": "address", + "name": "user", + "type": "address" + }, + { + "internalType": "contract BAMM", + "name": "bamm", + "type": "address" + }, + { + "internalType": "contract ERC20", + "name": "lqty", + "type": "address" + } + ], + "name": "getUserInfo", + "outputs": [ + { + "components": [ + { + "internalType": "uint256", + "name": "unclaimedLqty", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "bammUserBalance", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "bammTotalSupply", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "lusdUserBalance", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "ethUserBalance", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "lusdTotal", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "ethTotal", + "type": "uint256" + } + ], + "internalType": "struct BLens.UserInfo", + "name": "info", + "type": "tuple" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, { "inputs": [ { diff --git a/packages/liquidator/.gitignore b/packages/liquidator/.gitignore new file mode 100644 index 000000000..2c495c7ef --- /dev/null +++ b/packages/liquidator/.gitignore @@ -0,0 +1,6 @@ +n# package directories +node_modules +jspm_packages + +# Serverless directories +.serverless \ No newline at end of file diff --git a/packages/liquidator/README.md b/packages/liquidator/README.md new file mode 100644 index 000000000..878f0d933 --- /dev/null +++ b/packages/liquidator/README.md @@ -0,0 +1,90 @@ + + + +# Serverless Framework AWS NodeJS Example + +This template demonstrates how to deploy a NodeJS function running on AWS Lambda using the traditional Serverless Framework. The deployed function does not include any event definitions as well as any kind of persistence (database). For more advanced configurations check out the [examples repo](https://github.com/serverless/examples/) which includes integrations with SQS, DynamoDB or examples of functions that are triggered in `cron`-like manner. For details about configuration of specific `events`, please refer to our [documentation](https://www.serverless.com/framework/docs/providers/aws/events/). + +## Usage + +### Deployment + +In order to deploy the example, you need to run the following command: + +``` +$ serverless deploy +``` + +After running deploy, you should see output similar to: + +```bash +Serverless: Packaging service... +Serverless: Excluding development dependencies... +Serverless: Creating Stack... +Serverless: Checking Stack create progress... +........ +Serverless: Stack create finished... +Serverless: Uploading CloudFormation file to S3... +Serverless: Uploading artifacts... +Serverless: Uploading service aws-node.zip file to S3 (711.23 KB)... +Serverless: Validating template... +Serverless: Updating Stack... +Serverless: Checking Stack update progress... +................................. +Serverless: Stack update finished... +Service Information +service: aws-node +stage: dev +region: us-east-1 +stack: aws-node-dev +resources: 6 +functions: + api: aws-node-dev-hello +layers: + None +``` + +### Invocation + +After successful deployment, you can invoke the deployed function by using the following command: + +```bash +serverless invoke --function hello +``` + +Which should result in response similar to the following: + +```json +{ + "statusCode": 200, + "body": "{\n \"message\": \"Go Serverless v2.0! Your function executed successfully!\",\n \"input\": {}\n}" +} +``` + +### Local development + +You can invoke your function locally by using the following command: + +```bash +serverless invoke local --function hello +``` + +Which should result in response similar to the following: + +``` +{ + "statusCode": 200, + "body": "{\n \"message\": \"Go Serverless v2.0! Your function executed successfully!\",\n \"input\": \"\"\n}" +} +``` diff --git a/packages/liquidator/abi.json b/packages/liquidator/abi.json new file mode 100644 index 000000000..7ea7de09a --- /dev/null +++ b/packages/liquidator/abi.json @@ -0,0 +1,7 @@ +{ + "BAMM": [{"inputs":[{"internalType":"address","name":"_LUSD","type":"address"},{"internalType":"address","name":"_cBorrow","type":"address"},{"internalType":"uint256","name":"_maxDiscount","type":"uint256"},{"internalType":"address payable","name":"_feePool","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"tokenOwner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"tokens","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"A","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"callerFee","type":"uint256"}],"name":"ParamsSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"lusdAmount","type":"uint256"},{"indexed":false,"internalType":"contract IERC20","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"tokenAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"RebalanceSwap","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"tokens","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"lusdAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"numShares","type":"uint256"}],"name":"UserDeposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"lusdAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"numShares","type":"uint256"}],"name":"UserWithdraw","type":"event"},{"inputs":[],"name":"A","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LUSD","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_A","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_CALLER_FEE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_FEE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_A","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PRECISION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ICToken","name":"ctoken","type":"address"},{"internalType":"contract AggregatorV3Interface","name":"feed","type":"address"}],"name":"addCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"tokens","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"success","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"cBorrow","outputs":[{"internalType":"contract ICToken","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"cTokens","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"callerFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ICToken","name":"cTokenBorrowed","type":"address"},{"internalType":"contract ICToken","name":"cTokenCollateral","type":"address"},{"internalType":"uint256","name":"repayAmount","type":"uint256"}],"name":"canLiquidate","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"collateralDecimals","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"collaterals","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"lusdAmount","type":"uint256"}],"name":"deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"fee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feePool","outputs":[{"internalType":"address payable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"token","type":"address"}],"name":"fetchPrice","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCollateralValue","outputs":[{"internalType":"bool","name":"succ","type":"bool"},{"internalType":"uint256","name":"value","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"xQty","type":"uint256"},{"internalType":"uint256","name":"xBalance","type":"uint256"},{"internalType":"uint256","name":"yBalance","type":"uint256"},{"internalType":"uint256","name":"A","type":"uint256"}],"name":"getReturn","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"},{"internalType":"uint256","name":"A","type":"uint256"}],"name":"getSumFixedPoint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"lusdQty","type":"uint256"},{"internalType":"contract IERC20","name":"token","type":"address"}],"name":"getSwapAmount","outputs":[{"internalType":"uint256","name":"tokenAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isOwner","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"contract ICToken","name":"collateral","type":"address"}],"name":"liquidateBorrow","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"lusdDecimals","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxDiscount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"priceAggregators","outputs":[{"internalType":"contract AggregatorV3Interface","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ICToken","name":"ctoken","type":"address"}],"name":"removeCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_A","type":"uint256"},{"internalType":"uint256","name":"_fee","type":"uint256"},{"internalType":"uint256","name":"_callerFee","type":"uint256"}],"name":"setParams","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"lusdAmount","type":"uint256"},{"internalType":"contract IERC20","name":"returnToken","type":"address"},{"internalType":"uint256","name":"minReturn","type":"uint256"},{"internalType":"address payable","name":"dest","type":"address"}],"name":"swap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokens","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"success","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokens","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"success","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"numShares","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}], + "bKeeper": [{"inputs":[{"internalType":"contract Arb","name":"_arb","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"succ","type":"bool"}],"name":"KeepOperation","type":"event"},{"inputs":[{"internalType":"address","name":"newBamm","type":"address"}],"name":"addBamm","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"admin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"arb","outputs":[{"internalType":"contract Arb","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"bamms","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"","type":"bytes"}],"name":"checkUpkeep","outputs":[{"internalType":"bool","name":"upkeepNeeded","type":"bool"},{"internalType":"bytes","name":"performData","type":"bytes"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"checker","outputs":[{"internalType":"bool","name":"canExec","type":"bool"},{"internalType":"bytes","name":"execPayload","type":"bytes"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"performData","type":"bytes"}],"name":"doer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"findSmallestQty","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxEthQty","type":"uint256"},{"internalType":"uint256","name":"_minEthQty","type":"uint256"},{"internalType":"uint256","name":"_minProfit","type":"uint256"}],"name":"initParams","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"performData","type":"bytes"}],"name":"performUpkeep","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"performData","type":"bytes"}],"name":"performUpkeepSafe","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"bamm","type":"address"}],"name":"removeBamm","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract Arb","name":"_arb","type":"address"}],"name":"setArb","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newVal","type":"uint256"}],"name":"setMaxEthQty","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newVal","type":"uint256"}],"name":"setMinEthQty","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newVal","type":"uint256"}],"name":"setMinProfit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newAdmin","type":"address"}],"name":"transferAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"withdrawEth","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}], + "cEthAbi": [{"inputs":[{"internalType":"contract ComptrollerInterface","name":"comptroller_","type":"address"},{"internalType":"contract InterestRateModel","name":"interestRateModel_","type":"address"},{"internalType":"uint256","name":"initialExchangeRateMantissa_","type":"uint256"},{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"},{"internalType":"uint8","name":"decimals_","type":"uint8"},{"internalType":"address payable","name":"admin_","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"cashPrior","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"interestAccumulated","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"borrowIndex","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalBorrows","type":"uint256"}],"name":"AccrueInterest","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"borrower","type":"address"},{"indexed":false,"internalType":"uint256","name":"borrowAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"accountBorrows","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalBorrows","type":"uint256"}],"name":"Borrow","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"error","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"info","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"detail","type":"uint256"}],"name":"Failure","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"liquidator","type":"address"},{"indexed":false,"internalType":"address","name":"borrower","type":"address"},{"indexed":false,"internalType":"uint256","name":"repayAmount","type":"uint256"},{"indexed":false,"internalType":"address","name":"cTokenCollateral","type":"address"},{"indexed":false,"internalType":"uint256","name":"seizeTokens","type":"uint256"}],"name":"LiquidateBorrow","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"minter","type":"address"},{"indexed":false,"internalType":"uint256","name":"mintAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"mintTokens","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newAdmin","type":"address"}],"name":"NewAdmin","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract ComptrollerInterface","name":"oldComptroller","type":"address"},{"indexed":false,"internalType":"contract ComptrollerInterface","name":"newComptroller","type":"address"}],"name":"NewComptroller","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract InterestRateModel","name":"oldInterestRateModel","type":"address"},{"indexed":false,"internalType":"contract InterestRateModel","name":"newInterestRateModel","type":"address"}],"name":"NewMarketInterestRateModel","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldPendingAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newPendingAdmin","type":"address"}],"name":"NewPendingAdmin","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldReserveFactorMantissa","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newReserveFactorMantissa","type":"uint256"}],"name":"NewReserveFactor","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"redeemer","type":"address"},{"indexed":false,"internalType":"uint256","name":"redeemAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"redeemTokens","type":"uint256"}],"name":"Redeem","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"payer","type":"address"},{"indexed":false,"internalType":"address","name":"borrower","type":"address"},{"indexed":false,"internalType":"uint256","name":"repayAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"accountBorrows","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalBorrows","type":"uint256"}],"name":"RepayBorrow","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"benefactor","type":"address"},{"indexed":false,"internalType":"uint256","name":"addAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newTotalReserves","type":"uint256"}],"name":"ReservesAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"admin","type":"address"},{"indexed":false,"internalType":"uint256","name":"reduceAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newTotalReserves","type":"uint256"}],"name":"ReservesReduced","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"constant":false,"inputs":[],"name":"_acceptAdmin","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"reduceAmount","type":"uint256"}],"name":"_reduceReserves","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract ComptrollerInterface","name":"newComptroller","type":"address"}],"name":"_setComptroller","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract InterestRateModel","name":"newInterestRateModel","type":"address"}],"name":"_setInterestRateModel","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address payable","name":"newPendingAdmin","type":"address"}],"name":"_setPendingAdmin","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"newReserveFactorMantissa","type":"uint256"}],"name":"_setReserveFactor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"accrualBlockNumber","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"accrueInterest","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"admin","outputs":[{"internalType":"address payable","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOfUnderlying","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"borrowAmount","type":"uint256"}],"name":"borrow","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"borrowBalanceCurrent","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"borrowBalanceStored","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"borrowIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"borrowRatePerBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"comptroller","outputs":[{"internalType":"contract ComptrollerInterface","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"exchangeRateCurrent","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"exchangeRateStored","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAccountSnapshot","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getCash","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"contract ComptrollerInterface","name":"comptroller_","type":"address"},{"internalType":"contract InterestRateModel","name":"interestRateModel_","type":"address"},{"internalType":"uint256","name":"initialExchangeRateMantissa_","type":"uint256"},{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"},{"internalType":"uint8","name":"decimals_","type":"uint8"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"interestRateModel","outputs":[{"internalType":"contract InterestRateModel","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isCToken","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"contract CToken","name":"cTokenCollateral","type":"address"}],"name":"liquidateBorrow","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"mint","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"pendingAdmin","outputs":[{"internalType":"address payable","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"redeemTokens","type":"uint256"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"redeemAmount","type":"uint256"}],"name":"redeemUnderlying","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"repayBorrow","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"borrower","type":"address"}],"name":"repayBorrowBehalf","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"reserveFactorMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"liquidator","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"seizeTokens","type":"uint256"}],"name":"seize","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"supplyRatePerBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalBorrows","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"totalBorrowsCurrent","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalReserves","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"dst","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"src","type":"address"},{"internalType":"address","name":"dst","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}], + "helperAbi": [{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"contract IComptroller","name":"comptroller","type":"address"},{"internalType":"contract BAMMLike","name":"bamm","type":"address"}],"name":"getAccountInfo","outputs":[{"components":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"bamm","type":"address"},{"internalType":"address","name":"ctoken","type":"address"},{"internalType":"uint256","name":"repayAmount","type":"uint256"},{"internalType":"bool","name":"underwater","type":"bool"}],"internalType":"struct LiquidationBotHelper.Account","name":"a","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"accounts","type":"address[]"},{"internalType":"address","name":"comptroller","type":"address"},{"internalType":"address[]","name":"bamms","type":"address[]"}],"name":"getInfo","outputs":[{"components":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"bamm","type":"address"},{"internalType":"address","name":"ctoken","type":"address"},{"internalType":"uint256","name":"repayAmount","type":"uint256"},{"internalType":"bool","name":"underwater","type":"bool"}],"internalType":"struct LiquidationBotHelper.Account[]","name":"unsafeAccounts","type":"tuple[]"}],"stateMutability":"view","type":"function"}], + "comptroller" : [{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"action","type":"string"},{"indexed":false,"internalType":"bool","name":"pauseState","type":"bool"}],"name":"ActionPaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract CToken","name":"cToken","type":"address"},{"indexed":false,"internalType":"string","name":"action","type":"string"},{"indexed":false,"internalType":"bool","name":"pauseState","type":"bool"}],"name":"ActionPaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"CompGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract CToken","name":"cToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"newSpeed","type":"uint256"}],"name":"CompSpeedUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"contributor","type":"address"},{"indexed":false,"internalType":"uint256","name":"newSpeed","type":"uint256"}],"name":"ContributorCompSpeedUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract CToken","name":"cToken","type":"address"},{"indexed":true,"internalType":"address","name":"borrower","type":"address"},{"indexed":false,"internalType":"uint256","name":"compDelta","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"compBorrowIndex","type":"uint256"}],"name":"DistributedBorrowerComp","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract CToken","name":"cToken","type":"address"},{"indexed":true,"internalType":"address","name":"supplier","type":"address"},{"indexed":false,"internalType":"uint256","name":"compDelta","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"compSupplyIndex","type":"uint256"}],"name":"DistributedSupplierComp","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"error","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"info","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"detail","type":"uint256"}],"name":"Failure","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract CToken","name":"cToken","type":"address"},{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"MarketEntered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract CToken","name":"cToken","type":"address"},{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"MarketExited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract CToken","name":"cToken","type":"address"}],"name":"MarketListed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract CToken","name":"cToken","type":"address"}],"name":"MarketRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract CToken","name":"cToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"newBorrowCap","type":"uint256"}],"name":"NewBorrowCap","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldBorrowCapGuardian","type":"address"},{"indexed":false,"internalType":"address","name":"newBorrowCapGuardian","type":"address"}],"name":"NewBorrowCapGuardian","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldCloseFactorMantissa","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newCloseFactorMantissa","type":"uint256"}],"name":"NewCloseFactor","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract CToken","name":"cToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"oldCollateralFactorMantissa","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newCollateralFactorMantissa","type":"uint256"}],"name":"NewCollateralFactor","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldLiquidationIncentiveMantissa","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newLiquidationIncentiveMantissa","type":"uint256"}],"name":"NewLiquidationIncentive","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldPauseGuardian","type":"address"},{"indexed":false,"internalType":"address","name":"newPauseGuardian","type":"address"}],"name":"NewPauseGuardian","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract PriceOracle","name":"oldPriceOracle","type":"address"},{"indexed":false,"internalType":"contract PriceOracle","name":"newPriceOracle","type":"address"}],"name":"NewPriceOracle","type":"event"},{"constant":false,"inputs":[{"internalType":"contract Unitroller","name":"unitroller","type":"address"}],"name":"_become","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"_borrowGuardianPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"contract CToken","name":"cToken","type":"address"}],"name":"_disableMarket","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"_grantComp","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"_mintGuardianPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newBorrowCapGuardian","type":"address"}],"name":"_setBorrowCapGuardian","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract CToken","name":"cToken","type":"address"},{"internalType":"bool","name":"state","type":"bool"}],"name":"_setBorrowPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"newCloseFactorMantissa","type":"uint256"}],"name":"_setCloseFactor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract CToken","name":"cToken","type":"address"},{"internalType":"uint256","name":"newCollateralFactorMantissa","type":"uint256"}],"name":"_setCollateralFactor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract CToken","name":"cToken","type":"address"},{"internalType":"uint256","name":"compSpeed","type":"uint256"}],"name":"_setCompSpeed","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"contributor","type":"address"},{"internalType":"uint256","name":"compSpeed","type":"uint256"}],"name":"_setContributorCompSpeed","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"newLiquidationIncentiveMantissa","type":"uint256"}],"name":"_setLiquidationIncentive","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract CToken[]","name":"cTokens","type":"address[]"},{"internalType":"uint256[]","name":"newBorrowCaps","type":"uint256[]"}],"name":"_setMarketBorrowCaps","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract CToken","name":"cToken","type":"address"},{"internalType":"bool","name":"state","type":"bool"}],"name":"_setMintPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newPauseGuardian","type":"address"}],"name":"_setPauseGuardian","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract PriceOracle","name":"newOracle","type":"address"}],"name":"_setPriceOracle","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bool","name":"state","type":"bool"}],"name":"_setSeizePaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bool","name":"state","type":"bool"}],"name":"_setTransferPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract CToken","name":"cToken","type":"address"}],"name":"_supportMarket","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"accountAssets","outputs":[{"internalType":"contract CToken","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"admin","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"allMarkets","outputs":[{"internalType":"contract CToken","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"cToken","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"borrowAmount","type":"uint256"}],"name":"borrowAllowed","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"borrowCapGuardian","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"borrowCaps","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"borrowGuardianPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"cToken","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"borrowAmount","type":"uint256"}],"name":"borrowVerify","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"contract CToken","name":"cToken","type":"address"}],"name":"checkMembership","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"holder","type":"address"},{"internalType":"contract CToken[]","name":"cTokens","type":"address[]"}],"name":"claimComp","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address[]","name":"holders","type":"address[]"},{"internalType":"contract CToken[]","name":"cTokens","type":"address[]"}],"name":"claimComp","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"holder","type":"address"}],"name":"claimComp","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"closeFactorMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"compAccrued","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"compBorrowState","outputs":[{"internalType":"uint224","name":"index","type":"uint224"},{"internalType":"uint32","name":"block","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"compBorrowerIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"compContributorSpeeds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"compInitialIndex","outputs":[{"internalType":"uint224","name":"","type":"uint224"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"compRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"compSpeeds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"compSupplierIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"compSupplyState","outputs":[{"internalType":"uint224","name":"index","type":"uint224"},{"internalType":"uint32","name":"block","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address[]","name":"cTokens","type":"address[]"}],"name":"enterMarkets","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"cTokenAddress","type":"address"}],"name":"exitMarket","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAccountLiquidity","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getAllMarkets","outputs":[{"internalType":"contract CToken[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAssetsIn","outputs":[{"internalType":"contract CToken[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getBlockNumber","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getCompAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"cTokenModify","type":"address"},{"internalType":"uint256","name":"redeemTokens","type":"uint256"},{"internalType":"uint256","name":"borrowAmount","type":"uint256"}],"name":"getHypotheticalAccountLiquidity","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"implementation","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isComptroller","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"lastContributorBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"cTokenBorrowed","type":"address"},{"internalType":"address","name":"cTokenCollateral","type":"address"},{"internalType":"address","name":"liquidator","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"repayAmount","type":"uint256"}],"name":"liquidateBorrowAllowed","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"cTokenBorrowed","type":"address"},{"internalType":"address","name":"cTokenCollateral","type":"address"},{"internalType":"address","name":"liquidator","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"actualRepayAmount","type":"uint256"},{"internalType":"uint256","name":"seizeTokens","type":"uint256"}],"name":"liquidateBorrowVerify","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"cTokenBorrowed","type":"address"},{"internalType":"address","name":"cTokenCollateral","type":"address"},{"internalType":"uint256","name":"actualRepayAmount","type":"uint256"}],"name":"liquidateCalculateSeizeTokens","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"liquidationIncentiveMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"markets","outputs":[{"internalType":"bool","name":"isListed","type":"bool"},{"internalType":"uint256","name":"collateralFactorMantissa","type":"uint256"},{"internalType":"bool","name":"isComped","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"maxAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"cToken","type":"address"},{"internalType":"address","name":"minter","type":"address"},{"internalType":"uint256","name":"mintAmount","type":"uint256"}],"name":"mintAllowed","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"mintGuardianPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"cToken","type":"address"},{"internalType":"address","name":"minter","type":"address"},{"internalType":"uint256","name":"actualMintAmount","type":"uint256"},{"internalType":"uint256","name":"mintTokens","type":"uint256"}],"name":"mintVerify","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"oracle","outputs":[{"internalType":"contract PriceOracle","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"pauseGuardian","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"pendingAdmin","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"pendingImplementation","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"cToken","type":"address"},{"internalType":"address","name":"redeemer","type":"address"},{"internalType":"uint256","name":"redeemTokens","type":"uint256"}],"name":"redeemAllowed","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"cToken","type":"address"},{"internalType":"address","name":"redeemer","type":"address"},{"internalType":"uint256","name":"redeemAmount","type":"uint256"},{"internalType":"uint256","name":"redeemTokens","type":"uint256"}],"name":"redeemVerify","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"cToken","type":"address"},{"internalType":"address","name":"payer","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"repayAmount","type":"uint256"}],"name":"repayBorrowAllowed","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"cToken","type":"address"},{"internalType":"address","name":"payer","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"actualRepayAmount","type":"uint256"},{"internalType":"uint256","name":"borrowerIndex","type":"uint256"}],"name":"repayBorrowVerify","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"cTokenCollateral","type":"address"},{"internalType":"address","name":"cTokenBorrowed","type":"address"},{"internalType":"address","name":"liquidator","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"seizeTokens","type":"uint256"}],"name":"seizeAllowed","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"seizeGuardianPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"cTokenCollateral","type":"address"},{"internalType":"address","name":"cTokenBorrowed","type":"address"},{"internalType":"address","name":"liquidator","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"seizeTokens","type":"uint256"}],"name":"seizeVerify","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"cToken","type":"address"},{"internalType":"address","name":"src","type":"address"},{"internalType":"address","name":"dst","type":"address"},{"internalType":"uint256","name":"transferTokens","type":"uint256"}],"name":"transferAllowed","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"transferGuardianPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"cToken","type":"address"},{"internalType":"address","name":"src","type":"address"},{"internalType":"address","name":"dst","type":"address"},{"internalType":"uint256","name":"transferTokens","type":"uint256"}],"name":"transferVerify","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"contributor","type":"address"}],"name":"updateContributorRewards","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}] +} \ No newline at end of file diff --git a/packages/liquidator/bKeeper.js b/packages/liquidator/bKeeper.js new file mode 100644 index 000000000..1de0a7956 --- /dev/null +++ b/packages/liquidator/bKeeper.js @@ -0,0 +1,40 @@ +const Web3 = require("web3") + +const secret = require("./secret.json") +const abi = require("./abi.json") + +const web3 = new Web3(secret.nodeEndPoint) + +// checkUpkeep +const check = async () => { + console.log("checking upkeep...") + const bKeeper = new web3.eth.Contract(abi.bKeeper, "0xb5CDc43cefd1826A669Dbd3A8D6180a3B623aef7") + const {upkeepNeeded, performData} = await bKeeper.methods.checkUpkeep("0x").call({gas: 100000000}) + return {upkeepNeeded, performData} +} + +// preform +const preform = async (data) => { + const {privateKey} = secret + const account = web3.eth.accounts.privateKeyToAccount(privateKey) + web3.eth.accounts.wallet.clear() + web3.eth.accounts.wallet.add(account) + console.log("preforming upkeep...") + const bKeeper = new web3.eth.Contract(abi.bKeeper, "0xb5CDc43cefd1826A669Dbd3A8D6180a3B623aef7") + await bKeeper.methods.performUpkeep(data).send({from: account.address, gas:3120853}) +} + +const run = async () => { + const {upkeepNeeded, performData} = await check() + console.log(`upkeep ${upkeepNeeded? "is" : "not"} needed`) + if(upkeepNeeded){ + await preform(performData) + } + console.log("all done!") +} + +module.exports = { + runBKeeper: run +} + + diff --git a/packages/liquidator/bytecodes.json b/packages/liquidator/bytecodes.json new file mode 100644 index 000000000..a81c97a5a --- /dev/null +++ b/packages/liquidator/bytecodes.json @@ -0,0 +1,3 @@ +{ + "LiquidationBotHelper": "0x608060405234801561001057600080fd5b50610cf2806100206000396000f3fe608060405234801561001057600080fd5b50600436106100415760003560e01c80635dbc7e4314610046578063913458101461006f578063d65ba0701461008f575b600080fd5b610059610054366004610a17565b6100b1565b6040516100669190610c96565b60405180910390f35b61008261007d366004610a61565b610519565b6040516100669190610c48565b6100a261009d366004610a61565b610766565b60405161006693929190610be0565b6100b961092f565b6000826001600160a01b0316634bb4695d6040518163ffffffff1660e01b815260040160206040518083038186803b1580156100f457600080fd5b505afa158015610108573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061012c91906109fb565b90506000836001600160a01b031663a1b4d0116040518163ffffffff1660e01b815260040160206040518083038186803b15801561016957600080fd5b505afa15801561017d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101a191906109fb565b6001600160a01b03808816855285811660208601526040516395dd919360e01b8152919250600091908416906395dd9193906101e1908a90600401610ba8565b60206040518083038186803b1580156101f957600080fd5b505afa15801561020d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102319190610ad6565b90506000670de0b6b3a7640000876001600160a01b031663e87554466040518163ffffffff1660e01b815260040160206040518083038186803b15801561027757600080fd5b505afa15801561028b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102af9190610ad6565b8302816102b857fe5b0490506000846001600160a01b0316636f307dc36040518163ffffffff1660e01b815260040160206040518083038186803b1580156102f657600080fd5b505afa15801561030a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061032e91906109fb565b6001600160a01b03166370a08231886040518263ffffffff1660e01b81526004016103599190610ba8565b60206040518083038186803b15801561037157600080fd5b505afa158015610385573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103a99190610ad6565b9050808211156103b7578091505b816103c757506105129350505050565b600080896001600160a01b031663c488847b8888876040518463ffffffff1660e01b81526004016103fa93929190610bbc565b604080518083038186803b15801561041157600080fd5b505afa158015610425573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104499190610aee565b91509150806000148061045b57508115155b1561046d575061051295505050505050565b6040516370a0823160e01b81526000906001600160a01b038816906370a082319061049c908f90600401610ba8565b60206040518083038186803b1580156104b457600080fd5b505afa1580156104c8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104ec9190610ad6565b90508181101561050557818582028161050157fe5b0494505b5050505060408501525050505b9392505050565b606083516000141561052a57610512565b6060845167ffffffffffffffff8111801561054457600080fd5b5060405190808252806020026020018201604052801561057e57816020015b61056b61092f565b8152602001906001900390816105635790505b5090506000805b86518110156106c957600080876001600160a01b0316635ec88c798a85815181106105ac57fe5b60200260200101516040518263ffffffff1660e01b81526004016105d09190610ba8565b60606040518083038186803b1580156105e857600080fd5b505afa1580156105fc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106209190610b11565b9250509150806000148061063357508115155b1561063f5750506106c1565b61064761092f565b60005b88518110156106bc576106848b868151811061066257fe5b60200260200101518b8b848151811061067757fe5b60200260200101516100b1565b6040810151909250156106b457818787806001019850815181106106a457fe5b60200260200101819052506106bc565b60010161064a565b505050505b600101610585565b508067ffffffffffffffff811180156106e157600080fd5b5060405190808252806020026020018201604052801561071b57816020015b61070861092f565b8152602001906001900390816107005790505b50925060005b8181101561075c5782818151811061073557fe5b602002602001015184828151811061074957fe5b6020908102919091010152600101610721565b5050509392505050565b606080606080610777878787610519565b90508051600014156107895750610926565b805167ffffffffffffffff811180156107a157600080fd5b506040519080825280602002602001820160405280156107cb578160200160208202803683370190505b509350805167ffffffffffffffff811180156107e657600080fd5b50604051908082528060200260200182016040528015610810578160200160208202803683370190505b509250805167ffffffffffffffff8111801561082b57600080fd5b50604051908082528060200260200182016040528015610855578160200160208202803683370190505b50915060005b81518110156109235781818151811061087057fe5b60200260200101516000015185828151811061088857fe5b60200260200101906001600160a01b031690816001600160a01b0316815250508181815181106108b457fe5b6020026020010151602001518482815181106108cc57fe5b60200260200101906001600160a01b031690816001600160a01b0316815250508181815181106108f857fe5b60200260200101516040015183828151811061091057fe5b602090810291909101015260010161085b565b50505b93509350939050565b604080516060810182526000808252602082018190529181019190915290565b803561095a81610ca4565b92915050565b600082601f830112610970578081fd5b813567ffffffffffffffff80821115610987578283fd5b6020808302604051828282010181811085821117156109a4578687fd5b6040528481529450818501925085820181870183018810156109c557600080fd5b600091505b848210156109f0576109dc888261094f565b8452928201926001919091019082016109ca565b505050505092915050565b600060208284031215610a0c578081fd5b815161051281610ca4565b600080600060608486031215610a2b578182fd5b8335610a3681610ca4565b92506020840135610a4681610ca4565b91506040840135610a5681610ca4565b809150509250925092565b600080600060608486031215610a75578283fd5b833567ffffffffffffffff80821115610a8c578485fd5b610a9887838801610960565b945060208601359150610aaa82610ca4565b90925060408501359080821115610abf578283fd5b50610acc86828701610960565b9150509250925092565b600060208284031215610ae7578081fd5b5051919050565b60008060408385031215610b00578182fd5b505080516020909101519092909150565b600080600060608486031215610b25578283fd5b8351925060208401519150604084015190509250925092565b6000815180845260208085019450808401835b83811015610b765781516001600160a01b031687529582019590820190600101610b51565b509495945050505050565b80516001600160a01b03908116835260208083015190911690830152604090810151910152565b6001600160a01b0391909116815260200190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b600060608252610bf36060830186610b3e565b602083820381850152610c068287610b3e565b84810360408601528551808252908201925081860190845b81811015610c3a57825185529383019391830191600101610c1e565b509298975050505050505050565b6020808252825182820181905260009190848201906040850190845b81811015610c8a57610c77838551610b81565b9284019260609290920191600101610c64565b50909695505050505050565b6060810161095a8284610b81565b6001600160a01b0381168114610cb957600080fd5b5056fea264697066735822122073638e28ae22d88829cdeabe453272ecf48ca2a03da5273a37e9d58214f6d24d64736f6c634300060b0033" +} \ No newline at end of file diff --git a/packages/liquidator/handler.js b/packages/liquidator/handler.js new file mode 100644 index 000000000..d7584b40e --- /dev/null +++ b/packages/liquidator/handler.js @@ -0,0 +1,63 @@ +'use strict'; +const {runOnLambda} = require('./liquidator') +const {runBKeeper} = require('./bKeeper') + +module.exports.liquidate = async (event) => { + try{ + await runOnLambda() + return { + statusCode: 200, + body: JSON.stringify( + { + message: 'liquidator runOnLambda executed successfully!', + input: event, + }, + null, + 2 + ), + }; + } catch (err){ + console.error(err) + return { + statusCode: 500, + body: JSON.stringify( + { + message: err.message, + input: event, + }, + null, + 2 + ), + }; + } +}; + +module.exports.bKeeper = async (event) => { + try{ + await runBKeeper() + return { + statusCode: 200, + body: JSON.stringify( + { + message: 'bKeeper run executed successfully!', + input: event, + }, + null, + 2 + ), + }; + } catch (err){ + console.error(err) + return { + statusCode: 500, + body: JSON.stringify( + { + message: err.message, + input: event, + }, + null, + 2 + ), + }; + } +}; diff --git a/packages/liquidator/liquidator.js b/packages/liquidator/liquidator.js new file mode 100644 index 000000000..401a4ddba --- /dev/null +++ b/packages/liquidator/liquidator.js @@ -0,0 +1,133 @@ +const Web3 = require("web3") +const axios = require("axios") +const {toWei} = Web3.utils +const secret = require("./secret.json") +const abi = require("./abi.json") +const web3 = new Web3(secret.nodeEndPoint) +const {uploadJsonFile} = require("./s3-client") + + +const fileName = "liquidatorStoredData_hundred_fantom.json" +let storedData = { + accounts: [], + lastCoveredBlock: 20683828 + 1 +} + +function handleEvent(e) { + const to = e.returnValues.account + //if(to !== "0xdbbf063782B8BEbFD34D88E3043531bBC7a8D82b") + if(! storedData.accounts.includes(to)) storedData.accounts.push(to) +} + +async function readAllUsers(startBlock, lastBlock) { + const step = 100000 + const unitroller = new web3.eth.Contract(abi.comptroller, "0x0F390559F258eB8591C8e31Cf0905E97cf36ACE2") + console.log({lastBlock}) + + for(let i = startBlock; i < lastBlock ; i += step) { + let start = i + let end = i + step - 1 + if(end > lastBlock) end = lastBlock + + const events = await unitroller.getPastEvents("MarketEntered", {fromBlock: start, toBlock:end}) + console.log({i}, events.length, storedData.accounts.length) + + for(let j = 0 ; j < events.length ; j++) { + handleEvent(events[j]) + } + } + + console.log("num users", storedData.accounts.length) +} + +async function updateUsers() { + console.log("updating users") + const currBlock = await web3.eth.getBlockNumber() - 10 + if(currBlock > storedData.lastCoveredBlock) { + await readAllUsers(storedData.lastCoveredBlock - 50, currBlock) + } + + storedData.lastCoveredBlock = currBlock + + console.log("updateUsers end") + //setTimeout(updateUsers, 1000 * 60); +} + +async function liquidateCheck(accountsForHelper) { + const helperContract = new web3.eth.Contract(abi.helperAbi, "0xd134A5cE381d7db33596D83de74CBBfC34fbc7dC") + + const comptroller = "0x0F390559F258eB8591C8e31Cf0905E97cf36ACE2" + const bamms1 = ["0xEDC7905a491fF335685e2F2F1552541705138A3D", "0x6d62d6Af9b82CDfA3A7d16601DDbCF8970634d22"] + const bamms2 = [].concat(bamms1).reverse() + const rand = (Math.floor(+new Date() / 1000)) % 2 + console.log({rand}) + const bamms = (rand == 0) ? bamms1 : bamms2 + + //console.log("calling helper") + //console.log({accountsForHelper}) + const result = await helperContract.methods.getInfo(accountsForHelper, comptroller, bamms).call({gas: 40000000000000}) + if(result.length > 0) { + console.log("found liquidation candidate", result[0]) + await doLiquidate(result[0].account, result[0].bamm, result[0].ctoken, result[0].repayAmount) + console.log("done") + } + + //console.log("liquidateCheck end") +} + +async function readStoredDataFromS3 () { + try{ + const {data} = await axios.get(secret.s3Bucket + fileName) + console.log("stored accounts= ", data.accounts.length) + storedData = data + } + catch(err) { + console.log(err) + } +} + +async function writeStoredDataToS3() { + await uploadJsonFile(JSON.stringify(storedData, null, 2), fileName); +} + +async function doLiquidate(user, bammAddress, ctoken, repayAmount) { + const privKey = secret.privateKey + const account = web3.eth.accounts.privateKeyToAccount(privKey) + + web3.eth.accounts.wallet.clear() + web3.eth.accounts.wallet.add(account) + + const bammContract = new web3.eth.Contract(abi.BAMM, bammAddress) + const gasPrice = await axios.get("https://gftm.blockscan.com/gasapi.ashx?apikey=key&method=pendingpooltxgweidata") + .then(({data}) => { + const gasPriceGwei = data.result.standardgaspricegwei.toString() + return toWei(gasPriceGwei, 'gwei') + }) + .catch(err => { + console.error(err) + return null + }) + + await bammContract.methods.liquidateBorrow(user, repayAmount, ctoken).send({from: account.address, gas:3120853, gasPrice }) +} + +async function run() { + await updateUsers() + for(let i = 0 ; i < storedData.accounts.length ; i += 50) { + const slice = storedData.accounts.slice(i, i + 50) + //console.log({slice}) + await liquidateCheck(slice) + } +} + +async function runOnLambda() { + await readStoredDataFromS3() + await run() + await writeStoredDataToS3() +} + +module.exports = { + run, + runOnLambda +} + diff --git a/packages/liquidator/package.json b/packages/liquidator/package.json new file mode 100644 index 000000000..6e33af567 --- /dev/null +++ b/packages/liquidator/package.json @@ -0,0 +1,16 @@ +{ + "name": "liquidator", + "version": "1.0.0", + "description": "", + "main": "liquidator.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "dependencies": { + "aws-sdk": "^2.1037.0", + "axios": "^0.24.0", + "web3": "^1.6.1" + } +} diff --git a/packages/liquidator/run.js b/packages/liquidator/run.js new file mode 100644 index 000000000..2f7e82d96 --- /dev/null +++ b/packages/liquidator/run.js @@ -0,0 +1,9 @@ +const {run} = require('./liquidator') + +const init = async ()=>{ + await run() + setTimeout(init, 1000 * 10 * 60); + console.log("sleeping for 10 minute") +} + +init() diff --git a/packages/liquidator/s3-client.js b/packages/liquidator/s3-client.js new file mode 100644 index 000000000..22e5eb456 --- /dev/null +++ b/packages/liquidator/s3-client.js @@ -0,0 +1,37 @@ +const AWS = require('aws-sdk') +const s3 = new AWS.S3() + +const BUCKET_NAME = 'bp-liquidator' + +const uploadJsonFile = (jsonString, fileName) => { + console.log("========================uploadJsonFile") + return new Promise((resolve, reject) => { + // Read content from the file + + // Setting up S3 upload parameters + const params = { + Bucket: BUCKET_NAME, + Key: fileName, // File name you want to save as in S3 + Body: jsonString, + ACL: 'public-read' + }; + + console.log(params) + + // Uploading files to the bucket + s3.upload(params, function(err, data) { + if (err) { + reject(err) + return + } + console.log(`File uploaded successfully.`); + resolve(data) + }); + + }) +} + + +module.exports = { + uploadJsonFile +} \ No newline at end of file diff --git a/packages/liquidator/serverless.yml b/packages/liquidator/serverless.yml new file mode 100644 index 000000000..aadceab61 --- /dev/null +++ b/packages/liquidator/serverless.yml @@ -0,0 +1,29 @@ +service: hundred-fantom + +frameworkVersion: '2 || 3' + + +provider: + name: aws + runtime: nodejs12.x + profile: bp-sls + lambdaHashingVersion: 20201221 + iam: + role: + statements: # permissions for all of your functions can be set here + - Effect: Allow + Action: # Gives permission to DynamoDB tables in a specific region + - s3:* + Resource: '*' + +functions: + liquidate: + handler: handler.liquidate + timeout: 900 # optional, in seconds, default is 6 max is 15minutes + events: + - schedule: rate(10 minutes) + bKeeper: + handler: handler.bKeeper + timeout: 900 # optional, in seconds, default is 6 max is 15minutes + events: + - schedule: rate(10 minutes)