From 440c0fa555b03f14c591d8b634e3f31ea4add1bd Mon Sep 17 00:00:00 2001 From: Mubaris NK Date: Wed, 13 Jan 2021 20:41:56 +0530 Subject: [PATCH 1/4] Remove Maker --- contracts/connectors/refinance.sol | 419 +---------------------------- 1 file changed, 1 insertion(+), 418 deletions(-) diff --git a/contracts/connectors/refinance.sol b/contracts/connectors/refinance.sol index f347a59..346b112 100644 --- a/contracts/connectors/refinance.sol +++ b/contracts/connectors/refinance.sol @@ -270,59 +270,6 @@ interface AaveV2DataProviderInterface { } // End Aave v2 Helpers -// MakerDAO Helpers -interface ManagerLike { - function cdpCan(address, uint, address) external view returns (uint); - function ilks(uint) external view returns (bytes32); - function last(address) external view returns (uint); - function count(address) external view returns (uint); - function owns(uint) external view returns (address); - function urns(uint) external view returns (address); - function vat() external view returns (address); - function open(bytes32, address) external returns (uint); - function give(uint, address) external; - function frob(uint, int, int) external; - function flux(uint, address, uint) external; - function move(uint, address, uint) external; -} - -interface VatLike { - function can(address, address) external view returns (uint); - function ilks(bytes32) external view returns (uint, uint, uint, uint, uint); - function dai(address) external view returns (uint); - function urns(bytes32, address) external view returns (uint, uint); - function frob( - bytes32, - address, - address, - address, - int, - int - ) external; - function hope(address) external; - function move(address, address, uint) external; - function gem(bytes32, address) external view returns (uint); -} - -interface TokenJoinInterface { - function dec() external returns (uint); - function gem() external returns (TokenInterface); - function join(address, uint) external payable; - function exit(address, uint) external; -} - -interface DaiJoinInterface { - function vat() external returns (VatLike); - function dai() external returns (TokenInterface); - function join(address, uint) external payable; - function exit(address, uint) external; -} - -interface JugLike { - function drip(bytes32) external returns (uint); -} -// End MakerDAO Helpers - contract DSMath { uint constant WAD = 10 ** 18; @@ -343,28 +290,6 @@ contract DSMath { function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } - - function wdiv(uint x, uint y) internal pure returns (uint z) { - z = add(mul(x, WAD), y / 2) / y; - } - - function toRad(uint wad) internal pure returns (uint rad) { - rad = mul(wad, 10 ** 27); - } - - function toInt(uint x) internal pure returns (int y) { - y = int(x); - require(y >= 0, "int-overflow"); - } - - function convertTo18(uint _dec, uint256 _amt) internal pure returns (uint256 amt) { - amt = mul(_amt, 10 ** (18 - _dec)); - } - - function convert18ToDec(uint _dec, uint256 _amt) internal pure returns (uint256 amt) { - amt = (_amt / 10 ** (18 - _dec)); - } - } contract Helpers is DSMath { @@ -415,34 +340,6 @@ contract Helpers is DSMath { return 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; } - /** - * @dev Return Maker MCD DAI_Join Address. - */ - function getMcdDaiJoin() internal pure returns (address) { - return 0x9759A6Ac90977b93B58547b4A71c78317f391A28; - } - - /** - * @dev Return Maker MCD Manager Address. - */ - function getMcdManager() internal pure returns (address) { - return 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; - } - - /** - * @dev Return Maker MCD DAI Address. - */ - function getMcdDai() internal pure returns (address) { - return 0x6B175474E89094C44Da98b954EedeAC495271d0F; - } - - /** - * @dev Return Maker MCD Jug Address. - */ - function getMcdJug() internal pure returns (address) { - return 0x19c0976f590D67707E62397C87829d896Dc0f1F1; - } - /** * @dev get Aave Provider */ @@ -507,90 +404,6 @@ contract Helpers is DSMath { (, , , , , , , , isCol) = aaveData.getUserReserveData(token, address(this)); } - /** - * @dev Get Vault's ilk. - */ - function getVaultData(ManagerLike managerContract, uint vault) internal view returns (bytes32 ilk, address urn) { - ilk = managerContract.ilks(vault); - urn = managerContract.urns(vault); - } - - /** - * @dev Get Vault Debt Amount. - */ - function _getVaultDebt( - address vat, - bytes32 ilk, - address urn - ) internal view returns (uint wad) { - (, uint rate,,,) = VatLike(vat).ilks(ilk); - (, uint art) = VatLike(vat).urns(ilk, urn); - uint dai = VatLike(vat).dai(urn); - - uint rad = sub(mul(art, rate), dai); - wad = rad / RAY; - - wad = mul(wad, RAY) < rad ? wad + 1 : wad; - } - - /** - * @dev Get Payback Amount. - */ - function _getWipeAmt( - address vat, - uint amt, - address urn, - bytes32 ilk - ) internal view returns (int dart) - { - (, uint rate,,,) = VatLike(vat).ilks(ilk); - (, uint art) = VatLike(vat).urns(ilk, urn); - dart = toInt(amt / rate); - dart = uint(dart) <= art ? - dart : - toInt(art); - } - - /** - * @dev Convert String to bytes32. - */ - function stringToBytes32(string memory str) internal pure returns (bytes32 result) { - require(bytes(str).length != 0, "string-empty"); - // solium-disable-next-line security/no-inline-assembly - assembly { - result := mload(add(str, 32)) - } - } - - /** - * @dev Get vault ID. If `vault` is 0, get last opened vault. - */ - function getVault(ManagerLike managerContract, uint vault) internal view returns (uint _vault) { - if (vault == 0) { - require(managerContract.count(address(this)) > 0, "no-vault-opened"); - _vault = managerContract.last(address(this)); - } else { - _vault = vault; - } - } - - /** - * @dev Get Borrow Amount [MakerDAO] - */ - function _getBorrowAmt( - address vat, - address urn, - bytes32 ilk, - uint amt - ) internal returns (int dart) - { - address jug = getMcdJug(); - uint rate = JugLike(jug).drip(ilk); - uint dai = VatLike(vat).dai(urn); - if (dai < mul(amt, RAY)) { - dart = toInt(sub(mul(amt, RAY), dai) / rate); - dart = mul(uint(dart), rate) < mul(amt, RAY) ? dart + 1 : dart; - } - } - function convertEthToWeth(bool isEth, TokenInterface token, uint amount) internal { if(isEth) token.deposit.value(amount)(); } @@ -1166,153 +979,7 @@ contract AaveV2Helpers is AaveV1Helpers { } } -contract MakerHelpers is AaveV2Helpers { - - struct MakerData { - uint _vault; - address colAddr; - address daiJoin; - TokenJoinInterface tokenJoinContract; - VatLike vatContract; - TokenInterface tokenContract; - DaiJoinInterface daiJoinContract; - } - - function _makerOpen(string memory colType) internal { - bytes32 ilk = stringToBytes32(colType); - require(InstaMapping(getMappingAddr()).gemJoinMapping(ilk) != address(0), "wrong-col-type"); - ManagerLike(getMcdManager()).open(ilk, address(this)); - } - - function _makerDepositAndBorrow( - uint vault, - uint collateralAmt, - uint debtAmt, - uint collateralFee, - uint debtFee - ) internal { - (uint collateralFeeAmt, uint _collateralAmt) = calculateFee(collateralAmt, collateralFee, false); - - (uint debtFeeAmt, uint _debtAmt) = calculateFee(debtAmt, debtFee, true); - - MakerData memory makerData; - - ManagerLike managerContract = ManagerLike(getMcdManager()); - - makerData._vault = getVault(managerContract, vault); - (bytes32 ilk, address urn) = getVaultData(managerContract, makerData._vault); - - makerData.colAddr = InstaMapping(getMappingAddr()).gemJoinMapping(ilk); - makerData.tokenJoinContract = TokenJoinInterface(makerData.colAddr); - makerData.tokenContract = makerData.tokenJoinContract.gem(); - makerData.daiJoin = getMcdDaiJoin(); - makerData.vatContract = VatLike(managerContract.vat()); - - if (address(makerData.tokenContract) == getWethAddr()) { - makerData.tokenContract.deposit.value(collateralAmt)(); - } - - transferFees(address(makerData.tokenContract), collateralFeeAmt); - - makerData.tokenContract.approve(address(makerData.colAddr), _collateralAmt); - makerData.tokenJoinContract.join(urn, _collateralAmt); - - int intAmt = toInt(convertTo18(makerData.tokenJoinContract.dec(), _collateralAmt)); - - int dart = _getBorrowAmt(address(makerData.vatContract), urn, ilk, _debtAmt); - - managerContract.frob( - makerData._vault, - intAmt, - dart - ); - - managerContract.move( - makerData._vault, - address(this), - toRad(_debtAmt) - ); - - if (makerData.vatContract.can(address(this), address(makerData.daiJoin)) == 0) { - makerData.vatContract.hope(makerData.daiJoin); - } - - DaiJoinInterface(makerData.daiJoin).exit(address(this), _debtAmt); - - transferFees(getMcdDai(), debtFeeAmt); - } - - function _makerPaybackAndWithdraw( - uint vault, - uint withdrawAmt, - uint paybackAmt - ) internal returns (uint, uint) { - ManagerLike managerContract = ManagerLike(getMcdManager()); - MakerData memory makerData; - - makerData._vault = getVault(managerContract, vault); - (bytes32 ilk, address urn) = getVaultData(managerContract, makerData._vault); - - makerData.colAddr = InstaMapping(getMappingAddr()).gemJoinMapping(ilk); - makerData.tokenJoinContract = TokenJoinInterface(makerData.colAddr); - makerData.tokenContract = makerData.tokenJoinContract.gem(); - makerData.daiJoin = getMcdDaiJoin(); - makerData.vatContract = VatLike(managerContract.vat()); - - uint _withdrawAmt18; - if (withdrawAmt == uint(-1)) { - (_withdrawAmt18,) = makerData.vatContract.urns(ilk, urn); - withdrawAmt = convert18ToDec(makerData.tokenJoinContract.dec(), _withdrawAmt18); - } else { - _withdrawAmt18 = convertTo18(makerData.tokenJoinContract.dec(), withdrawAmt); - } - - int _paybackDart; - { - (, uint art) = makerData.vatContract.urns(ilk, urn); - uint _maxDebt = _getVaultDebt(address(makerData.vatContract), ilk, urn); - _paybackDart = paybackAmt == uint(-1) ? - -int(art) : - _getWipeAmt( - address(makerData.vatContract), - makerData.vatContract.dai(urn), - urn, - ilk - ); - - paybackAmt = paybackAmt == uint(-1) ? _maxDebt : paybackAmt; - - require(_maxDebt >= paybackAmt, "paying-excess-debt"); - } - - makerData.daiJoinContract = DaiJoinInterface(makerData.daiJoin); - makerData.daiJoinContract.dai().approve(makerData.daiJoin, paybackAmt); - makerData.daiJoinContract.join(urn, paybackAmt); - - managerContract.frob( - makerData._vault, - -toInt(_withdrawAmt18), - _paybackDart - ); - - managerContract.flux( - makerData._vault, - address(this), - _withdrawAmt18 - ); - - if (address(makerData.tokenContract) == getWethAddr()) { - makerData.tokenJoinContract.exit(address(this), _withdrawAmt18); - makerData.tokenContract.withdraw(_withdrawAmt18); - } else { - makerData.tokenJoinContract.exit(address(this), _withdrawAmt18); - } - - return (withdrawAmt, paybackAmt); - } -} - -contract RefinanceResolver is MakerHelpers { +contract RefinanceResolver is AaveV2Helpers { struct RefinanceData { Protocol source; @@ -1326,22 +993,6 @@ contract RefinanceResolver is MakerHelpers { uint[] paybackRateModes; } - struct RefinanceMakerData { - uint fromVaultId; - uint toVaultId; - Protocol source; - Protocol target; - uint collateralFee; - uint debtFee; - bool isFrom; - string colType; - address token; - uint debt; - uint collateral; - uint borrowRateMode; - uint paybackRateMode; - } - struct CommonData { AaveV2Interface aaveV2; AaveV1Interface aaveV1; @@ -1475,74 +1126,6 @@ contract RefinanceResolver is MakerHelpers { revert("invalid-options"); } } - - function refinanceMaker(RefinanceMakerData calldata data) external payable { - - AaveV2Interface aaveV2 = AaveV2Interface(getAaveV2Provider().getLendingPool()); - AaveV1Interface aaveV1 = AaveV1Interface(getAaveProvider().getLendingPool()); - AaveV1CoreInterface aaveCore = AaveV1CoreInterface(getAaveProvider().getLendingPoolCore()); - AaveV2DataProviderInterface aaveData = getAaveV2DataProvider(); - - TokenInterface dai = TokenInterface(getMcdDai()); - TokenInterface token = TokenInterface(data.token == getEthAddr() ? getWethAddr() : data.token); - - uint depositAmt; - uint borrowAmt; - - if (data.isFrom) { - (depositAmt, borrowAmt) = _makerPaybackAndWithdraw( - data.fromVaultId, - data.collateral, - data.debt - ); - - if (data.target == Protocol.Aave) { - _aaveV1DepositOne(aaveV1, aaveCore, data.collateralFee, token, depositAmt); - _aaveV1BorrowOne(aaveV1, data.debtFee, Protocol.AaveV2, dai, CTokenInterface(address(0)), borrowAmt, data.borrowRateMode, 2); - } else if (data.target == Protocol.AaveV2) { - _aaveV2DepositOne(aaveV2, aaveData, data.collateralFee, token, depositAmt); - _aaveV2BorrowOne(aaveV2, data.debtFee, Protocol.AaveV2, dai, CTokenInterface(address(0)), borrowAmt, data.borrowRateMode); - } else if (data.target == Protocol.Compound) { - address[] memory tokens = new address[](2); - tokens[0] = address(dai); - tokens[1] = data.token; - - CTokenInterface[] memory _ctokens = getCtokenInterfaces(2, tokens); - - _compEnterMarkets(2, _ctokens); - - _compDepositOne(data.collateralFee, _ctokens[1], token, depositAmt); - _compBorrowOne(data.debtFee, _ctokens[0], dai, borrowAmt, Protocol.Aave, 2); - } else { - revert("invalid-option"); - } - } else { - if (data.toVaultId == 0) { - _makerOpen(data.colType); - } - - if (data.source == Protocol.Aave) { - borrowAmt = _aaveV1PaybackOne(aaveV1, aaveCore, dai, data.debt); - depositAmt = _aaveV1WithdrawOne(aaveV1, aaveCore, token, data.collateral); - } else if (data.source == Protocol.AaveV2) { - borrowAmt = _aaveV2PaybackOne(aaveV2, aaveData, dai, data.debt, data.paybackRateMode); - depositAmt = _aaveV2WithdrawOne(aaveV2, aaveData, token, data.collateral); - } else if (data.source == Protocol.Compound) { - address _cDai = InstaMapping(getMappingAddr()).cTokenMapping(address(dai)); - address _cToken = InstaMapping(getMappingAddr()).cTokenMapping(data.token); - - CTokenInterface cDai = CTokenInterface(_cDai); - CTokenInterface cToken = CTokenInterface(_cToken); - - borrowAmt = _compPaybackOne(cDai, dai, data.debt); - depositAmt = _compWithdrawOne(cToken, token, data.collateral); - } else { - revert("invalid-option"); - } - - _makerDepositAndBorrow(data.toVaultId, depositAmt, borrowAmt, data.collateralFee, data.debtFee); - } - } } contract ConnectRefinance is RefinanceResolver { From 2c5828ef9a46e817990e1f6c3bf3c82f5c941ed4 Mon Sep 17 00:00:00 2001 From: Mubaris NK Date: Tue, 19 Jan 2021 00:00:25 +0530 Subject: [PATCH 2/4] Refactor the refinance connector --- contracts/connectors/refinance.sol | 448 +++++++++++------------------ 1 file changed, 164 insertions(+), 284 deletions(-) diff --git a/contracts/connectors/refinance.sol b/contracts/connectors/refinance.sol index 346b112..e0d9e61 100644 --- a/contracts/connectors/refinance.sol +++ b/contracts/connectors/refinance.sol @@ -1,4 +1,4 @@ -pragma solidity ^0.6.0; +pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** @@ -296,6 +296,30 @@ contract Helpers is DSMath { using SafeERC20 for IERC20; + struct RefinanceData { + Protocol source; + Protocol target; + uint collateralFee; + uint debtFee; + address[] tokens; + uint[] borrowAmts; + uint[] withdrawAmts; + uint[] borrowRateModes; + uint[] paybackRateModes; + } + + struct CommonData { + AaveV2Interface aaveV2; + AaveV1Interface aaveV1; + AaveV1CoreInterface aaveCore; + AaveV2DataProviderInterface aaveData; + uint length; + uint[] depositAmts; + uint[] paybackAmts; + TokenInterface[] tokens; + CTokenInterface[] ctokens; + } + enum Protocol { Aave, AaveV2, @@ -405,7 +429,7 @@ contract Helpers is DSMath { } function convertEthToWeth(bool isEth, TokenInterface token, uint amount) internal { - if(isEth) token.deposit.value(amount)(); + if(isEth) token.deposit{value: amount}(); } function convertWethToEth(bool isEth, TokenInterface token, uint amount) internal { @@ -468,16 +492,6 @@ contract Helpers is DSMath { contract CompoundHelpers is Helpers { - struct CompoundBorrowData { - uint length; - uint fee; - Protocol target; - CTokenInterface[] ctokens; - TokenInterface[] tokens; - uint[] amts; - uint[] rateModes; - } - function _compEnterMarkets(uint length, CTokenInterface[] memory ctokens) internal { ComptrollerInterface troller = ComptrollerInterface(getComptrollerAddress()); address[] memory _cTokens = new address[](length); @@ -512,17 +526,18 @@ contract CompoundHelpers is Helpers { } function _compBorrow( - CompoundBorrowData memory data + RefinanceData memory data, + CommonData memory commonData ) internal returns (uint[] memory) { - uint[] memory finalAmts = new uint[](data.length); - for (uint i = 0; i < data.length; i++) { + uint[] memory finalAmts = new uint[](commonData.length); + for (uint i = 0; i < commonData.length; i++) { finalAmts[i] = _compBorrowOne( - data.fee, - data.ctokens[i], - data.tokens[i], - data.amts[i], - data.target, - data.rateModes[i] + data.debtFee, + commonData.ctokens[i], + commonData.tokens[i], + data.borrowAmts[i], + data.source, + data.borrowRateModes[i] ); } return finalAmts; @@ -538,21 +553,18 @@ contract CompoundHelpers is Helpers { token.approve(address(ctoken), _amt); require(ctoken.mint(_amt) == 0, "deposit-failed"); } else { - CETHInterface(address(ctoken)).mint.value(_amt)(); + CETHInterface(address(ctoken)).mint{value: _amt}(); } transferFees(_token, feeAmt); } } function _compDeposit( - uint length, - uint fee, - CTokenInterface[] memory ctokens, - TokenInterface[] memory tokens, - uint[] memory amts + RefinanceData memory data, + CommonData memory commonData ) internal { - for (uint i = 0; i < length; i++) { - _compDepositOne(fee, ctokens[i], tokens[i], amts[i]); + for (uint i = 0; i < commonData.length; i++) { + _compDepositOne(data.collateralFee, commonData.ctokens[i], commonData.tokens[i], commonData.depositAmts[i]); } } @@ -572,14 +584,12 @@ contract CompoundHelpers is Helpers { } function _compWithdraw( - uint length, - CTokenInterface[] memory ctokens, - TokenInterface[] memory tokens, - uint[] memory amts + RefinanceData memory data, + CommonData memory commonData ) internal returns(uint[] memory) { - uint[] memory finalAmts = new uint[](length); - for (uint i = 0; i < length; i++) { - finalAmts[i] = _compWithdrawOne(ctokens[i], tokens[i], amts[i]); + uint[] memory finalAmts = new uint[](commonData.length); + for (uint i = 0; i < commonData.length; i++) { + finalAmts[i] = _compWithdrawOne(commonData.ctokens[i], commonData.tokens[i], data.withdrawAmts[i]); } return finalAmts; } @@ -593,47 +603,23 @@ contract CompoundHelpers is Helpers { token.approve(address(ctoken), amt); require(ctoken.repayBorrow(amt) == 0, "repay-failed."); } else { - CETHInterface(address(ctoken)).repayBorrow.value(amt)(); + CETHInterface(address(ctoken)).repayBorrow{value: amt}(); } } return amt; } function _compPayback( - uint length, - CTokenInterface[] memory ctokens, - TokenInterface[] memory tokens, - uint[] memory amts + CommonData memory commonData ) internal { - for (uint i = 0; i < length; i++) { - _compPaybackOne(ctokens[i], tokens[i], amts[i]); + for (uint i = 0; i < commonData.length; i++) { + _compPaybackOne(commonData.ctokens[i], commonData.tokens[i], commonData.paybackAmts[i]); } } } contract AaveV1Helpers is CompoundHelpers { - struct AaveV1BorrowData { - AaveV1Interface aave; - uint length; - uint fee; - Protocol target; - TokenInterface[] tokens; - CTokenInterface[] ctokens; - uint[] amts; - uint[] borrowRateModes; - uint[] paybackRateModes; - } - - struct AaveV1DepositData { - AaveV1Interface aave; - AaveV1CoreInterface aaveCore; - uint length; - uint fee; - TokenInterface[] tokens; - uint[] amts; - } - function _aaveV1BorrowOne( AaveV1Interface aave, uint fee, @@ -661,17 +647,18 @@ contract AaveV1Helpers is CompoundHelpers { } function _aaveV1Borrow( - AaveV1BorrowData memory data + RefinanceData memory data, + CommonData memory commonData ) internal returns (uint[] memory) { - uint[] memory finalAmts = new uint[](data.length); - for (uint i = 0; i < data.length; i++) { + uint[] memory finalAmts = new uint[](commonData.length); + for (uint i = 0; i < commonData.length; i++) { finalAmts[i] = _aaveV1BorrowOne( - data.aave, - data.fee, - data.target, - data.tokens[i], - data.ctokens[i], - data.amts[i], + commonData.aaveV1, + data.debtFee, + data.source, + commonData.tokens[i], + commonData.ctokens[i], + data.borrowAmts[i], data.borrowRateModes[i], data.paybackRateModes[i] ); @@ -702,7 +689,7 @@ contract AaveV1Helpers is CompoundHelpers { transferFees(_token, feeAmt); - aave.deposit.value(ethAmt)(_token, _amt, getReferralCode()); + aave.deposit{value: ethAmt}(_token, _amt, getReferralCode()); if (!getIsColl(aave, _token)) aave.setUserUseReserveAsCollateral(_token, true); @@ -710,15 +697,16 @@ contract AaveV1Helpers is CompoundHelpers { } function _aaveV1Deposit( - AaveV1DepositData memory data + RefinanceData memory data, + CommonData memory commonData ) internal { - for (uint i = 0; i < data.length; i++) { + for (uint i = 0; i < commonData.length; i++) { _aaveV1DepositOne( - data.aave, - data.aaveCore, - data.fee, - data.tokens[i], - data.amts[i] + commonData.aaveV1, + commonData.aaveCore, + data.collateralFee, + commonData.tokens[i], + commonData.depositAmts[i] ); } } @@ -741,15 +729,17 @@ contract AaveV1Helpers is CompoundHelpers { } function _aaveV1Withdraw( - AaveV1Interface aave, - AaveV1CoreInterface aaveCore, - uint length, - TokenInterface[] memory tokens, - uint[] memory amts + RefinanceData memory data, + CommonData memory commonData ) internal returns (uint[] memory) { - uint[] memory finalAmts = new uint[](length); - for (uint i = 0; i < length; i++) { - finalAmts[i] = _aaveV1WithdrawOne(aave, aaveCore, tokens[i], amts[i]); + uint[] memory finalAmts = new uint[](commonData.length); + for (uint i = 0; i < commonData.length; i++) { + finalAmts[i] = _aaveV1WithdrawOne( + commonData.aaveV1, + commonData.aaveCore, + commonData.tokens[i], + data.withdrawAmts[i] + ); } return finalAmts; } @@ -778,54 +768,27 @@ contract AaveV1Helpers is CompoundHelpers { token.approve(address(aaveCore), amt); } - aave.repay.value(ethAmt)(_token, amt, payable(address(this))); + aave.repay{value: ethAmt}(_token, amt, payable(address(this))); } return amt; } function _aaveV1Payback( - AaveV1Interface aave, - AaveV1CoreInterface aaveCore, - uint length, - TokenInterface[] memory tokens, - uint[] memory amts + CommonData memory commonData ) internal { - for (uint i = 0; i < length; i++) { - _aaveV1PaybackOne(aave, aaveCore, tokens[i], amts[i]); + for (uint i = 0; i < commonData.length; i++) { + _aaveV1PaybackOne( + commonData.aaveV1, + commonData.aaveCore, + commonData.tokens[i], + commonData.paybackAmts[i] + ); } } } contract AaveV2Helpers is AaveV1Helpers { - struct AaveV2BorrowData { - AaveV2Interface aave; - uint length; - uint fee; - Protocol target; - TokenInterface[] tokens; - CTokenInterface[] ctokens; - uint[] amts; - uint[] rateModes; - } - - struct AaveV2PaybackData { - AaveV2Interface aave; - AaveV2DataProviderInterface aaveData; - uint length; - TokenInterface[] tokens; - uint[] amts; - uint[] rateModes; - } - - struct AaveV2WithdrawData { - AaveV2Interface aave; - AaveV2DataProviderInterface aaveData; - uint length; - TokenInterface[] tokens; - uint[] amts; - } - function _aaveV2BorrowOne( AaveV2Interface aave, uint fee, @@ -855,18 +818,19 @@ contract AaveV2Helpers is AaveV1Helpers { } function _aaveV2Borrow( - AaveV2BorrowData memory data + RefinanceData memory data, + CommonData memory commonData ) internal returns (uint[] memory) { - uint[] memory finalAmts = new uint[](data.length); - for (uint i = 0; i < data.length; i++) { + uint[] memory finalAmts = new uint[](commonData.length); + for (uint i = 0; i < commonData.length; i++) { finalAmts[i] = _aaveV2BorrowOne( - data.aave, - data.fee, - data.target, - data.tokens[i], - data.ctokens[i], - data.amts[i], - data.rateModes[i] + commonData.aaveV2, + data.debtFee, + data.source, + commonData.tokens[i], + commonData.ctokens[i], + data.borrowAmts[i], + data.borrowRateModes[i] ); } return finalAmts; @@ -900,15 +864,17 @@ contract AaveV2Helpers is AaveV1Helpers { } function _aaveV2Deposit( - AaveV2Interface aave, - AaveV2DataProviderInterface aaveData, - uint length, - uint fee, - TokenInterface[] memory tokens, - uint[] memory amts + RefinanceData memory data, + CommonData memory commonData ) internal { - for (uint i = 0; i < length; i++) { - _aaveV2DepositOne(aave, aaveData, fee, tokens[i], amts[i]); + for (uint i = 0; i < commonData.length; i++) { + _aaveV2DepositOne( + commonData.aaveV2, + commonData.aaveData, + data.collateralFee, + commonData.tokens[i], + commonData.depositAmts[i] + ); } } @@ -921,24 +887,25 @@ contract AaveV2Helpers is AaveV1Helpers { if (amt > 0) { bool isEth = address(token) == getWethAddr(); - aave.withdraw(address(token), amt, address(this)); - _amt = amt == uint(-1) ? getWithdrawBalanceV2(aaveData, address(token)) : amt; + aave.withdraw(address(token), amt, address(this)); + convertWethToEth(isEth, token, _amt); } } function _aaveV2Withdraw( - AaveV2WithdrawData memory data + RefinanceData memory data, + CommonData memory commonData ) internal returns (uint[] memory) { - uint[] memory finalAmts = new uint[](data.length); - for (uint i = 0; i < data.length; i++) { + uint[] memory finalAmts = new uint[](commonData.length); + for (uint i = 0; i < commonData.length; i++) { finalAmts[i] = _aaveV2WithdrawOne( - data.aave, - data.aaveData, - data.tokens[i], - data.amts[i] + commonData.aaveV2, + commonData.aaveData, + commonData.tokens[i], + data.withdrawAmts[i] ); } return finalAmts; @@ -965,15 +932,16 @@ contract AaveV2Helpers is AaveV1Helpers { } function _aaveV2Payback( - AaveV2PaybackData memory data + RefinanceData memory data, + CommonData memory commonData ) internal { - for (uint i = 0; i < data.length; i++) { + for (uint i = 0; i < commonData.length; i++) { _aaveV2PaybackOne( - data.aave, - data.aaveData, - data.tokens[i], - data.amts[i], - data.rateModes[i] + commonData.aaveV2, + commonData.aaveData, + commonData.tokens[i], + commonData.paybackAmts[i], + data.paybackRateModes[i] ); } } @@ -981,147 +949,59 @@ contract AaveV2Helpers is AaveV1Helpers { contract RefinanceResolver is AaveV2Helpers { - struct RefinanceData { - Protocol source; - Protocol target; - uint collateralFee; - uint debtFee; - address[] tokens; - uint[] borrowAmts; - uint[] withdrawAmts; - uint[] borrowRateModes; - uint[] paybackRateModes; - } - - struct CommonData { - AaveV2Interface aaveV2; - AaveV1Interface aaveV1; - AaveV1CoreInterface aaveCore; - AaveV2DataProviderInterface aaveData; - uint length; - TokenInterface[] tokens; - CTokenInterface[] _ctokens; - } - function refinance(RefinanceData calldata data) external payable { CommonData memory commonData; require(data.source != data.target, "source-and-target-unequal"); - uint length = data.tokens.length; // TODO: move to common struct + commonData.length = data.tokens.length; - require(data.borrowAmts.length == length, "length-mismatch"); - require(data.withdrawAmts.length == length, "length-mismatch"); - require(data.borrowRateModes.length == length, "length-mismatch"); - require(data.paybackRateModes.length == length, "length-mismatch"); + require(data.borrowAmts.length == commonData.length, "length-mismatch"); + require(data.withdrawAmts.length == commonData.length, "length-mismatch"); + require(data.borrowRateModes.length == commonData.length, "length-mismatch"); + require(data.paybackRateModes.length == commonData.length, "length-mismatch"); - AaveV2Interface aaveV2 = AaveV2Interface(getAaveV2Provider().getLendingPool()); // TODO: move to common struct - AaveV1Interface aaveV1 = AaveV1Interface(getAaveProvider().getLendingPool()); // TODO: move to common struct - AaveV1CoreInterface aaveCore = AaveV1CoreInterface(getAaveProvider().getLendingPoolCore()); // TODO: move to common struct - AaveV2DataProviderInterface aaveData = getAaveV2DataProvider(); // TODO: move to common struct + commonData.aaveV2 = AaveV2Interface(getAaveV2Provider().getLendingPool()); + commonData.aaveV1 = AaveV1Interface(getAaveProvider().getLendingPool()); + commonData.aaveCore = AaveV1CoreInterface(getAaveProvider().getLendingPoolCore()); + commonData.aaveData = getAaveV2DataProvider(); - uint[] memory depositAmts; // TODO: move to common struct - uint[] memory paybackAmts; // TODO: move to common struct - - TokenInterface[] memory tokens = getTokenInterfaces(length, data.tokens); // TODO: move to common struct - CTokenInterface[] memory _ctokens = getCtokenInterfaces(length, data.tokens); // TODO: move to common struct - - AaveV2BorrowData memory _aaveV2BorrowData; - if (data.target == Protocol.AaveV2) { - _aaveV2BorrowData.aave = aaveV2; - _aaveV2BorrowData.length = length; - _aaveV2BorrowData.fee = data.debtFee; - _aaveV2BorrowData.target = data.source; - _aaveV2BorrowData.tokens = tokens; - _aaveV2BorrowData.ctokens = _ctokens; - _aaveV2BorrowData.amts = data.borrowAmts; - _aaveV2BorrowData.rateModes = data.borrowRateModes; - } - - CompoundBorrowData memory _compoundBorrowData; - if (data.target == Protocol.Compound) { - _compoundBorrowData.length = length; - _compoundBorrowData.fee = data.debtFee; - _compoundBorrowData.target = data.source; - _compoundBorrowData.ctokens = _ctokens; - _compoundBorrowData.tokens = tokens; - _compoundBorrowData.amts = data.borrowAmts; - _compoundBorrowData.rateModes = data.borrowRateModes; - } - - AaveV1BorrowData memory _aaveV1BorrowData; - AaveV1DepositData memory _aaveV1DepositData; - - if (data.target == Protocol.Aave) { - _aaveV1BorrowData.aave = aaveV1; - _aaveV1BorrowData.length = length; - _aaveV1BorrowData.fee = data.debtFee; - _aaveV1BorrowData.target = data.source; - _aaveV1BorrowData.tokens = tokens; - _aaveV1BorrowData.ctokens = _ctokens; - _aaveV1BorrowData.amts = data.borrowAmts; - _aaveV1BorrowData.borrowRateModes = data.borrowRateModes; - _aaveV1BorrowData.paybackRateModes = data.paybackRateModes; - - _aaveV1DepositData.aave = aaveV1; - _aaveV1DepositData.aaveCore = aaveCore; - _aaveV1DepositData.length = length; - _aaveV1DepositData.fee = data.collateralFee; - _aaveV1DepositData.tokens = tokens; - _aaveV1DepositData.amts = depositAmts; - } - - AaveV2PaybackData memory _aaveV2PaybackData; - AaveV2WithdrawData memory _aaveV2WithdrawData; - if (data.source == Protocol.AaveV2) { - _aaveV2PaybackData.aave = aaveV2; - _aaveV2PaybackData.aaveData = aaveData; - _aaveV2PaybackData.length = length; - _aaveV2PaybackData.tokens = tokens; - _aaveV2PaybackData.amts = paybackAmts; - _aaveV2PaybackData.rateModes = data.paybackRateModes; - - _aaveV2WithdrawData.aave = aaveV2; - _aaveV2WithdrawData.aaveData = aaveData; - _aaveV2WithdrawData.length = length; - _aaveV2WithdrawData.tokens = tokens; - _aaveV2WithdrawData.amts = data.withdrawAmts; - } + commonData.tokens = getTokenInterfaces(commonData.length, data.tokens); + commonData.ctokens = getCtokenInterfaces(commonData.length, data.tokens); if (data.source == Protocol.Aave && data.target == Protocol.AaveV2) { - paybackAmts = _aaveV2Borrow(_aaveV2BorrowData); // TODO: pass common struct + RefinanceData calldata data and refactor in the common function - _aaveV1Payback(aaveV1, aaveCore, length, tokens, paybackAmts); - depositAmts = _aaveV1Withdraw(aaveV1, aaveCore, length, tokens, data.withdrawAmts); - _aaveV2Deposit(aaveV2, aaveData, length, data.collateralFee, tokens, depositAmts); + commonData.paybackAmts = _aaveV2Borrow(data, commonData); // TODO: pass common struct + RefinanceData calldata data and refactor in the common function + _aaveV1Payback(commonData); + commonData.depositAmts = _aaveV1Withdraw(data, commonData); + _aaveV2Deposit(data, commonData); } else if (data.source == Protocol.Aave && data.target == Protocol.Compound) { - _compEnterMarkets(length, _ctokens); + _compEnterMarkets(commonData.length, commonData.ctokens); - paybackAmts = _compBorrow(_compoundBorrowData); - _aaveV1Payback(aaveV1, aaveCore, length, tokens, paybackAmts); - depositAmts = _aaveV1Withdraw(aaveV1, aaveCore, length, tokens, data.withdrawAmts); - _compDeposit(length, data.collateralFee, _ctokens, tokens, depositAmts); + commonData.paybackAmts = _compBorrow(data, commonData); + _aaveV1Payback(commonData); + commonData.depositAmts = _aaveV1Withdraw(data, commonData); + _compDeposit(data, commonData); } else if (data.source == Protocol.AaveV2 && data.target == Protocol.Aave) { - paybackAmts = _aaveV1Borrow(_aaveV1BorrowData); - _aaveV2Payback(_aaveV2PaybackData); - depositAmts = _aaveV2Withdraw(_aaveV2WithdrawData); - - _aaveV1Deposit(_aaveV1DepositData); + commonData.paybackAmts = _aaveV1Borrow(data, commonData); + _aaveV2Payback(data, commonData); + commonData.depositAmts = _aaveV2Withdraw(data, commonData); + _aaveV1Deposit(data, commonData); } else if (data.source == Protocol.AaveV2 && data.target == Protocol.Compound) { - _compEnterMarkets(length, _ctokens); + _compEnterMarkets(commonData.length, commonData.ctokens); - paybackAmts = _compBorrow(_compoundBorrowData); - _aaveV2Payback(_aaveV2PaybackData); - depositAmts = _aaveV2Withdraw(_aaveV2WithdrawData); - _compDeposit(length, data.collateralFee, _ctokens, tokens, depositAmts); + commonData.paybackAmts = _compBorrow(data, commonData); + _aaveV2Payback(data, commonData); + commonData.depositAmts = _aaveV2Withdraw(data, commonData); + _compDeposit(data, commonData); } else if (data.source == Protocol.Compound && data.target == Protocol.Aave) { - paybackAmts = _aaveV1Borrow(_aaveV1BorrowData); - _compPayback(length, _ctokens, tokens, paybackAmts); - depositAmts = _compWithdraw(length, _ctokens, tokens, data.withdrawAmts); - _aaveV1Deposit(_aaveV1DepositData); + commonData.paybackAmts = _aaveV1Borrow(data, commonData); + _compPayback(commonData); + commonData.depositAmts = _compWithdraw(data, commonData); + _aaveV1Deposit(data, commonData); } else if (data.source == Protocol.Compound && data.target == Protocol.AaveV2) { - paybackAmts = _aaveV2Borrow(_aaveV2BorrowData); - _compPayback(length, _ctokens, tokens, paybackAmts); - depositAmts = _compWithdraw(length, _ctokens, tokens, data.withdrawAmts); - _aaveV2Deposit(aaveV2, aaveData, length, data.collateralFee, tokens, depositAmts); + commonData.paybackAmts = _aaveV2Borrow(data, commonData); + _compPayback(commonData); + commonData.depositAmts = _compWithdraw(data, commonData); + _aaveV2Deposit(data, commonData); } else { revert("invalid-options"); } From 3b08bc26514e71940434e060a8b449a902ecf4ef Mon Sep 17 00:00:00 2001 From: Mubaris NK Date: Tue, 19 Jan 2021 00:09:20 +0530 Subject: [PATCH 3/4] Update solidity --- contracts/connectors/refinance.sol | 156 ++++++++++++++++++++++++++++- 1 file changed, 151 insertions(+), 5 deletions(-) diff --git a/contracts/connectors/refinance.sol b/contracts/connectors/refinance.sol index fe59688..e0b144c 100644 --- a/contracts/connectors/refinance.sol +++ b/contracts/connectors/refinance.sol @@ -1,8 +1,153 @@ -pragma solidity ^0.7.0; +pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; -import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; -import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; +/** + * @dev Interface of the ERC20 standard as defined in the EIP. + */ +interface IERC20 { + /** + * @dev Returns the amount of tokens in existence. + */ + function totalSupply() external view returns (uint256); + + /** + * @dev Returns the amount of tokens owned by `account`. + */ + function balanceOf(address account) external view returns (uint256); + + /** + * @dev Moves `amount` tokens from the caller's account to `recipient`. + * + * Returns a boolean value indicating whether the operation succeeded. + * + * Emits a {Transfer} event. + */ + function transfer(address recipient, uint256 amount) external returns (bool); + + /** + * @dev Returns the remaining number of tokens that `spender` will be + * allowed to spend on behalf of `owner` through {transferFrom}. This is + * zero by default. + * + * This value changes when {approve} or {transferFrom} are called. + */ + function allowance(address owner, address spender) external view returns (uint256); + + /** + * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. + * + * Returns a boolean value indicating whether the operation succeeded. + * + * IMPORTANT: Beware that changing an allowance with this method brings the risk + * that someone may use both the old and the new allowance by unfortunate + * transaction ordering. One possible solution to mitigate this race + * condition is to first reduce the spender's allowance to 0 and set the + * desired value afterwards: + * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 + * + * Emits an {Approval} event. + */ + function approve(address spender, uint256 amount) external returns (bool); + + /** + * @dev Moves `amount` tokens from `sender` to `recipient` using the + * allowance mechanism. `amount` is then deducted from the caller's + * allowance. + * + * Returns a boolean value indicating whether the operation succeeded. + * + * Emits a {Transfer} event. + */ + function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); + + /** + * @dev Emitted when `value` tokens are moved from one account (`from`) to + * another (`to`). + * + * Note that `value` may be zero. + */ + event Transfer(address indexed from, address indexed to, uint256 value); + + /** + * @dev Emitted when the allowance of a `spender` for an `owner` is set by + * a call to {approve}. `value` is the new allowance. + */ + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +/** + * @dev Collection of functions related to the address type + */ +library Address { + function isContract(address account) internal view returns (bool) { + // According to EIP-1052, 0x0 is the value returned for not-yet created accounts + // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned + // for accounts without code, i.e. `keccak256('')` + bytes32 codehash; + bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; + // solhint-disable-next-line no-inline-assembly + assembly { codehash := extcodehash(account) } + return (codehash != accountHash && codehash != 0x0); + } + + + /** + * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with + * `errorMessage` as a fallback revert reason when `target` reverts. + * + * _Available since v3.1._ + */ + function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { + return _functionCallWithValue(target, data, 0, errorMessage); + } + + function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { + require(isContract(target), "Address: call to non-contract"); + + // solhint-disable-next-line avoid-low-level-calls + (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); + if (success) { + return returndata; + } else { + // Look for revert reason and bubble it up if present + if (returndata.length > 0) { + // The easiest way to bubble the revert reason is using memory via assembly + + // solhint-disable-next-line no-inline-assembly + assembly { + let returndata_size := mload(returndata) + revert(add(32, returndata), returndata_size) + } + } else { + revert(errorMessage); + } + } + } +} + +library SafeERC20 { + using Address for address; + + function safeTransfer(IERC20 token, address to, uint256 value) internal { + _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); + } + + function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { + _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); + } + + function _callOptionalReturn(IERC20 token, bytes memory data) private { + // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since + // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that + // the target address contains contract code and also asserts for success in the low-level call. + + bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); + if (returndata.length > 0) { // Return data is optional + // solhint-disable-next-line max-line-length + require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); + } + } +} interface TokenInterface { function approve(address, uint256) external; @@ -805,9 +950,10 @@ contract AaveV2Helpers is AaveV1Helpers { contract RefinanceResolver is AaveV2Helpers { function refinance(RefinanceData calldata data) external payable { - require(data.source != data.target, "source-and-target-unequal"); + CommonData memory commonData; + commonData.length = data.tokens.length; require(data.borrowAmts.length == commonData.length, "length-mismatch"); @@ -864,5 +1010,5 @@ contract RefinanceResolver is AaveV2Helpers { } contract ConnectRefinance is RefinanceResolver { - string public name = "Refinance-v1"; + string public name = "Refinance-v1.2"; } From 5318c8ea5b9ba57e5fc85a40dd0c1f1a5c0a35d2 Mon Sep 17 00:00:00 2001 From: Mubaris NK Date: Thu, 11 Feb 2021 21:44:56 +0530 Subject: [PATCH 4/4] Fix wrong address bug --- contracts/connectors/refinance.sol | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contracts/connectors/refinance.sol b/contracts/connectors/refinance.sol index e0b144c..000c3ac 100644 --- a/contracts/connectors/refinance.sol +++ b/contracts/connectors/refinance.sol @@ -514,7 +514,7 @@ contract CompoundHelpers is Helpers { address _token = address(token) == getWethAddr() ? getEthAddr() : address(token); if (amt == uint(-1)) { - amt = getMaxBorrow(target, address(token), ctoken, rateMode); + amt = getMaxBorrow(target, _token, ctoken, rateMode); } (uint feeAmt, uint _amt) = calculateFee(amt, fee, true); @@ -635,7 +635,7 @@ contract AaveV1Helpers is CompoundHelpers { address _token = address(token) == getWethAddr() ? getEthAddr() : address(token); if (amt == uint(-1)) { - amt = getMaxBorrow(target, address(token), ctoken, paybackRateMode); + amt = getMaxBorrow(target, _token, ctoken, paybackRateMode); } (uint feeAmt, uint _amt) = calculateFee(amt, fee, true);