This repository has been archived by the owner on Nov 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathAuraSpell.sol
225 lines (197 loc) · 8.82 KB
/
AuraSpell.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
// SPDX-License-Identifier: MIT
/*
██████╗ ██╗ ██╗ ██╗███████╗██████╗ ███████╗██████╗ ██████╗ ██╗ ██╗
██╔══██╗██║ ██║ ██║██╔════╝██╔══██╗██╔════╝██╔══██╗██╔══██╗╚██╗ ██╔╝
██████╔╝██║ ██║ ██║█████╗ ██████╔╝█████╗ ██████╔╝██████╔╝ ╚████╔╝
██╔══██╗██║ ██║ ██║██╔══╝ ██╔══██╗██╔══╝ ██╔══██╗██╔══██╗ ╚██╔╝
██████╔╝███████╗╚██████╔╝███████╗██████╔╝███████╗██║ ██║██║ ██║ ██║
╚═════╝ ╚══════╝ ╚═════╝ ╚══════╝╚═════╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝
*/
pragma solidity 0.8.16;
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "./BasicSpell.sol";
import "../interfaces/ICurveOracle.sol";
import "../interfaces/IWAuraPools.sol";
import "../interfaces/balancer/IBalancerPool.sol";
import "../interfaces/uniswap/IUniswapV2Router02.sol";
/**
* @title AuraSpell
* @author BlueberryProtocol
* @notice AuraSpell is the factory contract that
* defines how Blueberry Protocol interacts with Aura pools
*/
contract AuraSpell is BasicSpell {
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @dev Address to Wrapped Aura Pools
IWAuraPools public wAuraPools;
/// @dev address of CurveOracle
ICurveOracle public crvOracle;
/// @dev address of AURA token
address public AURA;
function initialize(
IBank bank_,
address werc20_,
address weth_,
address wAuraPools_
) external initializer {
__BasicSpell_init(bank_, werc20_, weth_);
if (wAuraPools_ == address(0)) revert Errors.ZERO_ADDRESS();
wAuraPools = IWAuraPools(wAuraPools_);
AURA = address(wAuraPools.AURA());
IWAuraPools(wAuraPools_).setApprovalForAll(address(bank_), true);
}
/**
* @notice Add strategy to the spell
* @param bpt Address of Balaner Pool Token
* @param maxPosSize, USD price of maximum position size for given strategy, based 1e18
*/
function addStrategy(address bpt, uint256 maxPosSize) external onlyOwner {
_addStrategy(bpt, maxPosSize);
}
/**
* @notice Add liquidity to Balancer pool, with staking to Aura
*/
function openPositionFarm(
OpenPosParam calldata param
)
external
existingStrategy(param.strategyId)
existingCollateral(param.strategyId, param.collToken)
{
Strategy memory strategy = strategies[param.strategyId];
(address lpToken, ) = wAuraPools.getPool(
strategy.vault,
param.farmingPoolId
);
if (strategy.vault != lpToken) revert Errors.INCORRECT_LP(lpToken);
// 1. Deposit isolated collaterals on Blueberry Money Market
_doLend(param.collToken, param.collAmount);
// 2. Borrow specific amounts
uint256 borrowBalance = _doBorrow(
param.borrowToken,
param.borrowAmount
);
// 3. Add liquidity on Balancer, get BPT
{
IBalancerVault vault = wAuraPools.getVault(lpToken);
_ensureApprove(param.borrowToken, address(vault), borrowBalance);
(address[] memory tokens, uint256[] memory balances, ) = wAuraPools
.getPoolTokens(lpToken);
uint[] memory maxAmountsIn = new uint[](2);
maxAmountsIn[0] = IERC20(tokens[0]).balanceOf(address(this));
maxAmountsIn[1] = IERC20(tokens[1]).balanceOf(address(this));
uint totalLPSupply = IBalancerPool(lpToken).totalSupply();
// compute in reverse order of how Balancer's `joinPool` computes tokenAmountIn
uint poolAmountFromA = (maxAmountsIn[0] * totalLPSupply) /
balances[0];
uint poolAmountFromB = (maxAmountsIn[1] * totalLPSupply) /
balances[1];
uint poolAmountOut = poolAmountFromA > poolAmountFromB
? poolAmountFromB
: poolAmountFromA;
bytes32 poolId = bytes32(param.farmingPoolId);
if (poolAmountOut > 0) {
vault.joinPool(
poolId,
address(this),
address(this),
IBalancerVault.JoinPoolRequest(
tokens,
maxAmountsIn,
"",
false
)
);
}
}
// 4. Validate MAX LTV
_validateMaxLTV(param.strategyId);
// 5. Validate Max Pos Size
_validateMaxPosSize(param.strategyId);
// 6. Take out existing collateral and burn
IBank.Position memory pos = bank.getCurrentPositionInfo();
if (pos.collateralSize > 0) {
(uint256 pid, ) = wAuraPools.decodeId(pos.collId);
if (param.farmingPoolId != pid)
revert Errors.INCORRECT_PID(param.farmingPoolId);
if (pos.collToken != address(wAuraPools))
revert Errors.INCORRECT_COLTOKEN(pos.collToken);
bank.takeCollateral(pos.collateralSize);
wAuraPools.burn(pos.collId, pos.collateralSize);
_doRefundRewards(AURA);
}
// 7. Deposit on Aura Pool, Put wrapped collateral tokens on Blueberry Bank
uint256 lpAmount = IERC20Upgradeable(lpToken).balanceOf(address(this));
_ensureApprove(lpToken, address(wAuraPools), lpAmount);
uint256 id = wAuraPools.mint(param.farmingPoolId, lpAmount);
bank.putCollateral(address(wAuraPools), id, lpAmount);
}
function closePositionFarm(
ClosePosParam calldata param,
IUniswapV2Router02 swapRouter,
address[][] calldata swapPath
)
external
existingStrategy(param.strategyId)
existingCollateral(param.strategyId, param.collToken)
{
address lpToken = strategies[param.strategyId].vault;
IBank.Position memory pos = bank.getCurrentPositionInfo();
if (pos.collToken != address(wAuraPools))
revert Errors.INCORRECT_COLTOKEN(pos.collToken);
if (wAuraPools.getUnderlyingToken(pos.collId) != lpToken)
revert Errors.INCORRECT_UNDERLYING(lpToken);
// 1. Take out collateral - Burn wrapped tokens, receive BPT tokens and harvest AURA
bank.takeCollateral(param.amountPosRemove);
(address[] memory rewardTokens, ) = wAuraPools.burn(
pos.collId,
param.amountPosRemove
);
{
// 2. Calculate actual amount to remove
uint256 amountPosRemove = param.amountPosRemove;
if (amountPosRemove == type(uint256).max) {
amountPosRemove = IERC20Upgradeable(lpToken).balanceOf(
address(this)
);
}
// 3. Remove liquidity
(address[] memory tokens, , ) = wAuraPools.getPoolTokens(lpToken);
uint[] memory minAmountsOut = new uint[](2);
wAuraPools.getVault(lpToken).exitPool(
IBalancerPool(lpToken).getPoolId(),
address(this),
address(this),
IBalancerVault.ExitPoolRequest(tokens, minAmountsOut, "", false)
);
}
// 4. Swap rewards tokens to debt token
for (uint256 i = 0; i < rewardTokens.length; i++) {
uint256 rewards = _doCutRewardsFee(rewardTokens[i]);
_ensureApprove(rewardTokens[i], address(swapRouter), rewards);
swapRouter.swapExactTokensForTokens(
rewards,
0,
swapPath[i],
address(this),
type(uint256).max
);
}
// 5. Withdraw isolated collateral from Bank
_doWithdraw(param.collToken, param.amountShareWithdraw);
// 6. Repay
{
// Compute repay amount if MAX_INT is supplied (max debt)
uint256 amountRepay = param.amountRepay;
if (amountRepay == type(uint256).max) {
amountRepay = bank.currentPositionDebt(bank.POSITION_ID());
}
_doRepay(param.borrowToken, amountRepay);
}
_validateMaxLTV(param.strategyId);
// 7. Refund
_doRefund(param.borrowToken);
_doRefund(param.collToken);
_doRefund(AURA);
}
}