|
| 1 | +// SPDX-License-Identifier: UNLICENSED |
| 2 | +pragma solidity ^0.8.27; |
| 3 | + |
| 4 | +import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; |
| 5 | +import {BaseHook} from "v4-periphery/src/utils/BaseHook.sol"; |
| 6 | +import {PoolKey} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; |
| 7 | +import {Currency} from "@uniswap/v4-core/src/types/Currency.sol"; |
| 8 | +import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol"; |
| 9 | +import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol"; |
| 10 | +import {SafeCast} from "@uniswap/v4-core/src/libraries/SafeCast.sol"; |
| 11 | +import { |
| 12 | + BeforeSwapDelta, toBeforeSwapDelta, BeforeSwapDeltaLibrary |
| 13 | +} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol"; |
| 14 | +import {EulerSwap, IEulerSwap, IEVault} from "./EulerSwap.sol"; |
| 15 | + |
| 16 | +contract EulerSwapHook is EulerSwap, BaseHook { |
| 17 | + using SafeCast for uint256; |
| 18 | + |
| 19 | + PoolKey internal _poolKey; |
| 20 | + |
| 21 | + constructor(IPoolManager _manager, Params memory params, CurveParams memory curveParams) |
| 22 | + EulerSwap(params, curveParams) |
| 23 | + BaseHook(_manager) |
| 24 | + { |
| 25 | + address asset0Addr = IEVault(params.vault0).asset(); |
| 26 | + address asset1Addr = IEVault(params.vault1).asset(); |
| 27 | + |
| 28 | + // convert fee in WAD to pips. 0.003e18 / 1e12 = 3000 = 0.30% |
| 29 | + uint24 fee = uint24(params.fee / 1e12); |
| 30 | + |
| 31 | + _poolKey = PoolKey({ |
| 32 | + currency0: Currency.wrap(asset0Addr), |
| 33 | + currency1: Currency.wrap(asset1Addr), |
| 34 | + fee: fee, |
| 35 | + tickSpacing: 60, // TODO: fix arbitrary tick spacing |
| 36 | + hooks: IHooks(address(this)) |
| 37 | + }); |
| 38 | + |
| 39 | + // create the pool on v4, using starting price as sqrtPrice(1/1) * Q96 |
| 40 | + poolManager.initialize(_poolKey, 79228162514264337593543950336); |
| 41 | + } |
| 42 | + |
| 43 | + /// @dev Helper function to return the poolKey as its struct type |
| 44 | + function poolKey() external view returns (PoolKey memory) { |
| 45 | + return _poolKey; |
| 46 | + } |
| 47 | + |
| 48 | + function _beforeSwap(address, PoolKey calldata key, IPoolManager.SwapParams calldata params, bytes calldata) |
| 49 | + internal |
| 50 | + override |
| 51 | + returns (bytes4, BeforeSwapDelta, uint24) |
| 52 | + { |
| 53 | + // determine inbound/outbound token based on 0->1 or 1->0 swap |
| 54 | + bool zeroForOne = params.zeroForOne; |
| 55 | + |
| 56 | + uint256 amountInWithoutFee; |
| 57 | + uint256 amountOut; |
| 58 | + BeforeSwapDelta returnDelta; |
| 59 | + |
| 60 | + { |
| 61 | + (Currency inputCurrency, Currency outputCurrency) = |
| 62 | + zeroForOne ? (key.currency0, key.currency1) : (key.currency1, key.currency0); |
| 63 | + |
| 64 | + uint256 amountIn; |
| 65 | + bool isExactInput = params.amountSpecified < 0; |
| 66 | + if (isExactInput) { |
| 67 | + amountIn = uint256(-params.amountSpecified); |
| 68 | + amountOut = computeQuote(zeroForOne, uint256(-params.amountSpecified), true); |
| 69 | + } else { |
| 70 | + amountIn = computeQuote(zeroForOne, uint256(params.amountSpecified), false); |
| 71 | + amountOut = uint256(params.amountSpecified); |
| 72 | + } |
| 73 | + |
| 74 | + // return the delta to the PoolManager, so it can process the accounting |
| 75 | + // exact input: |
| 76 | + // specifiedDelta = positive, to offset the input token taken by the hook (negative delta) |
| 77 | + // unspecifiedDelta = negative, to offset the credit of the output token paid by the hook (positive delta) |
| 78 | + // exact output: |
| 79 | + // specifiedDelta = negative, to offset the output token paid by the hook (positive delta) |
| 80 | + // unspecifiedDelta = positive, to offset the input token taken by the hook (negative delta) |
| 81 | + returnDelta = isExactInput |
| 82 | + ? toBeforeSwapDelta(amountIn.toInt128(), -(amountOut.toInt128())) |
| 83 | + : toBeforeSwapDelta(-(amountOut.toInt128()), amountIn.toInt128()); |
| 84 | + |
| 85 | + // take the input token, from the PoolManager to the Euler vault |
| 86 | + // the debt will be paid by the swapper via the swap router |
| 87 | + // TODO: can we optimize the transfer by pulling from PoolManager directly to Euler? |
| 88 | + poolManager.take(inputCurrency, address(this), amountIn); |
| 89 | + amountInWithoutFee = depositAssets(zeroForOne ? asset0 : asset1, zeroForOne ? vault0 : vault1); |
| 90 | + |
| 91 | + // pay the output token, to the PoolManager from an Euler vault |
| 92 | + // the credit will be forwarded to the swap router, which then forwards it to the swapper |
| 93 | + poolManager.sync(outputCurrency); |
| 94 | + withdrawAssets(zeroForOne ? vault1 : vault0, amountOut, address(poolManager)); |
| 95 | + poolManager.settle(); |
| 96 | + } |
| 97 | + |
| 98 | + { |
| 99 | + uint256 newReserve0 = zeroForOne ? (reserve0 + amountInWithoutFee) : (reserve0 - amountOut); |
| 100 | + uint256 newReserve1 = !zeroForOne ? (reserve1 + amountInWithoutFee) : (reserve1 - amountOut); |
| 101 | + |
| 102 | + require(newReserve0 <= type(uint112).max && newReserve1 <= type(uint112).max, Overflow()); |
| 103 | + require(verify(newReserve0, newReserve1), CurveViolation()); |
| 104 | + |
| 105 | + reserve0 = uint112(newReserve0); |
| 106 | + reserve1 = uint112(newReserve1); |
| 107 | + } |
| 108 | + |
| 109 | + return (BaseHook.beforeSwap.selector, returnDelta, 0); |
| 110 | + } |
| 111 | + |
| 112 | + // TODO: fix salt mining & verification for the hook |
| 113 | + function getHookPermissions() public pure override returns (Hooks.Permissions memory) {} |
| 114 | + function validateHookAddress(BaseHook) internal pure override {} |
| 115 | + |
| 116 | + error SwapLimitExceeded(); |
| 117 | + error OperatorNotInstalled(); |
| 118 | + |
| 119 | + function computeQuote(bool asset0IsInput, uint256 amount, bool exactIn) internal view returns (uint256) { |
| 120 | + require(evc.isAccountOperatorAuthorized(eulerAccount, address(this)), OperatorNotInstalled()); |
| 121 | + require(amount <= type(uint112).max, SwapLimitExceeded()); |
| 122 | + |
| 123 | + // exactIn: decrease effective amountIn |
| 124 | + if (exactIn) amount = amount - (amount * fee / 1e18); |
| 125 | + |
| 126 | + (uint256 inLimit, uint256 outLimit) = calcLimits(asset0IsInput); |
| 127 | + |
| 128 | + uint256 quote = binarySearch(amount, exactIn, asset0IsInput); |
| 129 | + |
| 130 | + if (exactIn) { |
| 131 | + // if `exactIn`, `quote` is the amount of assets to buy from the AMM |
| 132 | + require(amount <= inLimit && quote <= outLimit, SwapLimitExceeded()); |
| 133 | + } else { |
| 134 | + // if `!exactIn`, `amount` is the amount of assets to buy from the AMM |
| 135 | + require(amount <= outLimit && quote <= inLimit, SwapLimitExceeded()); |
| 136 | + } |
| 137 | + |
| 138 | + // exactOut: inflate required amountIn |
| 139 | + if (!exactIn) quote = (quote * 1e18) / (1e18 - fee); |
| 140 | + |
| 141 | + return quote; |
| 142 | + } |
| 143 | + |
| 144 | + function binarySearch(uint256 amount, bool exactIn, bool asset0IsInput) internal view returns (uint256 output) { |
| 145 | + int256 dx; |
| 146 | + int256 dy; |
| 147 | + |
| 148 | + if (exactIn) { |
| 149 | + if (asset0IsInput) dx = int256(amount); |
| 150 | + else dy = int256(amount); |
| 151 | + } else { |
| 152 | + if (asset0IsInput) dy = -int256(amount); |
| 153 | + else dx = -int256(amount); |
| 154 | + } |
| 155 | + |
| 156 | + unchecked { |
| 157 | + int256 reserve0New = int256(uint256(reserve0)) + dx; |
| 158 | + int256 reserve1New = int256(uint256(reserve1)) + dy; |
| 159 | + require(reserve0New > 0 && reserve1New > 0, SwapLimitExceeded()); |
| 160 | + |
| 161 | + uint256 low; |
| 162 | + uint256 high = type(uint112).max; |
| 163 | + |
| 164 | + while (low < high) { |
| 165 | + uint256 mid = (low + high) / 2; |
| 166 | + require(mid > 0, SwapLimitExceeded()); |
| 167 | + (uint256 a, uint256 b) = dy == 0 ? (uint256(reserve0New), mid) : (mid, uint256(reserve1New)); |
| 168 | + if (verify(a, b)) { |
| 169 | + high = mid; |
| 170 | + } else { |
| 171 | + low = mid + 1; |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + require(high < type(uint112).max, SwapLimitExceeded()); // at least one point verified |
| 176 | + |
| 177 | + if (dx != 0) dy = int256(low) - reserve1New; |
| 178 | + else dx = int256(low) - reserve0New; |
| 179 | + } |
| 180 | + |
| 181 | + if (exactIn) { |
| 182 | + if (asset0IsInput) output = uint256(-dy); |
| 183 | + else output = uint256(-dx); |
| 184 | + } else { |
| 185 | + if (asset0IsInput) output = dx >= 0 ? uint256(dx) : 0; |
| 186 | + else output = dy >= 0 ? uint256(dy) : 0; |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + function calcLimits(bool asset0IsInput) internal view returns (uint256, uint256) { |
| 191 | + uint256 inLimit = type(uint112).max; |
| 192 | + uint256 outLimit = type(uint112).max; |
| 193 | + |
| 194 | + (IEVault vault0, IEVault vault1) = (IEVault(vault0), IEVault(vault1)); |
| 195 | + // Supply caps on input |
| 196 | + { |
| 197 | + IEVault vault = (asset0IsInput ? vault0 : vault1); |
| 198 | + uint256 maxDeposit = vault.debtOf(eulerAccount) + vault.maxDeposit(eulerAccount); |
| 199 | + if (maxDeposit < inLimit) inLimit = maxDeposit; |
| 200 | + } |
| 201 | + |
| 202 | + // Remaining reserves of output |
| 203 | + { |
| 204 | + uint112 reserveLimit = asset0IsInput ? reserve1 : reserve0; |
| 205 | + if (reserveLimit < outLimit) outLimit = reserveLimit; |
| 206 | + } |
| 207 | + |
| 208 | + // Remaining cash and borrow caps in output |
| 209 | + { |
| 210 | + IEVault vault = (asset0IsInput ? vault1 : vault0); |
| 211 | + |
| 212 | + uint256 cash = vault.cash(); |
| 213 | + if (cash < outLimit) outLimit = cash; |
| 214 | + |
| 215 | + (, uint16 borrowCap) = vault.caps(); |
| 216 | + uint256 maxWithdraw = decodeCap(uint256(borrowCap)); |
| 217 | + maxWithdraw = vault.totalBorrows() > maxWithdraw ? 0 : maxWithdraw - vault.totalBorrows(); |
| 218 | + if (maxWithdraw > cash) maxWithdraw = cash; |
| 219 | + maxWithdraw += vault.convertToAssets(vault.balanceOf(eulerAccount)); |
| 220 | + if (maxWithdraw < outLimit) outLimit = maxWithdraw; |
| 221 | + } |
| 222 | + |
| 223 | + return (inLimit, outLimit); |
| 224 | + } |
| 225 | + |
| 226 | + function decodeCap(uint256 amountCap) internal pure returns (uint256) { |
| 227 | + if (amountCap == 0) return type(uint256).max; |
| 228 | + |
| 229 | + unchecked { |
| 230 | + // Cannot overflow because this is less than 2**256: |
| 231 | + // 10**(2**6 - 1) * (2**10 - 1) = 1.023e+66 |
| 232 | + return 10 ** (amountCap & 63) * (amountCap >> 6) / 100; |
| 233 | + } |
| 234 | + } |
| 235 | +} |
0 commit comments