{ "language": "Solidity", "sources": { "LoanTokenLogicWeth.sol": { "content": "/**\n * Copyright 2017-2022, OokiDao. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0.\n */\n\npragma solidity 0.5.17;\npragma experimental ABIEncoderV2;\n\nimport \"LoanTokenLogicStandard.sol\";\n\n\ncontract LoanTokenLogicWeth is LoanTokenLogicStandard {\n\n constructor()\n public\n LoanTokenLogicStandard()\n {}\n\n function mintWithEther(\n address receiver)\n external\n payable\n nonReentrant\n returns (uint256 mintAmount)\n {\n return _mintToken(\n receiver,\n msg.value\n );\n }\n\n function burnToEther(\n address payable receiver,\n uint256 burnAmount)\n external\n nonReentrant\n returns (uint256 loanAmountPaid)\n {\n loanAmountPaid = _burnToken(\n burnAmount\n );\n\n if (loanAmountPaid != 0) {\n IWethERC20(wethToken).withdraw(loanAmountPaid);\n Address.sendValue(\n receiver,\n loanAmountPaid\n );\n }\n }\n\n /* Internal functions */\n\n // sentAddresses[0]: lender\n // sentAddresses[1]: borrower\n // sentAddresses[2]: receiver\n // sentAddresses[3]: manager\n // sentAmounts[0]: interestRate\n // sentAmounts[1]: newPrincipal\n // sentAmounts[2]: interestInitialAmount\n // sentAmounts[3]: loanTokenSent\n // sentAmounts[4]: collateralTokenSent\n function _verifyTransfers(\n address collateralTokenAddress,\n address[4] memory sentAddresses,\n uint256[5] memory sentAmounts,\n uint256 withdrawalAmount,\n bytes memory loanDataBytes)\n internal\n returns (uint256 msgValue, bytes memory)\n {\n address _wethToken = wethToken;\n address _loanTokenAddress = _wethToken;\n address receiver = sentAddresses[2];\n uint256 newPrincipal = sentAmounts[1];\n uint256 loanTokenSent = sentAmounts[3];\n uint256 collateralTokenSent = sentAmounts[4];\n\n require(_loanTokenAddress != collateralTokenAddress, \"26\");\n\n msgValue = msg.value;\n\n if (withdrawalAmount != 0) { // withdrawOnOpen == true\n IWethERC20(_wethToken).withdraw(withdrawalAmount);\n Address.sendValue(\n address(uint160(receiver)),\n withdrawalAmount\n );\n if (newPrincipal > withdrawalAmount) {\n _safeTransfer(_loanTokenAddress, bZxContract, newPrincipal - withdrawalAmount, \"27\");\n }\n } else {\n _safeTransfer(_loanTokenAddress, bZxContract, newPrincipal, \"27\");\n }\n\n if (collateralTokenSent != 0) {\n loanDataBytes = _checkPermit(collateralTokenAddress, loanDataBytes);\n _safeTransferFrom(collateralTokenAddress, msg.sender, bZxContract, collateralTokenSent, \"28\");\n }\n\n if (loanTokenSent != 0) {\n if (msgValue != 0 && msgValue >= loanTokenSent) {\n IWeth(_wethToken).deposit.value(loanTokenSent)();\n _safeTransfer(_loanTokenAddress, bZxContract, loanTokenSent, \"29\");\n msgValue -= loanTokenSent;\n } else {\n loanDataBytes = _checkPermit(_loanTokenAddress, loanDataBytes);\n _safeTransferFrom(_loanTokenAddress, msg.sender, bZxContract, loanTokenSent, \"29\");\n }\n }\n return (msgValue, loanDataBytes);\n }\n}\n" }, "LoanTokenLogicStandard.sol": { "content": "/**\n * Copyright 2017-2022, OokiDao. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0.\n */\n\npragma solidity 0.5.17;\npragma experimental ABIEncoderV2;\n\nimport \"AdvancedToken.sol\";\nimport \"StorageExtension.sol\";\nimport \"IBZx.sol\";\nimport \"IPriceFeeds.sol\";\nimport \"Flags.sol\";\nimport \"draft-IERC20Permit.sol\";\nimport \"IERC20Detailed.sol\";\nimport \"SafeERC20.sol\";\n\ncontract LoanTokenLogicStandard is AdvancedToken, StorageExtension, Flags {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n using SignedSafeMath for int256;\n\n\n //// CONSTANTS ////\n\n uint256 public constant VERSION = 8;\n\n address internal constant arbitraryCaller = 0x000F400e6818158D541C3EBE45FE3AA0d47372FF; // mainnet\n // address internal constant arbitraryCaller = 0x81e7dddFAD37E6FAb0eccE95f0B508fd40996e6d; // bsc\n // address internal constant arbitraryCaller = 0x81e7dddFAD37E6FAb0eccE95f0B508fd40996e6d; // polygon\n // address internal constant arbitraryCaller = 0x01207468F48822f8535BC96D1Cf18EddDE4A2392; // arbitrum\n // address internal constant arbitraryCaller = 0xcbdF21de4D0aD99Ae02aAdfEd51CdA4C6c4714D9; // evmos\n // address internal constant arbitraryCaller = 0x8150F58218120AB900105C7cDBf0F12061D94441; // optimism\n\n address public constant bZxContract = 0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f; // mainnet\n address public constant wethToken = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet\n\n //address public constant bZxContract = 0x5cfba2639a3db0D9Cc264Aa27B2E6d134EeA486a; // kovan\n //address public constant wethToken = 0xd0A1E359811322d97991E03f863a0C30C2cF029C; // kovan\n\n // address public constant bZxContract = 0xD154eE4982b83a87b0649E5a7DDA1514812aFE1f; // bsc\n // address public constant wethToken = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; // bsc\n\n // address public constant bZxContract = 0x059D60a9CEfBc70b9Ea9FFBb9a041581B1dFA6a8; // polygon\n // address public constant wethToken = 0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270; // polygon\n\n // address public constant bZxContract = 0x37407F3178ffE07a6cF5C847F8f680FEcf319FAB; // arbitrum\n // address public constant wethToken = 0x82aF49447D8a07e3bd95BD0d56f35241523fBab1; // arbitrum\n\n // address public constant bZxContract = 0xAcedbFd5Bc1fb0dDC948579d4195616c05E74Fd1; // optimism\n // address public constant wethToken = 0x4200000000000000000000000000000000000006; // optimism\n\n // address public constant bZxContract = 0xf2FBaD7E59f0DeeE0ec2E724d2b6827Ea1cCf35f; // evmos\n // address public constant wethToken = 0xD4949664cD82660AaE99bEdc034a0deA8A0bd517; // evmos\n\n bytes32 internal constant iToken_ProfitSoFar = 0x37aa2b7d583612f016e4a4de4292cb015139b3d7762663d06a53964912ea2fb6; // keccak256(\"iToken_ProfitSoFar\")\n bytes32 internal constant iToken_LowerAdminAddress = 0x7ad06df6a0af6bd602d90db766e0d5f253b45187c3717a0f9026ea8b10ff0d4b; // keccak256(\"iToken_LowerAdminAddress\")\n bytes32 internal constant iToken_LowerAdminContract = 0x34b31cff1dbd8374124bd4505521fc29cab0f9554a5386ba7d784a4e611c7e31; // keccak256(\"iToken_LowerAdminContract\")\n\n constructor()\n public\n {\n renounceOwnership();\n }\n\n function()\n external\n payable\n {\n require(msg.sender == wethToken, \"fallback not allowed\");\n }\n\n /* Public functions */\n function mint(\n address receiver,\n uint256 depositAmount,\n bytes memory loanDataBytes)\n public\n returns (uint256) // mintAmount\n { \n _checkPermit(loanTokenAddress, loanDataBytes);\n mint(receiver, depositAmount);\n }\n\n function mint(\n address receiver,\n uint256 depositAmount)\n public\n nonReentrant\n pausable\n returns (uint256) // mintAmount\n {\n return _mintToken(\n receiver,\n depositAmount\n );\n }\n\n function burn(\n address receiver,\n uint256 burnAmount)\n public\n nonReentrant\n pausable\n returns (uint256 loanAmountPaid)\n {\n loanAmountPaid = _burnToken(\n burnAmount\n );\n\n if (loanAmountPaid != 0) {\n _safeTransfer(loanTokenAddress, receiver, loanAmountPaid, \"5\");\n }\n }\n\n function flashBorrow(\n uint256 borrowAmount,\n address borrower,\n address target,\n string calldata signature,\n bytes calldata data)\n external\n payable\n nonReentrant\n pausable\n returns (bytes memory)\n {\n require(borrowAmount != 0, \"38\");\n\n _settleInterest(0);\n\n // save before balances\n uint256 beforeEtherBalance = address(this).balance.sub(msg.value);\n uint256 beforeAssetsBalance = _underlyingBalance()\n .add(_totalAssetBorrowStored());\n\n // lock totalAssetSupply for duration of flash loan\n _flTotalAssetSupply = beforeAssetsBalance;\n\n // transfer assets to calling contract\n _safeTransfer(loanTokenAddress, borrower, borrowAmount, \"39\");\n\n emit FlashBorrow(borrower, target, loanTokenAddress, borrowAmount);\n\n bytes memory callData;\n if (bytes(signature).length == 0) {\n callData = data;\n } else {\n callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);\n }\n\n // arbitrary call\n (bool success, bytes memory returnData) = arbitraryCaller.call.value(msg.value)(\n abi.encodeWithSelector(\n 0xde064e0d, // sendCall(address,bytes)\n target,\n callData\n )\n );\n require(success, \"call failed\");\n\n // unlock totalAssetSupply\n _flTotalAssetSupply = 0;\n\t\t\n\t\t// pay flash borrow fees\n IBZx(bZxContract).payFlashBorrowFees(\n borrower,\n borrowAmount,\n flashBorrowFeePercent\n );\n\t\n // verifies return of flash loan\n require(\n address(this).balance >= beforeEtherBalance &&\n _underlyingBalance()\n .add(_totalAssetBorrowStored()) >= beforeAssetsBalance,\n \"40\"\n );\n\n return returnData;\n }\n\n function borrow(\n bytes32 loanId, // 0 if new loan\n uint256 withdrawAmount,\n uint256, // duration in seconds DEPRECATED\n uint256 collateralTokenSent, // if 0, loanId must be provided; any ETH sent must equal this value\n address collateralTokenAddress, // if address(0), this means ETH and ETH must be sent with the call or loanId must be provided\n address borrower,\n address receiver,\n bytes memory loanDataBytes) // arbitrary order data\n public\n payable\n nonReentrant\n pausable\n returns (IBZx.LoanOpenData memory)\n {\n return _borrow(\n loanId,\n withdrawAmount,\n 0,\n collateralTokenSent,\n collateralTokenAddress,\n borrower,\n receiver,\n loanDataBytes\n );\n }\n\n // Called to borrow and immediately get into a position\n function marginTrade(\n bytes32 loanId, // 0 if new loan\n uint256 leverageAmount,\n uint256 loanTokenSent,\n uint256 collateralTokenSent,\n address collateralTokenAddress,\n address trader,\n bytes memory loanDataBytes) // arbitrary order data\n public\n payable\n nonReentrant\n pausable\n returns (IBZx.LoanOpenData memory)\n {\n return _marginTrade(\n loanId,\n leverageAmount,\n loanTokenSent,\n collateralTokenSent,\n collateralTokenAddress,\n trader,\n loanDataBytes\n );\n }\n\n\n function tokenPrice()\n public\n view\n returns (uint256) // price\n {\n return _tokenPrice(_totalAssetSupply(totalAssetBorrow()));\n }\n\n // the current rate being paid by borrowers in active loans\n function borrowInterestRate()\n public\n view\n returns (uint256)\n {\n return _nextBorrowInterestRate(\n _totalAssetBorrowStored(),\n 0,\n poolTWAI()\n );\n }\n\n // the minimum rate that new and existing borrowers will pay after the next borrow\n function nextBorrowInterestRate(\n uint256 borrowAmount)\n external\n view\n returns (uint256)\n {\n return _nextBorrowInterestRate(\n totalAssetBorrow(),\n borrowAmount,\n poolTWAI()\n );\n }\n\n // the current rate being received by suppliers\n function supplyInterestRate()\n external\n view\n returns (uint256)\n {\n uint256 assetBorrow = _totalAssetBorrowStored();\n return _nextSupplyInterestRate(\n _nextBorrowInterestRate(assetBorrow, 0, poolTWAI()),\n assetBorrow,\n _totalAssetSupply(assetBorrow)\n );\n }\n\n // the minimum rate new and existing suppliers will receive after the next supply\n function nextSupplyInterestRate(\n int256 supplyAmount)\n external\n view\n returns (uint256)\n {\n uint256 assetBorrow = totalAssetBorrow();\n uint256 totalSupply = _totalAssetSupply(assetBorrow);\n\n if(supplyAmount >= 0)\n totalSupply = totalSupply.add(uint256(supplyAmount));\n else\n totalSupply = totalSupply.sub(uint256(-supplyAmount));\n\n return _nextSupplyInterestRate(\n _nextBorrowInterestRate(assetBorrow, 0, poolTWAI(), totalSupply),\n assetBorrow,\n totalSupply\n );\n }\n\n\n function totalAssetBorrow()\n public\n view\n returns (uint256)\n {\n return IBZx(bZxContract).getTotalPrincipal(\n address(this),\n address(0) // loanTokenAddress (depreciated)\n );\n }\n\n function _totalAssetBorrowStored()\n internal\n view\n returns (uint256)\n {\n return IBZx(bZxContract).getPoolPrincipalStored(address(this));\n }\n\n function totalAssetSupply()\n external\n view\n returns (uint256)\n {\n return _totalAssetSupply(totalAssetBorrow());\n }\n\n function poolLastInterestRate()\n public\n view\n returns (uint256)\n {\n return IBZx(bZxContract).getPoolLastInterestRate(address(this));\n }\n\n function poolTWAI()\n public\n view\n returns (uint256)\n {\n return IBZx(bZxContract).getTWAI(address(this));\n }\n\n // returns the user's balance of underlying token\n function assetBalanceOf(\n address _owner)\n external\n view\n returns (uint256)\n {\n return balanceOf(_owner)\n .mul(tokenPrice())\n .div(WEI_PRECISION);\n }\n\n function getPoolUtilization()\n external\n view\n returns (uint256)\n {\n uint256 totalBorrow = totalAssetBorrow();\n return _utilizationRate(\n totalBorrow,\n _totalAssetSupply(totalBorrow)\n );\n }\n\n /* Internal functions */\n\n function _mintToken(\n address receiver,\n uint256 depositAmount)\n internal\n pausable\n returns (uint256 mintAmount)\n {\n require (depositAmount != 0, \"17\");\n\n _settleInterest(0);\n\n uint256 currentPrice = _tokenPrice(_totalAssetSupply(_totalAssetBorrowStored()));\n mintAmount = depositAmount\n .mul(WEI_PRECISION)\n .div(currentPrice);\n\n if (msg.value == 0) {\n _safeTransferFrom(loanTokenAddress, msg.sender, address(this), depositAmount, \"18\");\n } else {\n require(msg.value == depositAmount, \"18\");\n IWeth(wethToken).deposit.value(depositAmount)();\n }\n\n _mint(receiver, mintAmount);\n emit Mint(receiver, mintAmount, depositAmount, currentPrice);\n }\n\n function _burnToken(\n uint256 burnAmount)\n internal\n pausable\n returns (uint256 loanAmountPaid)\n {\n require(burnAmount != 0, \"19\");\n\n _settleInterest(0);\n\n if (burnAmount > balanceOf(msg.sender)) {\n require(burnAmount == uint256(-1), \"32\");\n burnAmount = balanceOf(msg.sender);\n }\n\n uint256 currentPrice = _tokenPrice(_totalAssetSupply(_totalAssetBorrowStored()));\n\n uint256 loanAmountOwed = burnAmount\n .mul(currentPrice)\n .div(WEI_PRECISION);\n uint256 loanAmountAvailableInContract = _underlyingBalance();\n\n loanAmountPaid = loanAmountOwed;\n require(loanAmountPaid <= loanAmountAvailableInContract, \"37\");\n _burn(msg.sender, burnAmount);\n emit Burn(msg.sender, burnAmount, loanAmountPaid, currentPrice);\n }\n\n function _borrow(\n bytes32 loanId, // 0 if new loan\n uint256 withdrawAmount,\n uint256 initialLoanDuration, // duration in seconds\n uint256 collateralTokenSent, // if 0, loanId must be provided; any ETH sent must equal this value\n address collateralTokenAddress, // if address(0), this means ETH and ETH must be sent with the call or loanId must be provided\n address borrower,\n address receiver,\n bytes memory loanDataBytes) // arbitrary order data\n internal\n pausable\n returns (IBZx.LoanOpenData memory)\n {\n require(withdrawAmount != 0, \"6\");\n\n require(msg.value == 0 || msg.value == collateralTokenSent, \"7\");\n require(collateralTokenSent != 0 || loanId != 0, \"8\");\n require(collateralTokenAddress != address(0) || msg.value != 0 || loanId != 0, \"9\");\n\n // ensures authorized use of existing loan\n require(loanId == 0 || msg.sender == borrower, \"13\");\n\n _settleInterest(loanId);\n\n if (loanId == 0) {\n loanId = keccak256(abi.encodePacked(\n collateralTokenAddress,\n address(this),\n msg.sender,\n borrower,\n block.timestamp\n ));\n }\n\n if (collateralTokenAddress == address(0)) {\n collateralTokenAddress = wethToken;\n }\n require(collateralTokenAddress != loanTokenAddress, \"10\");\n\n address[4] memory sentAddresses;\n uint256[5] memory sentAmounts;\n\n sentAddresses[0] = address(this); // lender\n sentAddresses[1] = borrower;\n sentAddresses[2] = receiver;\n //sentAddresses[3] = address(0); // manager\n\n //sentAmounts[0] = 0; // interestRate (found later)\n //sentAmounts[1] = 0; // borrowAmount (found later)\n //sentAmounts[2] = 0; // interestInitialAmount (found later)\n //sentAmounts[3] = 0; // loanTokenSent\n sentAmounts[4] = collateralTokenSent;\n\n sentAmounts[1] = withdrawAmount;\n sentAmounts[2] = 0; // interestInitialAmount (depreciated)\n\n return _borrowOrTrade(\n loanId,\n withdrawAmount,\n 0, // leverageAmount (calculated later)\n collateralTokenAddress,\n sentAddresses,\n sentAmounts,\n loanDataBytes // loanDataBytes\n );\n }\n\n function _marginTrade(\n bytes32 loanId, // 0 if new loan\n uint256 leverageAmount,\n uint256 loanTokenSent,\n uint256 collateralTokenSent,\n address collateralTokenAddress,\n address trader,\n bytes memory loanDataBytes)\n internal\n pausable\n returns (IBZx.LoanOpenData memory loanOpenData)\n {\n // ensures authorized use of existing loan\n require(loanId == 0 || msg.sender == trader, \"13\");\n\n _settleInterest(loanId);\n\n if (loanId == 0) {\n loanId = keccak256(abi.encodePacked(\n collateralTokenAddress,\n address(this),\n msg.sender,\n trader,\n block.timestamp\n ));\n }\n\n if (collateralTokenAddress == address(0)) {\n collateralTokenAddress = wethToken;\n }\n require(collateralTokenAddress != loanTokenAddress, \"11\");\n\n address[4] memory sentAddresses;\n uint256[5] memory sentAmounts;\n\n sentAddresses[0] = address(this); // lender\n sentAddresses[1] = trader;\n sentAddresses[2] = trader;\n //sentAddresses[3] = address(0); // manager\n\n //sentAmounts[0] = 0; // interestRate (found later)\n //sentAmounts[1] = 0; // borrowAmount (found later)\n //sentAmounts[2] = 0; // interestInitialAmount (interest is calculated based on fixed-term loan)\n sentAmounts[3] = loanTokenSent;\n sentAmounts[4] = collateralTokenSent;\n\n uint256 totalDeposit;\n uint256 collateralToLoanRate;\n (sentAmounts[1],, totalDeposit, collateralToLoanRate) = _getPreMarginData( // borrowAmount, interestRate, totalDeposit, collateralToLoanRate\n collateralTokenAddress,\n collateralTokenSent,\n loanTokenSent,\n leverageAmount\n );\n require(totalDeposit != 0, \"12\");\n\n loanOpenData = _borrowOrTrade(\n loanId,\n 0, // withdrawAmount\n leverageAmount,\n collateralTokenAddress,\n sentAddresses,\n sentAmounts,\n loanDataBytes\n );\n\n IBZx(bZxContract).setDepositAmount(\n loanOpenData.loanId,\n totalDeposit,\n totalDeposit\n .mul(WEI_PRECISION)\n .div(collateralToLoanRate)\n );\n\n return loanOpenData;\n }\n\n function _settleInterest(\n bytes32 loanId)\n internal\n { \n IBZx(bZxContract).settleInterest(loanId);\n }\n\n function _totalDeposit(\n address collateralTokenAddress,\n uint256 collateralTokenSent,\n uint256 loanTokenSent)\n internal\n view\n returns (uint256 totalDeposit, uint256 collateralToLoanRate)\n {\n uint256 collateralToLoanPrecision;\n (collateralToLoanRate, collateralToLoanPrecision) = IPriceFeeds(IBZx(bZxContract).priceFeeds()).queryRate(\n collateralTokenAddress,\n loanTokenAddress\n );\n require(collateralToLoanRate != 0 && collateralToLoanPrecision != 0, \"20\");\n collateralToLoanRate = collateralToLoanRate\n .mul(WEI_PRECISION)\n .div(collateralToLoanPrecision);\n\n totalDeposit = loanTokenSent;\n if (collateralTokenSent != 0) {\n totalDeposit = collateralTokenSent\n .mul(collateralToLoanRate)\n .div(WEI_PRECISION)\n .add(totalDeposit);\n }\n }\n\n // returns newPrincipal\n function _borrowOrTrade(\n bytes32 loanId,\n uint256 withdrawAmount,\n uint256 leverageAmount,\n address collateralTokenAddress,\n address[4] memory sentAddresses,\n uint256[5] memory sentAmounts,\n bytes memory loanDataBytes)\n internal\n returns (IBZx.LoanOpenData memory)\n {\n require (sentAmounts[1] <= _underlyingBalance() && // newPrincipal\n sentAddresses[1] != address(0), // borrower\n \"24\"\n );\n\n\t if (sentAddresses[2] == address(0)) {\n sentAddresses[2] = sentAddresses[1]; // receiver = borrower\n }\n\n \n // handle transfers prior to adding newPrincipal to loanTokenSent\n (uint256 msgValue, bytes memory loanDataBytes) = _verifyTransfers(\n collateralTokenAddress,\n sentAddresses,\n sentAmounts,\n withdrawAmount,\n loanDataBytes\n );\n\n // adding the loan token portion from the lender to loanTokenSent\n sentAmounts[3] = sentAmounts[3]\n .add(sentAmounts[1]); // newPrincipal\n\n if (withdrawAmount != 0) {\n // withdrawAmount already sent to the borrower, so we aren't sending it to the protocol\n sentAmounts[3] = sentAmounts[3]\n .sub(withdrawAmount);\n }\n\n bool isTorqueLoan = withdrawAmount != 0 ?\n true :\n false;\n\n // converting to initialMargin\n if (leverageAmount != 0) {\n leverageAmount = SafeMath.div(WEI_PRECISION * WEI_PERCENT_PRECISION, leverageAmount);\n }\n\n return IBZx(bZxContract).borrowOrTradeFromPool.value(msgValue)(\n collateralTokenAddress,\n loanId,\n isTorqueLoan,\n leverageAmount, // initialMargin\n sentAddresses,\n sentAmounts,\n loanDataBytes\n );\n }\n\n // sentAddresses[0]: lender\n // sentAddresses[1]: borrower\n // sentAddresses[2]: receiver\n // sentAddresses[3]: manager\n // sentAmounts[0]: interestRate\n // sentAmounts[1]: newPrincipal\n // sentAmounts[2]: interestInitialAmount\n // sentAmounts[3]: loanTokenSent\n // sentAmounts[4]: collateralTokenSent\n function _verifyTransfers(\n address collateralTokenAddress,\n address[4] memory sentAddresses,\n uint256[5] memory sentAmounts,\n uint256 withdrawalAmount,\n bytes memory loanDataBytes)\n internal\n returns (uint256 msgValue, bytes memory)\n {\n address _wethToken = wethToken;\n address _loanTokenAddress = loanTokenAddress;\n address receiver = sentAddresses[2];\n uint256 newPrincipal = sentAmounts[1];\n uint256 loanTokenSent = sentAmounts[3];\n uint256 collateralTokenSent = sentAmounts[4];\n\n require(_loanTokenAddress != collateralTokenAddress, \"26\");\n\n msgValue = msg.value;\n\n if (withdrawalAmount != 0) { // withdrawOnOpen == true\n _safeTransfer(_loanTokenAddress, receiver, withdrawalAmount, \"27\");\n if (newPrincipal > withdrawalAmount) {\n _safeTransfer(_loanTokenAddress, bZxContract, newPrincipal - withdrawalAmount, \"27\");\n }\n } else {\n _safeTransfer(_loanTokenAddress, bZxContract, newPrincipal, \"27\");\n }\n\n if (collateralTokenSent != 0) {\n if (collateralTokenAddress == _wethToken && msgValue != 0 && msgValue >= collateralTokenSent) {\n IWeth(_wethToken).deposit.value(collateralTokenSent)();\n _safeTransfer(collateralTokenAddress, bZxContract, collateralTokenSent, \"28\");\n msgValue -= collateralTokenSent;\n } else {\n loanDataBytes = _checkPermit(collateralTokenAddress, loanDataBytes);\n _safeTransferFrom(collateralTokenAddress, msg.sender, bZxContract, collateralTokenSent, \"28\");\n }\n }\n\n if (loanTokenSent != 0) {\n loanDataBytes = _checkPermit(_loanTokenAddress, loanDataBytes);\n _safeTransferFrom(_loanTokenAddress, msg.sender, bZxContract, loanTokenSent, \"29\");\n }\n return (msgValue, loanDataBytes);\n }\n\n function _safeTransfer(\n address token,\n address to,\n uint256 amount,\n string memory errorMsg)\n internal\n {\n _callOptionalReturn(\n token,\n abi.encodeWithSelector(IERC20(token).transfer.selector, to, amount),\n errorMsg\n );\n }\n\n function _safeTransferFrom(\n address token,\n address from,\n address to,\n uint256 amount,\n string memory errorMsg)\n internal\n {\n _callOptionalReturn(\n token,\n abi.encodeWithSelector(IERC20(token).transferFrom.selector, from, to, amount),\n errorMsg\n );\n }\n\n function _checkPermit(address token, bytes memory loanDataBytes) internal returns (bytes memory) {\n if (loanDataBytes.length != 0) {\n if(abi.decode(loanDataBytes, (uint128)) & WITH_PERMIT != 0) {\n (uint128 f, bytes[] memory payload) = abi.decode(\n loanDataBytes,\n (uint128, bytes[])\n );\n (address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) = abi.decode(payload[2], (address, address, uint, uint, uint8, bytes32, bytes32));\n require(spender == address(this), \"Permit\");\n IERC20Permit(token).permit(owner, spender, value, deadline, v, r, s);\n payload[2] = \"\";\n loanDataBytes = abi.encode(f, payload);\n }\n }\n return loanDataBytes;\n }\n\n function _callOptionalReturn(\n address token,\n bytes memory data,\n string memory errorMsg)\n internal\n {\n (bool success, bytes memory returndata) = token.call(data);\n require(success, errorMsg);\n\n if (returndata.length != 0) {\n require(abi.decode(returndata, (bool)), errorMsg);\n }\n }\n\n\n function _nextSupplyInterestRate(\n uint256 nextBorrowRate,\n uint256 assetBorrow,\n uint256 assetSupply)\n public\n view\n returns (uint256)\n {\n if (assetBorrow != 0 && assetSupply >= assetBorrow) {\n return nextBorrowRate\n .mul(_utilizationRate(assetBorrow, assetSupply))\n .mul(SafeMath.sub(WEI_PERCENT_PRECISION, IBZx(bZxContract).lendingFeePercent()))\n .div(WEI_PERCENT_PRECISION * WEI_PERCENT_PRECISION);\n }\n }\n\n function _nextBorrowInterestRate(\n uint256 totalBorrow,\n uint256 newBorrowNotYetRealized,\n uint256 lastIR)\n public\n view\n returns (uint256 nextRate)\n {\n\t return _nextBorrowInterestRate(\n\t totalBorrow,\n newBorrowNotYetRealized,\n lastIR,\n _totalAssetSupply(totalBorrow)\n );\n }\n\n /* Internal View functions */\n function _underlyingBalance()\n internal\n view\n returns (uint256)\n {\n return IERC20(loanTokenAddress).balanceOf(address(this));\n }\n\n function _nextBorrowInterestRate(\n uint256 totalBorrow,\n uint256 newBorrowNotYetRealized,\n uint256 lastIR,\n uint256 assetSupply)\n internal\n view\n returns (uint256 nextRate)\n {\n uint256 utilRate = _utilizationRate(\n totalBorrow.add(newBorrowNotYetRealized),\n assetSupply\n );\n\n //utilRate from 0e18 to 100e18\n nextRate = rateHelper.calculateIR(utilRate, lastIR);\n }\n\n function _tokenPrice(\n uint256 assetSupply)\n internal\n view\n returns (uint256)\n {\n uint256 totalTokenSupply = _totalSupply;\n\n return totalTokenSupply != 0 ?\n assetSupply\n .mul(WEI_PRECISION)\n .div(totalTokenSupply) : initialPrice;\n }\n\n function _getPreMarginData(\n address collateralTokenAddress,\n uint256 collateralTokenSent,\n uint256 loanTokenSent,\n uint256 leverageAmount)\n internal\n view\n returns (uint256 borrowAmount, uint256 interestRate, uint256 totalDeposit, uint256 collateralToLoanRate)\n {\n (totalDeposit, collateralToLoanRate) = _totalDeposit(\n collateralTokenAddress,\n collateralTokenSent,\n loanTokenSent\n );\n\n uint256 initialMargin = SafeMath.div(WEI_PRECISION * WEI_PERCENT_PRECISION, leverageAmount);\n\n // assumes that loan and collateral token are the same\n borrowAmount = totalDeposit\n .mul(WEI_PERCENT_PRECISION)\n .div(initialMargin);\n }\n\n function _totalAssetSupply(\n uint256 totalBorrow)\n internal\n view\n returns (uint256 totalSupply)\n {\n totalSupply = _flTotalAssetSupply; // temporary locked totalAssetSupply during a flash loan transaction\n if (totalSupply == 0) {\n totalSupply = _underlyingBalance()\n .add(totalBorrow);\n }\n }\n\n function _utilizationRate(\n uint256 assetBorrow,\n uint256 assetSupply)\n internal\n pure\n returns (uint256)\n {\n if (assetSupply != 0) {\n // U = total_borrow / total_supply\n return assetBorrow\n .mul(WEI_PERCENT_PRECISION)\n .div(assetSupply);\n }\n }\n\n\n function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) public {\n require(deadline >= block.timestamp, \"OOKI: EXPIRED\");\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))\n )\n );\n address recoveredAddress = ecrecover(digest, v, r, s);\n require(recoveredAddress != address(0) && recoveredAddress == owner, \"OOKI: INVALID_SIGNATURE\");\n _approve(owner, spender, value);\n }\n\n function initializeDomainSeparator() public onlyGuardian {\n uint chainId;\n assembly {\n chainId := chainid\n }\n DOMAIN_SEPARATOR = keccak256(\n abi.encode(\n keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),\n keccak256(bytes(name)),\n keccak256(bytes('1')),\n chainId,\n address(this)\n )\n );\n }\n\n function initialize(\n address _loanTokenAddress,\n string memory _name,\n string memory _symbol)\n public onlyGuardian\n {\n loanTokenAddress = _loanTokenAddress;\n\n name = _name;\n symbol = _symbol;\n decimals = IERC20Detailed(loanTokenAddress).decimals();\n\n initialPrice = WEI_PRECISION; // starting price of 1\n\n IERC20(_loanTokenAddress).safeApprove(bZxContract, uint256(-1));\n }\n\n\n function setDemandCurve(ICurvedInterestRate _rateHelper) public onlyOwner {\n require(address(_rateHelper) != address(0), \"no zero address\");\n rateHelper = _rateHelper;\n }\n\n function updateFlashBorrowFeePercent(uint256 newFeePercent) public onlyOwner {\n flashBorrowFeePercent = newFeePercent;\n }\n}\n\n" }, "AdvancedToken.sol": { "content": "/**\n * Copyright 2017-2022, OokiDao. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0.\n */\n\npragma solidity 0.5.17;\n\nimport \"AdvancedTokenStorage.sol\";\n\n// Below is a copy implementation from openzeppelin 2.5.0, not a single line is changed\ncontract AdvancedToken is AdvancedTokenStorage {\n using SafeMath for uint256;\n\n \n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `recipient` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address recipient, uint256 amount) public returns (bool) {\n _transfer(_msgSender(), recipient, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public returns (bool) {\n _approve(_msgSender(), spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20};\n *\n * Requirements:\n * - `sender` and `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n * - the caller must have allowance for `sender`'s tokens of at least\n * `amount`.\n */\n function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {\n _transfer(sender, recipient, amount);\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n return true;\n }\n\n /**\n * @dev Moves tokens `amount` from `sender` to `recipient`.\n *\n * This is internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `sender` cannot be the zero address.\n * - `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n */\n function _transfer(address sender, address recipient, uint256 amount) internal {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n _balances[recipient] = _balances[recipient].add(amount);\n emit Transfer(sender, recipient, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements\n *\n * - `to` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _totalSupply = _totalSupply.add(amount);\n _balances[account] = _balances[account].add(amount);\n emit Transfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n _totalSupply = _totalSupply.sub(amount);\n emit Transfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.\n *\n * This is internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(address owner, address spender, uint256 amount) internal {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`.`amount` is then deducted\n * from the caller's allowance.\n *\n * See {_burn} and {_approve}.\n */\n function _burnFrom(address account, uint256 amount) internal {\n _burn(account, amount);\n _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, \"ERC20: burn amount exceeds allowance\"));\n }\n}\n" }, "AdvancedTokenStorage.sol": { "content": "/**\n * Copyright 2017-2022, OokiDao. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0.\n */\n\npragma solidity 0.5.17;\n\nimport \"LoanTokenBase.sol\";\n\n\ncontract AdvancedTokenStorage is LoanTokenBase {\n using SafeMath for uint256;\n\n event Transfer(\n address indexed from,\n address indexed to,\n uint256 value\n );\n\n event Approval(\n address indexed owner,\n address indexed spender,\n uint256 value\n );\n\n event Mint(\n address indexed minter,\n uint256 tokenAmount,\n uint256 assetAmount,\n uint256 price\n );\n\n event Burn(\n address indexed burner,\n uint256 tokenAmount,\n uint256 assetAmount,\n uint256 price\n );\n\n event FlashBorrow(\n address borrower,\n address target,\n address loanToken,\n uint256 loanAmount\n );\n\n mapping(address => uint256) internal _balances;\n mapping (address => mapping (address => uint256)) internal _allowances;\n uint256 internal _totalSupply;\n\n}\n" }, "LoanTokenBase.sol": { "content": "/**\n * Copyright 2017-2022, OokiDao. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0.\n */\n\npragma solidity 0.5.17;\n\nimport \"SafeMath.sol\";\nimport \"SignedSafeMath.sol\";\nimport \"ReentrancyGuard.sol\";\nimport \"Ownable.sol\";\nimport \"Address.sol\";\nimport \"IWethERC20.sol\";\nimport \"PausableGuardian.sol\";\n\n\ncontract LoanTokenBase is ReentrancyGuard, Ownable, PausableGuardian {\n\n uint256 internal constant WEI_PRECISION = 10**18;\n uint256 internal constant WEI_PERCENT_PRECISION = 10**20;\n\n int256 internal constant sWEI_PRECISION = 10**18;\n\n string public name;\n string public symbol;\n uint8 public decimals;\n\n // uint88 for tight packing -> 8 + 88 + 160 = 256\n uint88 internal lastSettleTime_;\n\n address public loanTokenAddress;\n\n uint256 internal baseRate_UNUSED;\n uint256 internal rateMultiplier_UNUSED;\n uint256 internal lowUtilBaseRate_UNUSED;\n uint256 internal lowUtilRateMultiplier_UNUSED;\n uint256 internal targetLevel_UNUSED;\n uint256 internal kinkLevel_UNUSED;\n uint256 internal maxScaleRate_UNUSED;\n\n uint256 internal _flTotalAssetSupply;\n uint256 internal checkpointSupply_UNUSED;\n uint256 public initialPrice;\n\n mapping (uint256 => bytes32) public loanParamsIds; // mapping of keccak256(collateralToken, isTorqueLoan) to loanParamsId\n mapping (address => uint256) internal checkpointPrices_DEPRECATED; // price of token at last user checkpoint\n}" }, "SafeMath.sol": { "content": "pragma solidity ^0.5.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n * - Subtraction cannot overflow.\n *\n * _Available since v2.4.0._\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n uint256 c = a - b;\n\n return c;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n *\n * _Available since v2.4.0._\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n // Solidity only automatically asserts when dividing by 0\n require(b > 0, errorMessage);\n uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n return c;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return mod(a, b, \"SafeMath: modulo by zero\");\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts with custom message when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n *\n * _Available since v2.4.0._\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b != 0, errorMessage);\n return a % b;\n }\n}\n" }, "SignedSafeMath.sol": { "content": "pragma solidity >=0.5.0 <0.6.0;\n\n/**\n * @title SignedSafeMath\n * @dev Signed math operations with safety checks that revert on error.\n */\nlibrary SignedSafeMath {\n int256 constant private _INT256_MIN = -2**255;\n\n /**\n * @dev Returns the multiplication of two signed integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(int256 a, int256 b) internal pure returns (int256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n require(!(a == -1 && b == _INT256_MIN), \"SignedSafeMath: multiplication overflow\");\n\n int256 c = a * b;\n require(c / a == b, \"SignedSafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two signed integers. Reverts on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(int256 a, int256 b) internal pure returns (int256) {\n require(b != 0, \"SignedSafeMath: division by zero\");\n require(!(b == -1 && a == _INT256_MIN), \"SignedSafeMath: division overflow\");\n\n int256 c = a / b;\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two signed integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a - b;\n require((b >= 0 && c <= a) || (b < 0 && c > a), \"SignedSafeMath: subtraction overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the addition of two signed integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a + b;\n require((b >= 0 && c >= a) || (b < 0 && c < a), \"SignedSafeMath: addition overflow\");\n\n return c;\n }\n}" }, "ReentrancyGuard.sol": { "content": "\npragma solidity >=0.5.0 <0.6.0;\n\n\n/**\n * @title Helps contracts guard against reentrancy attacks.\n * @author Remco Bloemen , Eenae \n * @dev If you mark a function `nonReentrant`, you should also\n * mark it `external`.\n */\ncontract ReentrancyGuard {\n\n /// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs.\n /// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056\n uint256 internal constant REENTRANCY_GUARD_FREE = 1;\n\n /// @dev Constant for locked guard state\n uint256 internal constant REENTRANCY_GUARD_LOCKED = 2;\n\n /**\n * @dev We use a single lock for the whole contract.\n */\n uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE;\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * If you mark a function `nonReentrant`, you should also\n * mark it `external`. Calling one `nonReentrant` function from\n * another is not supported. Instead, you can implement a\n * `private` function doing the actual work, and an `external`\n * wrapper marked as `nonReentrant`.\n */\n modifier nonReentrant() {\n require(reentrancyLock == REENTRANCY_GUARD_FREE, \"nonReentrant\");\n reentrancyLock = REENTRANCY_GUARD_LOCKED;\n _;\n reentrancyLock = REENTRANCY_GUARD_FREE;\n }\n\n}\n" }, "Ownable.sol": { "content": "pragma solidity ^0.5.0;\n\nimport \"Context.sol\";\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\ncontract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor () internal {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(isOwner(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Returns true if the caller is the current owner.\n */\n function isOwner() public view returns (bool) {\n return _msgSender() == _owner;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public onlyOwner {\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n */\n function _transferOwnership(address newOwner) internal {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n}\n" }, "Context.sol": { "content": "pragma solidity ^0.5.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\ncontract Context {\n // Empty internal constructor, to prevent people from mistakenly deploying\n // an instance of this contract, which should be used via inheritance.\n constructor () internal { }\n // solhint-disable-previous-line no-empty-blocks\n\n function _msgSender() internal view returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n}\n" }, "Address.sol": { "content": "pragma solidity ^0.5.5;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following \n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // According to EIP-1052, 0x0 is the value returned for not-yet created accounts\n // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned\n // for accounts without code, i.e. `keccak256('')`\n bytes32 codehash;\n bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\n // solhint-disable-next-line no-inline-assembly\n assembly { codehash := extcodehash(account) }\n return (codehash != accountHash && codehash != 0x0);\n }\n\n /**\n * @dev Converts an `address` into `address payable`. Note that this is\n * simply a type cast: the actual underlying value is not changed.\n *\n * _Available since v2.4.0._\n */\n function toPayable(address account) internal pure returns (address payable) {\n return address(uint160(account));\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n *\n * _Available since v2.4.0._\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-call-value\n (bool success, ) = recipient.call.value(amount)(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n}\n" }, "IWethERC20.sol": { "content": "/**\n * Copyright 2017-2022, OokiDao. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0.\n */\n\npragma solidity >=0.5.0 <0.6.0;\n\nimport \"IWeth.sol\";\nimport \"IERC20.sol\";\n\n\ncontract IWethERC20 is IWeth, IERC20 {}\n" }, "IWeth.sol": { "content": "/**\n * Copyright 2017-2022, OokiDao. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0.\n */\n\npragma solidity >=0.5.0 <0.6.0;\n\n\ninterface IWeth {\n function deposit() external payable;\n function withdraw(uint256 wad) external;\n}\n" }, "IERC20.sol": { "content": "pragma solidity ^0.5.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP. Does not include\n * the optional functions; to access them see {ERC20Detailed}.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n" }, "PausableGuardian.sol": { "content": "/**\n * Copyright 2017-2022, OokiDao. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0.\n */\n\npragma solidity 0.5.17;\n\nimport \"Ownable.sol\";\n\n\ncontract PausableGuardian is Ownable {\n\n // keccak256(\"Pausable_FunctionPause\")\n bytes32 internal constant Pausable_FunctionPause = 0xa7143c84d793a15503da6f19bf9119a2dac94448ca45d77c8bf08f57b2e91047;\n\n // keccak256(\"Pausable_GuardianAddress\")\n bytes32 internal constant Pausable_GuardianAddress = 0x80e6706973d0c59541550537fd6a33b971efad732635e6c3b99fb01006803cdf;\n\n modifier pausable {\n require(!_isPaused(msg.sig), \"paused\");\n _;\n }\n\n modifier onlyGuardian {\n require(msg.sender == getGuardian() || msg.sender == owner(), \"unauthorized\");\n _;\n }\n\n function _isPaused(bytes4 sig) public view returns (bool isPaused) {\n bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause));\n assembly {\n isPaused := sload(slot)\n }\n }\n\n function toggleFunctionPause(bytes4 sig) public onlyGuardian {\n bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause));\n assembly {\n sstore(slot, 1)\n }\n }\n\n function toggleFunctionUnPause(bytes4 sig) public onlyGuardian {\n // only DAO can unpause, and adding guardian temporarily\n bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause));\n assembly {\n sstore(slot, 0)\n }\n }\n\n function changeGuardian(address newGuardian) public onlyGuardian {\n assembly {\n sstore(Pausable_GuardianAddress, newGuardian)\n }\n }\n\n function getGuardian() public view returns (address guardian) {\n assembly {\n guardian := sload(Pausable_GuardianAddress)\n }\n }\n\n function pause(bytes4 [] calldata sig)\n external\n onlyGuardian\n {\n for(uint256 i = 0; i < sig.length; ++i){\n toggleFunctionPause(sig[i]);\n }\n }\n\n function unpause(bytes4 [] calldata sig)\n external\n onlyGuardian\n {\n for(uint256 i = 0; i < sig.length; ++i){\n toggleFunctionUnPause(sig[i]);\n }\n }\n}\n" }, "StorageExtension.sol": { "content": "/**\n * Copyright 2017-2022, OokiDao. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0.\n */\n\npragma solidity 0.5.17;\n\nimport \"ICurvedInterestRate.sol\";\n\n\ncontract StorageExtension {\n\n address internal target_;\n uint256 public flashBorrowFeePercent; // set to 0.03%\n ICurvedInterestRate rateHelper;\n\n bytes32 public DOMAIN_SEPARATOR;\n // keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;\n mapping(address => uint) public nonces;\n}" }, "ICurvedInterestRate.sol": { "content": "/**\n * Copyright 2017-2022, OokiDao. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0.\n */\n\n// SPDX-License-Identifier: Apache-2.0\n\npragma solidity >=0.5.0 <0.9.0;\n\ninterface ICurvedInterestRate {\n function getInterestRate(\n uint256 _U,\n uint256 _a,\n uint256 _b,\n uint256 _UR_MAX,\n uint256 _IR_ABSOLUTE_MIN\n ) external pure returns (uint256 interestRate);\n\n // function getAB(uint256 _IR1, address _OWNER) external pure returns (uint256 a, uint256 b);\n\n function getAB(\n uint256 _IR1,\n uint256 _IR2,\n uint256 _UR1,\n uint256 _UR2,\n uint256 _IR_MIN,\n uint256 _IR_MAX\n ) external pure returns (uint256 a, uint256 b);\n\n function calculateIR(uint256 _U, uint256 _IR1) external view returns (uint256 interestRate);\n}\n" }, "IBZx.sol": { "content": "/**\n * Copyright 2017-2022, OokiDao. All Rights Reserved.\n * Licensed under the Apache-2.0\n */\n// SPDX-License-Identifier: Apache-2.0\npragma solidity >=0.5.0 <0.9.0;\npragma experimental ABIEncoderV2;\n\n/// @title A proxy interface for The Protocol\n/// @author bZeroX\n/// @notice This is just an interface, not to be deployed itself.\n/// @dev This interface is to be used for the protocol interactions.\ninterface IBZx {\n ////// Protocol //////\n\n /// @dev adds or replaces existing proxy module\n /// @param target target proxy module address\n function replaceContract(address target) external;\n\n /// @dev updates all proxy modules addreses and function signatures.\n /// sigsArr and targetsArr should be of equal length\n /// @param sigsArr array of function signatures\n /// @param targetsArr array of target proxy module addresses\n function setTargets(\n string[] calldata sigsArr,\n address[] calldata targetsArr\n ) external;\n\n /// @dev returns protocol module address given a function signature\n /// @return module address\n function getTarget(string calldata sig) external view returns (address);\n\n ////// Protocol Settings //////\n\n /// @dev sets price feed contract address. The contract on the addres should implement IPriceFeeds interface\n /// @param newContract module address for the IPriceFeeds implementation\n function setPriceFeedContract(address newContract) external;\n\n /// @dev sets swaps contract address. The contract on the addres should implement ISwapsImpl interface\n /// @param newContract module address for the ISwapsImpl implementation\n function setSwapsImplContract(address newContract) external;\n\n /// @dev sets loan pool with assets. Accepts two arrays of equal length\n /// @param pools array of address of pools\n /// @param assets array of addresses of assets\n function setLoanPool(address[] calldata pools, address[] calldata assets)\n external;\n\n /// @dev updates list of supported tokens, it can be use also to disable or enable particualr token\n /// @param addrs array of address of pools\n /// @param toggles array of addresses of assets\n /// @param withApprovals resets tokens to unlimited approval with the swaps integration (kyber, etc.)\n function setSupportedTokens(\n address[] calldata addrs,\n bool[] calldata toggles,\n bool withApprovals\n ) external;\n\n /// @dev sets approvals for tokens for specific dexes on dex selector\n /// @param tokens tokens to have their approvals set\n /// @param dexIDs IDs of the swap impls on dex selector\n function setApprovals(address[] calldata tokens, uint256[] calldata dexIDs) external;\n\n /// @dev sets lending fee with WEI_PERCENT_PRECISION\n /// @param newValue lending fee percent\n function setLendingFeePercent(uint256 newValue) external;\n\n /// @dev sets trading fee with WEI_PERCENT_PRECISION\n /// @param newValue trading fee percent\n function setTradingFeePercent(uint256 newValue) external;\n\n /// @dev sets borrowing fee with WEI_PERCENT_PRECISION\n /// @param newValue borrowing fee percent\n function setBorrowingFeePercent(uint256 newValue) external;\n\n /// @dev sets affiliate fee with WEI_PERCENT_PRECISION\n /// @param newValue affiliate fee percent\n function setAffiliateFeePercent(uint256 newValue) external;\n\n /// @dev sets liquidation inncetive percent per loan per token. This is the profit percent\n /// that liquidator gets in the process of liquidating.\n /// @param loanTokens array list of loan tokens\n /// @param collateralTokens array list of collateral tokens\n /// @param amounts array list of liquidation inncetive amount\n function setLiquidationIncentivePercent(\n address[] calldata loanTokens,\n address[] calldata collateralTokens,\n uint256[] calldata amounts\n ) external;\n\n /// @dev sets max swap rate slippage percent.\n /// @param newAmount max swap rate slippage percent.\n function setMaxDisagreement(uint256 newAmount) external;\n\n /// TODO\n function setSourceBufferPercent(uint256 newAmount) external;\n\n /// @dev sets maximum supported swap size in ETH\n /// @param newAmount max swap size in ETH.\n function setMaxSwapSize(uint256 newAmount) external;\n\n /// @dev sets fee controller address\n /// @param newController address of the new fees controller\n function setFeesController(address newController) external;\n\n /// @dev withdraws lending fees to receiver. Only can be called by feesController address\n /// @param tokens array of token addresses.\n /// @param receiver fees receiver address\n /// @return amounts array of amounts withdrawn\n function withdrawFees(\n address[] calldata tokens,\n address receiver,\n FeeClaimType feeType\n ) external returns (uint256[] memory amounts);\n\n /*\n Targets still exist, but functions are decommissioned:\n\n /// @dev withdraw protocol token (BZRX) from vesting contract vBZRX\n /// @param receiver address of BZRX tokens claimed\n /// @param amount of BZRX token to be claimed. max is claimed if amount is greater than balance.\n /// @return rewardToken reward token address\n /// @return withdrawAmount amount\n function withdrawProtocolToken(address receiver, uint256 amount)\n external\n returns (address rewardToken, uint256 withdrawAmount);\n\n /// @dev depozit protocol token (BZRX)\n /// @param amount address of BZRX tokens to deposit\n function depositProtocolToken(uint256 amount) external;\n\n function grantRewards(address[] calldata users, uint256[] calldata amounts)\n external\n returns (uint256 totalAmount);*/\n\n // NOTE: this doesn't sanitize inputs -> inaccurate values may be returned if there are duplicate token inputs\n function queryFees(address[] calldata tokens, FeeClaimType feeType)\n external\n view\n returns (uint256[] memory amountsHeld, uint256[] memory amountsPaid);\n\n function priceFeeds() external view returns (address);\n\n function swapsImpl() external view returns (address);\n\n function logicTargets(bytes4) external view returns (address);\n\n function loans(bytes32) external view returns (Loan memory);\n\n function loanParams(bytes32) external view returns (LoanParams memory);\n\n // we don't use this yet\n // function lenderOrders(address, bytes32) external returns (Order memory);\n // function borrowerOrders(address, bytes32) external returns (Order memory);\n\n function delegatedManagers(bytes32, address) external view returns (bool);\n\n function lenderInterest(address, address)\n external\n view\n returns (LenderInterest memory);\n\n function loanInterest(bytes32) external view returns (LoanInterest memory);\n\n function feesController() external view returns (address);\n\n function lendingFeePercent() external view returns (uint256);\n\n function lendingFeeTokensHeld(address) external view returns (uint256);\n\n function lendingFeeTokensPaid(address) external view returns (uint256);\n\n function borrowingFeePercent() external view returns (uint256);\n\n function borrowingFeeTokensHeld(address) external view returns (uint256);\n\n function borrowingFeeTokensPaid(address) external view returns (uint256);\n\n function tradingFeeTokensHeld(address) external view returns (uint256);\n\n function tradingFeeTokensPaid(address) external view returns (uint256);\n\n function tradingFeePercent() external view returns (uint256);\n\n function protocolTokenHeld() external view returns (uint256);\n\n function protocolTokenPaid() external view returns (uint256);\n\n function affiliateFeePercent() external view returns (uint256);\n\n function liquidationIncentivePercent(address, address)\n external\n view\n returns (uint256);\n\n function loanPoolToUnderlying(address) external view returns (address);\n\n function underlyingToLoanPool(address) external view returns (address);\n\n function supportedTokens(address) external view returns (bool);\n\n function maxDisagreement() external view returns (uint256);\n\n function sourceBufferPercent() external view returns (uint256);\n\n function maxSwapSize() external view returns (uint256);\n\n /// @dev get list of loan pools in the system. Ordering is not guaranteed\n /// @param start start index\n /// @param count number of pools to return\n /// @return loanPoolsList array of loan pools\n function getLoanPoolsList(uint256 start, uint256 count)\n external\n view\n returns (address[] memory loanPoolsList);\n\n /// @dev checks whether addreess is a loan pool address\n /// @return boolean\n function isLoanPool(address loanPool) external view returns (bool);\n\n ////// Loan Settings //////\n\n /// @dev creates new loan param settings\n /// @param loanParamsList array of LoanParams\n /// @return loanParamsIdList array of loan ids created\n function setupLoanParams(LoanParams[] calldata loanParamsList)\n external\n returns (bytes32[] memory loanParamsIdList);\n\n function setupLoanPoolTWAI(address pool) external;\n\n function setTWAISettings(uint32 delta, uint32 secondsAgo) external;\n\n /// @dev Deactivates LoanParams for future loans. Active loans using it are unaffected.\n /// @param loanParamsIdList array of loan ids\n function disableLoanParams(bytes32[] calldata loanParamsIdList) external;\n\n /// @dev Modifies or adds new loan params, guardianOnly\n /// @param loanParamsList array of loanParams\n function modifyLoanParams(LoanParams[] calldata loanParamsList) external;\n\n /// @dev gets array of LoanParams by given ids\n /// @param loanParamsIdList array of loan ids\n /// @return loanParamsList array of LoanParams\n function getLoanParams(bytes32[] calldata loanParamsIdList)\n external\n view\n returns (LoanParams[] memory loanParamsList);\n\n /// @dev Enumerates LoanParams in the system by owner\n /// @param owner of the loan params\n /// @param start number of loans to return\n /// @param count total number of the items\n /// @return loanParamsList array of LoanParams\n function getLoanParamsList(\n address owner,\n uint256 start,\n uint256 count\n ) external view returns (bytes32[] memory loanParamsList);\n\n /// @dev returns total loan principal for token address\n /// @param lender address\n /// @param loanToken address\n /// @return total principal of the loan\n function getTotalPrincipal(address lender, address loanToken)\n external\n view\n returns (uint256);\n\n /// @dev returns total principal for a loan pool that was last settled\n /// @param pool address\n /// @return total stored principal of the loan\n function getPoolPrincipalStored(address pool)\n external\n view\n returns (uint256);\n\n /// @dev returns the last interest rate founnd during interest settlement\n /// @param pool address\n /// @return the last interset rate\n function getPoolLastInterestRate(address pool)\n external\n view\n returns (uint256);\n \n function migrateLoanParamsList(\n address owner,\n uint256 start,\n uint256 count)\n external;\n\n ////// Loan Openings //////\n\n /// @dev This is THE function that borrows or trades on the protocol\n /// @param collateralTokenAddress collateral address\n /// @param loanId id of existing loan, if 0, start a new loan\n /// @param isTorqueLoan boolean whether it is toreque or non torque loan\n /// @param initialMargin in WEI_PERCENT_PRECISION\n /// @param sentAddresses array of size 4:\n /// lender: must match loan if loanId provided\n /// borrower: must match loan if loanId provided\n /// receiver: receiver of funds (address(0) assumes borrower address)\n /// manager: delegated manager of loan unless address(0)\n /// @param sentValues array of size 5:\n /// newRate: new loan interest rate\n /// newPrincipal: new loan size (borrowAmount + any borrowed interest)\n /// torqueInterest: new amount of interest to escrow for Torque loan (determines initial loan length)\n /// loanTokenReceived: total loanToken deposit (amount not sent to borrower in the case of Torque loans)\n /// collateralTokenReceived: total collateralToken deposit\n /// @param loanDataBytes required when sending ether\n /// @return principal of the loan and collateral amount\n function borrowOrTradeFromPool(\n address collateralTokenAddress,\n bytes32 loanId,\n bool isTorqueLoan,\n uint256 initialMargin,\n address[4] calldata sentAddresses,\n uint256[5] calldata sentValues,\n bytes calldata loanDataBytes\n ) external payable returns (LoanOpenData memory);\n\n function swapLoanCollateral(\n bytes32 loanId,\n address newCollateralToken,\n bytes calldata loanDataBytes\n ) external;\n\n /// @dev sets/disables/enables the delegated manager for the loan\n /// @param loanId id of the loan\n /// @param delegated delegated manager address\n /// @param toggle boolean set enabled or disabled\n function setDelegatedManager(\n bytes32 loanId,\n address delegated,\n bool toggle\n ) external;\n\n /// @dev calculates required collateral for simulated position\n /// @param loanToken address of loan token\n /// @param collateralToken address of collateral token\n /// @param newPrincipal principal amount of the loan\n /// @param marginAmount margin amount of the loan\n /// @param isTorqueLoan boolean torque or non torque loan\n /// @return collateralAmountRequired amount required\n function getRequiredCollateral(\n address loanToken,\n address collateralToken,\n uint256 newPrincipal,\n uint256 marginAmount,\n bool isTorqueLoan\n ) external view returns (uint256 collateralAmountRequired);\n \n function getDefaultLoanParams(\n address loanToken,\n address collateralToken,\n bool isTorqueLoan)\n external\n view\n returns(LoanParams memory loanParamsLocal, bool isDefault);\n\n function generateLoanParamId(\n address loanToken,\n address collateralToken,\n bool isTorqueLoan\n ) external pure returns (bytes32);\n\n\n ////// Loan Closings //////\n\n /// @dev liquidates unhealty loans\n /// @param loanId id of the loan\n /// @param receiver address receiving liquidated loan collateral\n /// @param closeAmount amount to close denominated in loanToken\n /// @return loanCloseAmount amount of the collateral token of the loan\n /// @return seizedAmount sezied amount in the collateral token\n /// @return seizedToken loan token address\n function liquidate(\n bytes32 loanId,\n address receiver,\n uint256 closeAmount\n )\n external\n payable\n returns (\n uint256 loanCloseAmount,\n uint256 seizedAmount,\n address seizedToken\n );\n\n /// @dev close position with loan token deposit\n /// @param loanId id of the loan\n /// @param receiver collateral token reciever address\n /// @param depositAmount amount of loan token to deposit\n /// @param loanDataBytes additional functionality e.g permits\n /// @return loanCloseAmount loan close amount\n /// @return withdrawAmount loan token withdraw amount\n /// @return withdrawToken loan token address\n function closeWithDeposit(\n bytes32 loanId,\n address receiver,\n uint256 depositAmount, // denominated in loanToken\n bytes calldata loanDataBytes\n )\n external\n payable\n returns (\n uint256 loanCloseAmount,\n uint256 withdrawAmount,\n address withdrawToken\n );\n\n /// @dev close position with swap\n /// @param loanId id of the loan\n /// @param receiver collateral token reciever address\n /// @param swapAmount amount of loan token to swap\n /// @param returnTokenIsCollateral boolean whether to return tokens is collateral\n /// @param loanDataBytes custom payload for specifying swap implementation and data to pass\n /// @return loanCloseAmount loan close amount\n /// @return withdrawAmount loan token withdraw amount\n /// @return withdrawToken loan token address\n function closeWithSwap(\n bytes32 loanId,\n address receiver,\n uint256 swapAmount, // denominated in collateralToken\n bool returnTokenIsCollateral, // true: withdraws collateralToken, false: withdraws loanToken\n bytes calldata loanDataBytes\n )\n external\n returns (\n uint256 loanCloseAmount,\n uint256 withdrawAmount,\n address withdrawToken\n );\n\n ////// Loan Closings With Gas Token //////\n\n ////// Loan Maintenance //////\n\n /// @dev deposit collateral to existing loan\n /// @param loanId existing loan id\n /// @param depositAmount amount to deposit which must match msg.value if ether is sent\n function depositCollateral(bytes32 loanId, uint256 depositAmount)\n external\n payable;\n\n /// @dev withdraw collateral from existing loan\n /// @param loanId existing loan id\n /// @param receiver address of withdrawn tokens\n /// @param withdrawAmount amount to withdraw\n /// @return actualWithdrawAmount actual amount withdrawn\n function withdrawCollateral(\n bytes32 loanId,\n address receiver,\n uint256 withdrawAmount\n ) external returns (uint256 actualWithdrawAmount);\n\n /// @dev settles accrued interest for all active loans from a loan pool\n /// @param loanId existing loan id\n function settleInterest(bytes32 loanId) external;\n\n function setDepositAmount(\n bytes32 loanId,\n uint256 depositValueAsLoanToken,\n uint256 depositValueAsCollateralToken\n ) external;\n\n function transferLoan(bytes32 loanId, address newOwner) external;\n\n // Decommissioned function, but leave interface to allow remaining claims\n function claimRewards(address receiver)\n external\n returns (uint256 claimAmount);\n\n // Decommissioned function, but leave interface to allow remaining claims\n function rewardsBalanceOf(address user)\n external\n view\n returns (uint256 rewardsBalance);\n\n function getInterestModelValues(\n address pool,\n bytes32 loanId)\n external\n view\n returns (\n uint256 _poolLastUpdateTime,\n uint256 _poolPrincipalTotal,\n uint256 _poolInterestTotal,\n uint256 _poolRatePerTokenStored,\n uint256 _poolLastInterestRate,\n uint256 _loanPrincipalTotal,\n uint256 _loanInterestTotal,\n uint256 _loanRatePerTokenPaid\n );\n \n function getTWAI(\n address pool)\n external\n view returns (\n uint256 benchmarkRate\n );\n\n /// @dev gets list of loans of particular user address\n /// @param user address of the loans\n /// @param start of the index\n /// @param count number of loans to return\n /// @param loanType type of the loan: All(0), Margin(1), NonMargin(2)\n /// @param isLender whether to list lender loans or borrower loans\n /// @param unsafeOnly booleat if true return only unsafe loans that are open for liquidation\n /// @return loansData LoanReturnData array of loans\n function getUserLoans(\n address user,\n uint256 start,\n uint256 count,\n LoanType loanType,\n bool isLender,\n bool unsafeOnly\n ) external view returns (LoanReturnData[] memory loansData);\n\n function getUserLoansCount(address user, bool isLender)\n external\n view\n returns (uint256);\n\n /// @dev gets existing loan\n /// @param loanId id of existing loan\n /// @return loanData array of loans\n function getLoan(bytes32 loanId)\n external\n view\n returns (LoanReturnData memory loanData);\n\n /// @dev gets loan principal including interest\n /// @param loanId id of existing loan\n /// @return principal\n function getLoanPrincipal(bytes32 loanId)\n external\n view\n returns (uint256 principal);\n\n /// @dev gets loan outstanding interest\n /// @param loanId id of existing loan\n /// @return interest\n function getLoanInterestOutstanding(bytes32 loanId)\n external\n view\n returns (uint256 interest);\n\n\n /// @dev get current active loans in the system\n /// @param start of the index\n /// @param count number of loans to return\n /// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation)\n function getActiveLoans(\n uint256 start,\n uint256 count,\n bool unsafeOnly\n ) external view returns (LoanReturnData[] memory loansData);\n\n /// @dev get current active loans in the system\n /// @param start of the index\n /// @param count number of loans to return\n /// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation)\n /// @param isLiquidatable boolean if true return liquidatable loans only\n function getActiveLoansAdvanced(\n uint256 start,\n uint256 count,\n bool unsafeOnly,\n bool isLiquidatable\n ) external view returns (LoanReturnData[] memory loansData);\n\n function getActiveLoansCount() external view returns (uint256);\n\n ////// Swap External //////\n\n /// @dev swap thru external integration\n /// @param sourceToken source token address\n /// @param destToken destintaion token address\n /// @param receiver address to receive tokens\n /// @param returnToSender TODO\n /// @param sourceTokenAmount source token amount\n /// @param requiredDestTokenAmount destination token amount\n /// @param swapData TODO\n /// @return destTokenAmountReceived destination token received\n /// @return sourceTokenAmountUsed source token amount used\n function swapExternal(\n address sourceToken,\n address destToken,\n address receiver,\n address returnToSender,\n uint256 sourceTokenAmount,\n uint256 requiredDestTokenAmount,\n bytes calldata swapData\n )\n external\n payable\n returns (\n uint256 destTokenAmountReceived,\n uint256 sourceTokenAmountUsed\n );\n\n /// @dev calculate simulated return of swap\n /// @param sourceToken source token address\n /// @param destToken destination token address\n /// @param sourceTokenAmount source token amount\n /// @return amoun denominated in destination token\n // TODO remove as soon as deployed on all chains\n function getSwapExpectedReturn(\n address sourceToken,\n address destToken,\n uint256 sourceTokenAmount,\n bytes calldata swapData\n ) external view returns (uint256);\n\n /// @dev calculate simulated return of swap\n /// @param trader the wallet that will be used to execute the trade\n /// @param sourceToken source token address\n /// @param destToken destination token address\n /// @param sourceTokenAmount specifies source token amount\n /// @param payload loanDataBytes used\n /// @return amount amount received\n function getSwapExpectedReturn(\n address trader,\n address sourceToken,\n address destToken,\n uint256 sourceTokenAmount,\n bytes calldata payload)\n external\n returns (uint256);\n\n /// @dev calculate simulated return of swap\n /// @param trader the wallet that will be used to execute the trade\n /// @param sourceToken source token address\n /// @param destToken destination token address\n /// @param tokenAmount specifies either token amount in or specific amount out\n /// @param payload loanDataBytes used\n /// @param isAmountIn if marked as true it is returning an amount received and if false it returns an amount in \n /// @return amount amount received or amount in needed based on isAmountIn selection\n function getSwapExpectedReturn(\n address trader,\n address sourceToken,\n address destToken,\n uint256 tokenAmount,\n bytes calldata payload,\n bool isAmountIn)\n external\n returns (uint256);\n\n function owner() external view returns (address);\n\n function transferOwnership(address newOwner) external;\n\n\n /// Guardian Interface\n\n function _isPaused(bytes4 sig) external view returns (bool isPaused);\n\n function toggleFunctionPause(bytes4 sig) external;\n\n function toggleFunctionUnPause(bytes4 sig) external;\n\n function pause(bytes4 [] calldata sig) external;\n\n function unpause(bytes4 [] calldata sig) external;\n\n function changeGuardian(address newGuardian) external;\n\n function getGuardian() external view returns (address guardian);\n\n /// Loan Cleanup Interface\n\n function cleanupLoans(\n address loanToken,\n bytes32[] calldata loanIds)\n external\n payable\n returns (uint256 totalPrincipalIn);\n\n struct LoanParams {\n bytes32 id;\n bool active;\n address owner;\n address loanToken;\n address collateralToken;\n uint256 minInitialMargin;\n uint256 maintenanceMargin;\n uint256 maxLoanTerm;\n }\n\n struct LoanOpenData {\n bytes32 loanId;\n uint256 principal;\n uint256 collateral;\n }\n\n enum LoanType {\n All,\n Margin,\n NonMargin\n }\n\n struct LoanReturnData {\n bytes32 loanId;\n uint96 endTimestamp;\n address loanToken;\n address collateralToken;\n uint256 principal;\n uint256 collateral;\n uint256 interestOwedPerDay;\n uint256 interestDepositRemaining;\n uint256 startRate;\n uint256 startMargin;\n uint256 maintenanceMargin;\n uint256 currentMargin;\n uint256 maxLoanTerm;\n uint256 maxLiquidatable;\n uint256 maxSeizable;\n uint256 depositValueAsLoanToken;\n uint256 depositValueAsCollateralToken;\n }\n\n enum FeeClaimType {\n All,\n Lending,\n Trading,\n Borrowing\n }\n\n struct Loan {\n bytes32 id; // id of the loan\n bytes32 loanParamsId; // the linked loan params id\n bytes32 pendingTradesId; // the linked pending trades id\n uint256 principal; // total borrowed amount outstanding\n uint256 collateral; // total collateral escrowed for the loan\n uint256 startTimestamp; // loan start time\n uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time\n uint256 startMargin; // initial margin when the loan opened\n uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken\n address borrower; // borrower of this loan\n address lender; // lender of this loan\n bool active; // if false, the loan has been fully closed\n }\n\n struct LenderInterest {\n uint256 principalTotal; // total borrowed amount outstanding of asset\n uint256 owedPerDay; // interest owed per day for all loans of asset\n uint256 owedTotal; // total interest owed for all loans of asset (assuming they go to full term)\n uint256 paidTotal; // total interest paid so far for asset\n uint256 updatedTimestamp; // last update\n }\n\n struct LoanInterest {\n uint256 owedPerDay; // interest owed per day for loan\n uint256 depositTotal; // total escrowed interest for loan\n uint256 updatedTimestamp; // last update\n }\n\t\n\t////// Flash Borrow Fees //////\n function payFlashBorrowFees(\n address user,\n uint256 borrowAmount,\n uint256 flashBorrowFeePercent)\n external;\n}\n" }, "IPriceFeeds.sol": { "content": "/**\n * Copyright 2017-2022, OokiDao. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0.\n */\n\npragma solidity >=0.5.0 <0.9.0;\n\n\ninterface IPriceFeeds {\n\n function pricesFeeds(address token)\n external\n view\n returns(address pricefeed);\n\n function queryRate(\n address sourceToken,\n address destToken)\n external\n view\n returns (uint256 rate, uint256 precision);\n\n function queryPrecision(\n address sourceToken,\n address destToken)\n external\n view\n returns (uint256 precision);\n\n function queryReturn(\n address sourceToken,\n address destToken,\n uint256 sourceAmount)\n external\n view\n returns (uint256 destAmount);\n\n function checkPriceDisagreement(\n address sourceToken,\n address destToken,\n uint256 sourceAmount,\n uint256 destAmount,\n uint256 maxSlippage)\n external\n view\n returns (uint256 sourceToDestSwapRate);\n\n function amountInEth(\n address Token,\n uint256 amount)\n external\n view\n returns (uint256 ethAmount);\n\n function getMaxDrawdown(\n address loanToken,\n address collateralToken,\n uint256 loanAmount,\n uint256 collateralAmount,\n uint256 maintenanceMargin)\n external\n view\n returns (uint256);\n\n function getCurrentMarginAndCollateralSize(\n address loanToken,\n address collateralToken,\n uint256 loanAmount,\n uint256 collateralAmount)\n external\n view\n returns (uint256 currentMargin, uint256 collateralInEthAmount);\n\n function getCurrentMargin(\n address loanToken,\n address collateralToken,\n uint256 loanAmount,\n uint256 collateralAmount)\n external\n view\n returns (uint256 currentMargin, uint256 collateralToLoanRate);\n\n function shouldLiquidate(\n address loanToken,\n address collateralToken,\n uint256 loanAmount,\n uint256 collateralAmount,\n uint256 maintenanceMargin)\n external\n view\n returns (bool);\n}\n" }, "Flags.sol": { "content": "pragma solidity >=0.5.17 <0.9.0;\n\ncontract Flags {\n uint128 public constant HOLD_OOKI_FLAG = 1; // base-2: 1\n uint128 public constant DEX_SELECTOR_FLAG = 2; // base-2: 10\n uint128 public constant DELEGATE_FLAG = 4; // base-2: 100\n uint128 public constant PAY_WITH_OOKI_FLAG = 8; // base-2: 1000\n uint128 public constant WITH_PERMIT = 16; // base-2: 10000\n uint128 public constant TRACK_VOLUME_FLAG = 32; // base-2: 100000\n}\n" }, "draft-IERC20Permit.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity >=0.5.0 <0.9.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n" }, "IERC20Detailed.sol": { "content": "/**\n * Copyright 2017-2022, OokiDao. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0.\n */\n\n// SPDX-License-Identifier: Apache-2.0\n\npragma solidity >=0.5.0 <0.8.0;\n\n\n// optional functions from IERC20 not inheriting since old solidity version\ninterface IERC20Detailed {\n function name() external view returns (string memory);\n function symbol() external view returns (string memory);\n function decimals() external view returns (uint8);\n}\n" }, "SafeERC20.sol": { "content": "pragma solidity ^0.5.0;\n\nimport \"IERC20.sol\";\nimport \"SafeMath.sol\";\nimport \"Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using SafeMath for uint256;\n using Address for address;\n\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n function safeApprove(IERC20 token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n // solhint-disable-next-line max-line-length\n require((value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).add(value);\n callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).sub(value, \"SafeERC20: decreased allowance below zero\");\n callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves.\n\n // A Solidity high level call has three parts:\n // 1. The target address is checked to verify it contains contract code\n // 2. The call itself is made, and success asserted\n // 3. The return value is decoded, which in turn checks the size of the returned data.\n // solhint-disable-next-line max-line-length\n require(address(token).isContract(), \"SafeERC20: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = address(token).call(data);\n require(success, \"SafeERC20: low-level call failed\");\n\n if (returndata.length > 0) { // Return data is optional\n // solhint-disable-next-line max-line-length\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" } }, "settings": { "evmVersion": "istanbul", "optimizer": { "enabled": true, "runs": 200 }, "libraries": { "LoanTokenLogicWeth.sol": {} }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } } } }