generated from yearn/brownie-strategy-mix
-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathStrategy.sol
567 lines (470 loc) · 19 KB
/
Strategy.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
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./GenericLender/IGenericLender.sol";
import "./WantToEthOracle/IWantToEth.sol";
import "@yearnvaults/contracts/BaseStrategy.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
interface IUni {
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
}
/********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/yearnV2-generic-lender-strat
* v0.2.2
*
* This strategy works by taking plugins designed for standard lending platforms
* It automatically chooses the best yield generating platform and adjusts accordingly
* The adjustment is sub optimal so there is an additional option to manually set position
*
********************* */
contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IGenericLender[] public lenders;
bool public externalOracle = false;
address public wantToEthOracle;
constructor(address _vault) public BaseStrategy(_vault) {
debtThreshold = 1000;
//we do this horrible thing because you can't compare strings in solidity
require(keccak256(bytes(apiVersion())) == keccak256(bytes(VaultAPI(_vault).apiVersion())), "WRONG VERSION");
}
function setPriceOracle(address _oracle) external onlyAuthorized {
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiser";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav += want.balanceOf(address(this));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function estimatedAPR() public view returns (uint256) {
uint256 bal = estimatedTotalAssets();
if (bal == 0) {
return 0;
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR += lenders[i].weightedApr();
}
return weightedAPR.div(bal);
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR += lenders[i].weightedApr();
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR += lenders[i].weightedApr();
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR += lowestApr.mul(change);
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav += lenders[i].nav();
}
return nav;
}
//we need to free up profit plus _debtOutstanding.
//If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
//we just keep all money in want if we dont have any lenders
if (lenders.length == 0) {
return;
}
_debtOutstanding; //ignored. we handle it in prepare return
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000.
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[j].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share += _newPositions[i].share;
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
//dont withdraw dust
if (_amount < debtThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn += lenders[lowest].withdraw(_amount - amountWithdrawn);
j++;
//dont want infinite loop
if (j >= 6) {
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded, 0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded, 0);
} else {
return (received, 0);
}
}
}
function harvestTrigger(uint256 callCost) public view override returns (bool) {
uint256 wantCallCost = _callCostToWant(callCost);
return super.harvestTrigger(wantCallCost);
}
function ethToWant(uint256 _amount) internal view returns (uint256) {
address[] memory path = new address[](2);
path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256) {
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if (address(want) == weth) {
wantCallCost = callCost;
} else if (wantToEthOracle == address(0)) {
wantCallCost = ethToWant(callCost);
} else {
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//profit increase is 1 days profit with new apr
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).div(365);
uint256 wantCallCost = _callCostToWant(callCost);
return (wantCallCost * callCost < profitIncrease);
}
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
(, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding);
require(wantBalance.add(loss) >= outstanding, "LIQUIDITY LOCKED");
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
}