-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathMultiStrategyTokenImpl.sol
More file actions
532 lines (442 loc) · 20.2 KB
/
Copy pathMultiStrategyTokenImpl.sol
File metadata and controls
532 lines (442 loc) · 20.2 KB
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
pragma solidity 0.6.12;
import "./MultiStrategyTokenStorage.sol";
import "../../interfaces/Wrapped.sol";
import "../../interfaces/IStrategyToken.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
contract MultiStrategyTokenImpl is MultiStrategyTokenStorage {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
event Deposit(address tokenAddress, uint256 depositAmount, uint256 sharesMinted, address strategyAddress);
event Withdraw(address tokenAddress, uint256 withdrawAmount, uint256 sharesBurnt, address strategyAddress);
event Rebalance(address strategyWithdrawn, address strategyDeposited, uint256 amountMoved);
event RatioChanged(address strategyAddress, uint256 ratioBefore, uint256 ratioAfter);
event StrategyActiveSet(address strategyAddress, bool isDeposit, bool value);
event RebalanceThresholdSet(uint256 numer, uint256 denom);
event StrategyAdded(address strategyAddress);
event StrategyRemoved(address strategyAddress);
event DepositPause(address account, bool paused);
event WithdrawPause(address account, bool paused);
constructor () public ERC20("", ""){}
function setGovAddress(address _govAddress) external {
require(msg.sender == govAddress || msg.sender == owner(), "Not authorized");
govAddress = _govAddress;
}
function setPolicyAdmin(address _policyAdmin) external {
require(msg.sender == govAddress || msg.sender == owner(), "Not authorized");
policyAdmin = _policyAdmin;
}
function pauseDeposit() external {
require(!depositPaused, "deposit paused");
require(msg.sender == govAddress || msg.sender == owner(), "Not authorized");
depositPaused = true;
emit DepositPause(msg.sender, true);
}
function unpauseDeposit() external {
require(depositPaused, "deposit not paused");
require(msg.sender == govAddress || msg.sender == owner(), "Not authorized");
depositPaused = false;
emit DepositPause(msg.sender, false);
}
function pauseWithdraw() external virtual {
require(!withdrawPaused, "withdraw paused");
require(msg.sender == govAddress || msg.sender == owner(), "Not authorized");
withdrawPaused = true;
emit WithdrawPause(msg.sender, true);
}
function unpauseWithdraw() external virtual {
require(withdrawPaused, "withdraw not paused");
require(msg.sender == govAddress || msg.sender == owner(), "Not authorized");
withdrawPaused = false;
emit WithdrawPause(msg.sender, false);
}
function deposit(uint256 _amount, uint256 _minShares)
external
{
require(!depositPaused, "deposit paused");
require(_amount != 0, "deposit must be greater than 0");
IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);
_deposit(_amount, _minShares);
}
function depositBNB(uint256 _minShares) external payable {
require(!depositPaused, "deposit paused");
require(isWbnb, "not bnb");
require(msg.value != 0, "deposit must be greater than 0");
_wrapBNB(msg.value);
_deposit(msg.value, _minShares);
}
function _deposit(uint256 _amount, uint256 _minShares)
internal
nonReentrant
{
updateAllStrategies();
uint256 _pool = calcPoolValueInToken();
address strategyAddress;
(strategyAddress,) = findMostInsufficientStrategy();
ISingleStrategyToken(strategyAddress).deposit(_amount, 0);
uint256 sharesToMint = calcPoolValueInToken().sub(_pool);
if (totalSupply() != 0 && _pool != 0) {
sharesToMint = sharesToMint.mul(totalSupply())
.div(_pool);
}
require(sharesToMint >= _minShares, "did not meet minimum shares requested");
_mint(msg.sender, sharesToMint);
emit Deposit(token, _amount, sharesToMint, strategyAddress);
}
function withdraw(uint256 _shares, uint256 _minAmount)
external
{
uint r = _withdraw(_shares, _minAmount);
IERC20(token).safeTransfer(msg.sender, r);
}
function withdrawBNB(uint256 _shares, uint256 _minAmount)
external
{
require(isWbnb, "not bnb");
uint256 r = _withdraw(_shares, _minAmount);
_unwrapBNB(r);
msg.sender.transfer(r);
}
function _withdraw(uint256 _shares, uint256 _minAmount)
internal
nonReentrant
returns (uint256)
{
require(!withdrawPaused, "withdraw paused");
require(_shares != 0, "shares must be greater than 0");
uint256 ibalance = balanceOf(msg.sender);
require(_shares <= ibalance, "insufficient balance");
updateAllStrategies();
uint256 pool = calcPoolValueInToken();
uint256 r = pool.mul(_shares).div(totalSupply());
_burn(msg.sender, _shares);
address strategyToWithdraw;
uint256 strategyAvailableAmount;
(strategyToWithdraw, strategyAvailableAmount) = findMostOverLockedStrategy(r);
if (r > strategyAvailableAmount) {
(strategyToWithdraw, strategyAvailableAmount) = findMostLockedStrategy();
require(r <= strategyAvailableAmount, "withdrawal amount too big");
}
uint256 _stratPool = ISingleStrategyToken(strategyToWithdraw).calcPoolValueInToken();
uint256 stratShares = r
.mul(
IERC20(strategyToWithdraw).totalSupply()
)
.div(_stratPool);
uint256 diff = balance();
ISingleStrategyToken(strategyToWithdraw).withdraw(stratShares, 0/*strategyAvailableAmount*/);
diff = balance().sub(diff);
require(diff >= _minAmount, "did not meet minimum amount requested");
emit Withdraw(token, diff, _shares, strategyToWithdraw);
return diff;
}
function rebalance() public {
require(msg.sender == govAddress || msg.sender == policyAdmin || msg.sender == owner(), "Not authorized");
address strategyToWithdraw;
uint256 strategyAvailableAmount;
address strategyToDeposit;
// uint256 strategyInsuffAmount;
updateAllStrategies();
(strategyToWithdraw, strategyAvailableAmount) = findMostOverLockedStrategy(0);
(strategyToDeposit, /*strategyInsuffAmount*/) = findMostInsufficientStrategy();
uint256 totalBalance = calcPoolValueInToken();
uint256 optimal = totalBalance.mul(ratios[strategyToWithdraw]).div(ratioTotal);
uint256 threshold = optimal.mul(
rebalanceThresholdNumer
).div(rebalanceThresholdDenom);
if (strategyAvailableAmount != 0 && threshold < strategyAvailableAmount) {
uint256 _pool = ISingleStrategyToken(strategyToWithdraw).calcPoolValueInToken();
uint256 stratShares = strategyAvailableAmount
.mul(
IERC20(strategyToWithdraw).totalSupply()
)
.div(_pool);
uint256 diff = balance();
ISingleStrategyToken(strategyToWithdraw).withdraw(stratShares, 0/*strategyAvailableAmount)*/);
diff = balance().sub(diff);
ISingleStrategyToken(strategyToDeposit).deposit(diff, 0);
emit Rebalance(strategyToWithdraw, strategyToDeposit, diff);
}
}
function findMostOverLockedStrategy(uint256 withdrawAmt) public view returns (address, uint256) {
address[] memory strats = getAvailableStrategyList(false);
uint256 totalBalance = calcPoolValueInToken().sub(withdrawAmt);
address overLockedStrategy = strats[0];
uint256 optimal = totalBalance.mul(ratios[strats[0]]).div(ratioTotal);
uint256 current = getBalanceOfOneStrategy(strats[0]);
bool isLessThanOpt = current < optimal;
uint256 overLockedBalance = isLessThanOpt ? optimal.sub(current) : current.sub(optimal);
uint256 i = 1;
for (; i < strats.length; i += 1) {
optimal = totalBalance.mul(ratios[strats[i]]).div(ratioTotal);
current = getBalanceOfOneStrategy(strats[i]);
if (isLessThanOpt && current >= optimal) {
isLessThanOpt = false;
overLockedBalance = current.sub(optimal);
overLockedStrategy = strats[i];
} else if (isLessThanOpt && current < optimal) {
if (optimal.sub(current) < overLockedBalance) {
overLockedBalance = optimal.sub(current);
overLockedStrategy = strats[i];
}
} else if (!isLessThanOpt && current >= optimal) {
if (current.sub(optimal) > overLockedBalance) {
overLockedBalance = current.sub(optimal);
overLockedStrategy = strats[i];
}
}
}
if (isLessThanOpt) {
overLockedBalance = 0;
}
return (overLockedStrategy, overLockedBalance);
}
function findMostLockedStrategy() public view returns (address, uint256) {
address[] memory strats = getAvailableStrategyList(false);
uint256 current;
address lockedMostAddr = strats[0];
uint256 lockedBalance = getBalanceOfOneStrategy(strats[0]);
uint256 i = 1;
for (; i < strats.length; i += 1) {
current = getBalanceOfOneStrategy(strats[i]);
if (current > lockedBalance) {
lockedBalance = current;
lockedMostAddr = strats[i];
}
}
return (lockedMostAddr, lockedBalance);
}
function findMostInsufficientStrategy() public view returns (address, uint256) {
address[] memory strats = getAvailableStrategyList(true);
uint256 totalBalance = calcPoolValueInToken();
address insuffStrategy = strats[0];
uint256 optimal = totalBalance.mul(ratios[strats[0]]).div(ratioTotal);
uint256 current = getBalanceOfOneStrategy(strats[0]);
bool isGreaterThanOpt = current > optimal;
uint256 insuffBalance = isGreaterThanOpt ? current.sub(optimal) : optimal.sub(current);
uint256 i = 1;
for (; i < strats.length; i += 1) {
optimal = totalBalance.mul(ratios[strats[i]]).div(ratioTotal);
current = getBalanceOfOneStrategy(strats[i]);
if (isGreaterThanOpt && current < optimal) {
isGreaterThanOpt = false;
insuffBalance = optimal.sub(current);
insuffStrategy = strats[i];
} else if (isGreaterThanOpt && current > optimal) {
if (current.sub(optimal) < insuffBalance) {
insuffBalance = current.sub(optimal);
insuffStrategy = strats[i];
}
} else if (!isGreaterThanOpt && current <= optimal) {
if (optimal.sub(current) > insuffBalance) {
insuffBalance = optimal.sub(current);
insuffStrategy = strats[i];
}
}
}
if (isGreaterThanOpt) {
insuffBalance = 0;
}
return (insuffStrategy, insuffBalance);
}
function balance() public view returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
function getBalanceOfOneStrategy(address strategyAddress) public view returns (uint256 bal) {
ISingleStrategyToken stToken = ISingleStrategyToken(strategyAddress);
if (stToken.balanceOf(address(this)) != 0) {
bal = stToken.calcPoolValueInToken().mul(
stToken.balanceOf(address(this))
).div(
stToken.totalSupply()
);
} else {
bal = 0;
}
}
function balanceStrategy() public view returns (uint256) {
uint i = 0;
uint sum = 0;
for (; i < strategies.length; i += 1) {
sum = sum.add(getBalanceOfOneStrategy(strategies[i]));
}
return sum;
}
function getAvailableStrategyList(bool isDeposit) internal view returns (address[] memory) {
uint256 activeCnt = isDeposit ? depositActiveCount : withdrawActiveCount;
require(activeCnt != 0, "none of the strategies are active");
address[] memory addrArr = new address[](activeCnt);
uint256 i = 0;
uint256 cnt = 0;
for (; i < strategies.length; i += 1) {
if (isDeposit) {
if (depositActive[strategies[i]]) {
addrArr[cnt] = strategies[i];
cnt += 1;
}
} else {
if (withdrawActive[strategies[i]]) {
addrArr[cnt] = strategies[i];
cnt += 1;
}
}
}
return addrArr;
}
function calcPoolValueInToken() public view returns (uint256) {
return balanceStrategy();
}
function getPricePerFullShare() public view returns (uint) {
uint _pool = calcPoolValueInToken();
return _pool.mul(1e18).div(totalSupply());
}
function changeRatio(uint256 index, uint256 value) external {
require(msg.sender == govAddress || msg.sender == policyAdmin || msg.sender == owner(), "Not authorized");
// require(index != 0);
require(strategies.length > index, "invalid index");
uint256 valueBefore = ratios[strategies[index]];
ratios[strategies[index]] = value;
ratioTotal = ratioTotal.sub(valueBefore).add(value);
emit RatioChanged(strategies[index], valueBefore, value);
}
// doesn"t guarantee that withdrawing shares returned by this function will always be successful.
function getMaxWithdrawableShares() public view returns (uint256) {
require(totalSupply() != 0, "total supply is 0");
uint256 bal;
(, bal) = findMostLockedStrategy();
return amountToShares(bal);
}
function sharesToAmount(uint256 _shares) public view returns (uint256) {
uint256 _pool = calcPoolValueInToken();
return _shares.mul(_pool).div(totalSupply());
}
function amountToShares(uint256 _amount) public view returns (uint256) {
uint256 _pool = calcPoolValueInToken();
uint256 shares;
if (totalSupply() == 0 || _pool == 0) {
shares = _amount;
} else {
shares = (_amount.mul(totalSupply()))
.div(_pool);
}
return shares;
}
function setStrategyActive(uint256 index, bool isDeposit, bool b) public {
require(msg.sender == govAddress || msg.sender == policyAdmin || msg.sender == owner(), "Not authorized");
mapping(address => bool) storage isActive = isDeposit ? depositActive : withdrawActive;
require(index < strategies.length, "invalid index");
require(isActive[strategies[index]] != b, b ? "already active" : "already inactive");
if (isDeposit) {
depositActiveCount = b ? depositActiveCount.add(1) : depositActiveCount.sub(1);
} else {
withdrawActiveCount = b ? withdrawActiveCount.add(1) : withdrawActiveCount.sub(1);
}
isActive[strategies[index]] = b;
emit StrategyActiveSet(strategies[index], isDeposit, b);
}
function setRebalanceThreshold(uint256 _rebalanceThresholdNumer, uint256 _rebalanceThresholdDenom) external {
require(msg.sender == govAddress || msg.sender == policyAdmin || msg.sender == owner(), "Not authorized");
require(_rebalanceThresholdDenom != 0, "denominator should not be 0");
require(_rebalanceThresholdDenom >= _rebalanceThresholdNumer, "denominator should be greater than or equal to the numerator");
rebalanceThresholdNumer = _rebalanceThresholdNumer;
rebalanceThresholdDenom = _rebalanceThresholdDenom;
emit RebalanceThresholdSet(rebalanceThresholdNumer, rebalanceThresholdDenom);
}
function strategyCount() public view returns (uint256) {
return strategies.length;
}
function _wrapBNB(uint256 _amount) internal {
if (address(this).balance >= _amount) {
IWBNB(wbnbAddress).deposit{value: _amount}();
}
}
function _unwrapBNB(uint256 _amount) internal {
uint256 wbnbBal = IERC20(wbnbAddress).balanceOf(address(this));
if (wbnbBal >= _amount) {
IERC20(wbnbAddress).safeApprove(bnbHelper, _amount);
IUnwrapper(bnbHelper).unwrapBNB(_amount);
}
}
function inCaseTokensGetStuck(
address _token,
uint256 _amount,
address _to
) public {
require(msg.sender == govAddress || msg.sender == owner(), "!gov");
require(_token != address(this), "!safe");
uint8 i = 0;
for (; i < strategies.length; i += 1) {
require(_token != strategies[i], "!safe");
}
if (_token == address(0)) {
require(address(this).balance >= _amount, "amount greater than holding");
_wrapBNB(_amount);
_token = wbnbAddress;
} else if (_token == token) {
require(balance() >= _amount, "amount greater than holding");
}
IERC20(_token).safeTransfer(_to, _amount);
}
function getProxyAdmin() public view returns (address adm) {
bytes32 slot = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
// solhint-disable-next-line no-inline-assembly
assembly {
adm := sload(slot)
}
}
function setBNBHelper(address _helper) public {
require(msg.sender == govAddress || msg.sender == owner(), "!gov");
require(_helper != address(0));
bnbHelper = _helper;
}
function updateAllStrategies() public {
uint8 i = 0;
for (; i < strategies.length; i += 1) {
ISingleStrategyToken(strategies[i]).updateStrategy();
}
}
function getStrategyIndex(address strategyAddress) public view returns (uint8) {
for (uint8 i = 0; i < strategies.length; i++) {
if (strategies[i] == strategyAddress) return i;
}
revert("invalid strategy address");
}
function addStrategy(address strategyAddress) internal {
uint8 i = 0;
for (; i < strategies.length; i += 1) {
require(strategies[i] != strategyAddress, "Strategy Already Exists");
}
strategies.push(strategyAddress);
IERC20(token).safeApprove(strategyAddress, uint(-1));
emit StrategyAdded(strategyAddress);
}
function removeStrategy(address strategyAddress) internal {
uint8 index = getStrategyIndex(strategyAddress);
require(index < strategies.length);
address strategyToRemove = strategies[index];
for (uint8 i = index + 1; i < strategies.length; i++) {
strategies[i - 1] = strategies[i];
}
IERC20(token).safeApprove(strategyToRemove, 0);
strategies[strategies.length - 1] = strategyToRemove;
strategies.pop();
ratioTotal = ratioTotal.sub(ratios[strategyToRemove]);
ratios[strategyToRemove] = 0;
if (depositActive[strategyToRemove]) {
depositActiveCount = depositActiveCount.sub(1);
depositActive[strategyToRemove] = false;
}
if (withdrawActive[strategyToRemove]) {
withdrawActiveCount = withdrawActiveCount.sub(1);
withdrawActive[strategyToRemove] = false;
}
emit StrategyRemoved(strategyToRemove);
}
function updateStrategyList() public {
require(msg.sender == govAddress || msg.sender == owner(), "!gov");
}
fallback() external payable {}
receive() external payable {}
}