generated from Badger-Finance/badger-strategy-mix-v1
-
Notifications
You must be signed in to change notification settings - Fork 7
/
StrategyConvexStakingOptimizer.sol
619 lines (514 loc) · 21.2 KB
/
StrategyConvexStakingOptimizer.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.11;
pragma experimental ABIEncoderV2;
import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "interfaces/uniswap/IUniswapRouterV2.sol";
import "interfaces/badger/IBadgerGeyser.sol";
import "interfaces/uniswap/IUniswapPair.sol";
import "interfaces/badger/IController.sol";
import "interfaces/badger/ISettV4.sol";
import "interfaces/convex/IBooster.sol";
import "interfaces/convex/CrvDepositor.sol";
import "interfaces/convex/IBaseRewardsPool.sol";
import "interfaces/convex/ICvxRewardsPool.sol";
import "deps/BaseStrategySwapper.sol";
import "deps/libraries/CurveSwapper.sol";
import "deps/libraries/UniswapSwapper.sol";
import "deps/libraries/TokenSwapPathRegistry.sol";
/*
=== Deposit ===
Deposit & Stake underlying asset into appropriate convex vault (deposit + stake is atomic)
=== Tend ===
== Stage 1: Realize gains from all positions ==
Harvest CRV and CVX from core vault rewards pool
Harvest CVX and SUSHI from CVX/ETH LP
Harvest CVX and SUSHI from cvxCRV/CRV LP
Harvested coins:
CRV
CVX
SUSHI
== Stage 2: Deposit all gains into staked positions ==
Zap all CRV -> cvxCRV/CRV
Zap all CVX -> CVX/ETH
Stake Sushi
Position coins:
cvxCRV/CRV
CVX/ETH
xSushi
These position coins will be distributed on harvest
Changelog:
V1.1
* Implemented the _exchange function from the CurveSwapper library to perform the CRV -> cvxCRV and vice versa
swaps through curve instead of Sushiswap.
* It now swaps 3CRV into CRV instead of cvxCRV. If enough is aquired, it swaps this CRV for wBTC directly and, if not,
it swaps some cvxCRV for CRV to compensate.
* Removed some unused functions and variables such as the `addExtraRewardsToken` and `removeExtraRewardsToken` functions
as well as the obsolete swapping paths.
V1.2
* Removed unused Code
* Changed to purchase bveCVX via Curve Factory Pool
V1.3
* Remove auto compounding
* Added harvest threshold for 3Crv
* Removed unused variables
*/
contract StrategyConvexStakingOptimizer is
BaseStrategy,
CurveSwapper,
UniswapSwapper,
TokenSwapPathRegistry
{
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
// ===== Token Registry =====
address public constant wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52;
address public constant cvx = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
address public constant cvxCrv = 0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7;
address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public constant threeCrv =
0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;
IERC20Upgradeable public constant wbtcToken =
IERC20Upgradeable(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
IERC20Upgradeable public constant crvToken =
IERC20Upgradeable(0xD533a949740bb3306d119CC777fa900bA034cd52);
IERC20Upgradeable public constant cvxToken =
IERC20Upgradeable(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B);
IERC20Upgradeable public constant cvxCrvToken =
IERC20Upgradeable(0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7);
IERC20Upgradeable public constant usdcToken =
IERC20Upgradeable(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20Upgradeable public constant threeCrvToken =
IERC20Upgradeable(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490);
IERC20Upgradeable public constant bveCVX =
IERC20Upgradeable(0xfd05D3C7fe2924020620A8bE4961bBaA747e6305);
// ===== Convex Registry =====
CrvDepositor public constant crvDepositor =
CrvDepositor(0x8014595F2AB54cD7c604B00E9fb932176fDc86Ae); // Convert CRV -> cvxCRV
IBooster public constant booster =
IBooster(0xF403C135812408BFbE8713b5A23a04b3D48AAE31);
IBaseRewardsPool public baseRewardsPool;
IBaseRewardsPool public constant cvxCrvRewardsPool =
IBaseRewardsPool(0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e);
ICvxRewardsPool public constant cvxRewardsPool =
ICvxRewardsPool(0xCF50b810E57Ac33B91dCF525C6ddd9881B139332);
address public constant threeCrvSwap =
0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
uint256 public constant MAX_UINT_256 = uint256(-1);
uint256 public pid;
address public badgerTree;
ISettV4 public cvxCrvHelperVault;
/**
The default conditions for a rewards token are:
- Collect rewards token
- Distribute 100% via Tree to users
=== Harvest Config ===
- autoCompoundingBps: Sell this % of rewards for underlying asset.
- autoCompoundingPerfFee: Of the auto compounded portion, take this % as a performance fee.
- treeDistributionPerfFee: Of the remaining portion (everything not distributed or converted via another mehcanic is distributed via the tree), take this % as a performance fee.
=== Tend Config ===
- tendConvertTo: On tend, convert some of this token into another asset. By default with value as address(0), skip this step.
- tendConvertBps: Convert this portion of balance into another asset.
*/
uint256 public stableSwapSlippageTolerance;
uint256 public constant crvCvxCrvPoolIndex = 2;
// Minimum 3Crv harvested to perform a profitable swap on it
uint256 public minThreeCrvHarvest;
event TreeDistribution(
address indexed token,
uint256 amount,
uint256 indexed blockNumber,
uint256 timestamp
);
event PerformanceFeeGovernance(
address indexed destination,
address indexed token,
uint256 amount,
uint256 indexed blockNumber,
uint256 timestamp
);
event PerformanceFeeStrategist(
address indexed destination,
address indexed token,
uint256 amount,
uint256 indexed blockNumber,
uint256 timestamp
);
event WithdrawState(
uint256 toWithdraw,
uint256 preWant,
uint256 postWant,
uint256 withdrawn
);
struct TendData {
uint256 crvTended;
uint256 cvxTended;
uint256 cvxCrvTended;
}
event TendState(uint256 crvTended, uint256 cvxTended, uint256 cvxCrvTended);
function initialize(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian,
address[3] memory _wantConfig,
uint256 _pid,
uint256[3] memory _feeConfig
) public initializer whenNotPaused {
__BaseStrategy_init(
_governance,
_strategist,
_controller,
_keeper,
_guardian
);
want = _wantConfig[0];
badgerTree = _wantConfig[1];
cvxCrvHelperVault = ISettV4(_wantConfig[2]);
pid = _pid; // Core staking pool ID
IBooster.PoolInfo memory poolInfo = booster.poolInfo(pid);
baseRewardsPool = IBaseRewardsPool(poolInfo.crvRewards);
performanceFeeGovernance = _feeConfig[0];
performanceFeeStrategist = _feeConfig[1];
withdrawalFee = _feeConfig[2];
// Approvals: Staking Pools
IERC20Upgradeable(want).approve(address(booster), MAX_UINT_256);
cvxToken.approve(address(cvxRewardsPool), MAX_UINT_256);
cvxCrvToken.approve(address(cvxCrvRewardsPool), MAX_UINT_256);
// Approvals: CRV -> cvxCRV converter
crvToken.approve(address(crvDepositor), MAX_UINT_256);
// Set Swap Paths
address[] memory path = new address[](3);
path[0] = usdc;
path[1] = weth;
path[2] = crv;
_setTokenSwapPath(usdc, crv, path);
_initializeApprovals();
// Set default values
stableSwapSlippageTolerance = 500;
minThreeCrvHarvest = 1000e18;
}
/// ===== Permissioned Functions =====
function setPid(uint256 _pid) external {
_onlyGovernance();
pid = _pid; // LP token pool ID
}
function initializeApprovals() external {
_onlyGovernance();
_initializeApprovals();
}
function setstableSwapSlippageTolerance(uint256 _sl) external {
_onlyGovernance();
stableSwapSlippageTolerance = _sl;
}
function setMinThreeCrvHarvest(uint256 _minThreeCrvHarvest) external {
_onlyGovernance();
minThreeCrvHarvest = _minThreeCrvHarvest;
}
function _initializeApprovals() internal {
cvxCrvToken.approve(address(cvxCrvHelperVault), MAX_UINT_256);
}
/// ===== View Functions =====
function version() external pure returns (string memory) {
return "1.3";
}
function getName() external pure override returns (string memory) {
return "StrategyConvexStakingOptimizer";
}
function balanceOfPool() public view override returns (uint256) {
return baseRewardsPool.balanceOf(address(this));
}
function getProtectedTokens()
public
view
override
returns (address[] memory)
{
address[] memory protectedTokens = new address[](4);
protectedTokens[0] = want;
protectedTokens[1] = crv;
protectedTokens[2] = cvx;
protectedTokens[3] = cvxCrv;
return protectedTokens;
}
function isTendable() public view override returns (bool) {
return true;
}
/// ===== Internal Core Implementations =====
function _onlyNotProtectedTokens(address _asset) internal override {
require(address(want) != _asset, "want");
require(address(crv) != _asset, "crv");
require(address(cvx) != _asset, "cvx");
require(address(cvxCrv) != _asset, "cvxCrv");
}
/// @dev Deposit Badger into the staking contract
function _deposit(uint256 _want) internal override {
// Deposit all want in core staking pool
booster.deposit(pid, _want, true);
}
/// @dev Unroll from all strategy positions, and transfer non-core tokens to controller rewards
function _withdrawAll() internal override {
baseRewardsPool.withdrawAndUnwrap(balanceOfPool(), false);
// Note: All want is automatically withdrawn outside this "inner hook" in base strategy function
}
/// @dev Withdraw want from staking rewards, using earnings first
function _withdrawSome(uint256 _amount)
internal
override
returns (uint256)
{
// Get idle want in the strategy
uint256 _preWant = IERC20Upgradeable(want).balanceOf(address(this));
// If we lack sufficient idle want, withdraw the difference from the strategy position
if (_preWant < _amount) {
uint256 _toWithdraw = _amount.sub(_preWant);
baseRewardsPool.withdrawAndUnwrap(_toWithdraw, false);
}
// Confirm how much want we actually end up with
uint256 _postWant = IERC20Upgradeable(want).balanceOf(address(this));
// Return the actual amount withdrawn if less than requested
uint256 _withdrawn = MathUpgradeable.min(_postWant, _amount);
emit WithdrawState(_amount, _preWant, _postWant, _withdrawn);
return _withdrawn;
}
function _tendGainsFromPositions() internal {
// Harvest CRV, CVX, cvxCRV, 3CRV, and extra rewards tokens from staking positions
// Note: Always claim extras
baseRewardsPool.getReward(address(this), true);
if (cvxCrvRewardsPool.earned(address(this)) > 0) {
cvxCrvRewardsPool.getReward(address(this), true);
}
if (cvxRewardsPool.earned(address(this)) > 0) {
cvxRewardsPool.getReward(false);
}
}
/// @notice The more frequent the tend, the higher returns will be
function tend() external whenNotPaused returns (TendData memory) {
_onlyAuthorizedActors();
TendData memory tendData;
// 1. Harvest gains from positions
_tendGainsFromPositions();
// Track harvested coins, before conversion
tendData.crvTended = crvToken.balanceOf(address(this));
// 2. Convert CRV -> cvxCRV
if (tendData.crvTended > 0) {
uint256 minCvxCrvOut =
tendData
.crvTended
.mul(MAX_FEE.sub(stableSwapSlippageTolerance))
.div(MAX_FEE);
_exchange(
crv,
cvxCrv,
tendData.crvTended,
minCvxCrvOut,
crvCvxCrvPoolIndex,
true
);
}
// Track harvested + converted coins
tendData.cvxCrvTended = cvxCrvToken.balanceOf(address(this));
tendData.cvxTended = cvxToken.balanceOf(address(this));
// 3. Stake all cvxCRV
if (tendData.cvxCrvTended > 0) {
cvxCrvRewardsPool.stake(tendData.cvxCrvTended);
}
// 4. Stake all CVX
if (tendData.cvxTended > 0) {
cvxRewardsPool.stake(cvxToken.balanceOf(address(this)));
}
emit Tend(0);
emit TendState(
tendData.crvTended,
tendData.cvxTended,
tendData.cvxCrvTended
);
return tendData;
}
// No-op until we optimize harvesting strategy. Auto-compouding is key.
function harvest() external whenNotPaused returns (uint256) {
_onlyAuthorizedActors();
uint256 totalWantBefore = balanceOf();
// TODO: Harvest details still under constructuion. It's being designed to optimize yield while still allowing on-demand access to profits for users.
// 1. Withdraw accrued rewards from staking positions (claim unclaimed positions as well)
baseRewardsPool.getReward(address(this), true);
uint256 cvxCrvRewardsPoolBalance =
cvxCrvRewardsPool.balanceOf(address(this));
if (cvxCrvRewardsPoolBalance > 0) {
cvxCrvRewardsPool.withdraw(cvxCrvRewardsPoolBalance, true);
}
uint256 cvxRewardsPoolBalance = cvxRewardsPool.balanceOf(address(this));
if (cvxRewardsPoolBalance > 0) {
cvxRewardsPool.withdraw(cvxRewardsPoolBalance, true);
}
// 2. Convert 3CRV -> CRV via USDC
uint256 threeCrvBalance = threeCrvToken.balanceOf(address(this));
if (threeCrvBalance > minThreeCrvHarvest) {
_remove_liquidity_one_coin(threeCrvSwap, threeCrvBalance, 1, 0);
uint256 usdcBalance = usdcToken.balanceOf(address(this));
if (usdcBalance > 0) {
_swapExactTokensForTokens(
sushiswap,
usdc,
usdcBalance,
getTokenSwapPath(usdc, crv)
);
}
}
// 3. Convert CRV -> cvxCRV
uint256 crvBalance = crvToken.balanceOf(address(this));
if (crvBalance > 0) {
uint256 minCvxCrvOut =
crvBalance.mul(MAX_FEE.sub(stableSwapSlippageTolerance)).div(
MAX_FEE
);
_exchange(
crv,
cvxCrv,
crvBalance,
minCvxCrvOut,
crvCvxCrvPoolIndex,
true
);
}
// 4. Deposit cvxCRV rewards into helper vault and distribute
uint256 cvxCrvToDistribute = cvxCrvToken.balanceOf(address(this));
if (cvxCrvToDistribute > 0) {
if (performanceFeeGovernance > 0) {
uint256 cvxCrvToGovernance =
cvxCrvToDistribute.mul(performanceFeeGovernance).div(
MAX_FEE
);
uint256 govHelperVaultBefore =
cvxCrvHelperVault.balanceOf(
IController(controller).rewards()
);
cvxCrvHelperVault.depositFor(
IController(controller).rewards(),
cvxCrvToGovernance
);
uint256 govHelperVaultAfter =
cvxCrvHelperVault.balanceOf(
IController(controller).rewards()
);
uint256 govVaultPositionGained =
govHelperVaultAfter.sub(govHelperVaultBefore);
emit PerformanceFeeGovernance(
IController(controller).rewards(),
address(cvxCrvHelperVault),
govVaultPositionGained,
block.number,
block.timestamp
);
}
if (performanceFeeStrategist > 0) {
uint256 cvxCrvToStrategist =
cvxCrvToDistribute.mul(performanceFeeStrategist).div(
MAX_FEE
);
uint256 strategistHelperVaultBefore =
cvxCrvHelperVault.balanceOf(strategist);
cvxCrvHelperVault.depositFor(strategist, cvxCrvToStrategist);
uint256 strategistHelperVaultAfter =
cvxCrvHelperVault.balanceOf(strategist);
uint256 strategistVaultPositionGained =
strategistHelperVaultAfter.sub(strategistHelperVaultBefore);
emit PerformanceFeeStrategist(
strategist,
address(cvxCrvHelperVault),
strategistVaultPositionGained,
block.number,
block.timestamp
);
}
// TODO: [Optimization] Allow contract to circumvent blockLock to dedup deposit operations
uint256 treeHelperVaultBefore =
cvxCrvHelperVault.balanceOf(badgerTree);
// Deposit remaining to tree after taking fees.
uint256 cvxCrvToTree = cvxCrvToken.balanceOf(address(this));
cvxCrvHelperVault.depositFor(badgerTree, cvxCrvToTree);
uint256 treeHelperVaultAfter =
cvxCrvHelperVault.balanceOf(badgerTree);
uint256 treeVaultPositionGained =
treeHelperVaultAfter.sub(treeHelperVaultBefore);
emit TreeDistribution(
address(cvxCrvHelperVault),
treeVaultPositionGained,
block.number,
block.timestamp
);
}
// 5. Swap CVX for bveCVX and distribute
uint256 cvxToDistribute = cvxToken.balanceOf(address(this));
if (cvxToDistribute > 0) {
uint256 minbveCVXOut =
cvxToDistribute
.mul(MAX_FEE.sub(stableSwapSlippageTolerance))
.div(MAX_FEE);
// Get the bveCVX here
_exchange(
address(cvxToken),
address(bveCVX),
cvxToDistribute,
minbveCVXOut,
0,
true
);
uint256 bveCVXAmount = bveCVX.balanceOf(address(this));
if (performanceFeeGovernance > 0) {
uint256 bveCvxToGovernance =
bveCVXAmount.mul(performanceFeeGovernance).div(MAX_FEE);
bveCVX.safeTransfer(
IController(controller).rewards(),
bveCvxToGovernance
);
emit PerformanceFeeGovernance(
IController(controller).rewards(),
address(bveCVX),
bveCvxToGovernance,
block.number,
block.timestamp
);
}
if (performanceFeeStrategist > 0) {
uint256 bveCvxToStrategist =
bveCVXAmount.mul(performanceFeeStrategist).div(MAX_FEE);
bveCVX.safeTransfer(strategist, bveCvxToStrategist);
emit PerformanceFeeStrategist(
strategist,
address(bveCVX),
bveCvxToStrategist,
block.number,
block.timestamp
);
}
uint256 treeHelperVaultBefore = bveCVX.balanceOf(badgerTree);
// Deposit remaining to tree after taking fees.
uint256 bveCvxToTree = bveCVX.balanceOf(address(this));
bveCVX.safeTransfer(badgerTree, bveCvxToTree);
uint256 treeHelperVaultAfter = bveCVX.balanceOf(badgerTree);
uint256 treeVaultPositionGained =
treeHelperVaultAfter.sub(treeHelperVaultBefore);
emit TreeDistribution(
address(bveCVX),
treeVaultPositionGained,
block.number,
block.timestamp
);
}
uint256 totalWantAfter = balanceOf();
require(totalWantAfter >= totalWantBefore, "want-decreased");
// Expected to be 0 since there is no auto compounding
uint256 wantGained = totalWantAfter - totalWantBefore;
emit Harvest(wantGained, block.number);
return wantGained;
}
}