-
Notifications
You must be signed in to change notification settings - Fork 54
/
DexStrategyV5a.sol
1151 lines (981 loc) · 41.1 KB
/
DexStrategyV5a.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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Sources flattened with hardhat v2.2.1 https://hardhat.org
// File contracts/lib/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol
// Subject to the MIT license.
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction underflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts with custom message on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File contracts/lib/Context.sol
pragma solidity ^0.7.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File contracts/lib/Ownable.sol
pragma solidity ^0.7.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File contracts/lib/Permissioned.sol
pragma solidity ^0.7.0;
abstract contract Permissioned is Ownable {
using SafeMath for uint;
uint public numberOfAllowedDepositors;
mapping(address => bool) public allowedDepositors;
event AllowDepositor(address indexed account);
event RemoveDepositor(address indexed account);
modifier onlyAllowedDeposits() {
if (numberOfAllowedDepositors > 0) {
require(allowedDepositors[msg.sender] == true, "Permissioned::onlyAllowedDeposits, not allowed");
}
_;
}
/**
* @notice Add an allowed depositor
* @param depositor address
*/
function allowDepositor(address depositor) external onlyOwner {
require(allowedDepositors[depositor] == false, "Permissioned::allowDepositor");
allowedDepositors[depositor] = true;
numberOfAllowedDepositors = numberOfAllowedDepositors.add(1);
emit AllowDepositor(depositor);
}
/**
* @notice Remove an allowed depositor
* @param depositor address
*/
function removeDepositor(address depositor) external onlyOwner {
require(numberOfAllowedDepositors > 0, "Permissioned::removeDepositor, no allowed depositors");
require(allowedDepositors[depositor] == true, "Permissioned::removeDepositor, not allowed");
allowedDepositors[depositor] = false;
numberOfAllowedDepositors = numberOfAllowedDepositors.sub(1);
emit RemoveDepositor(depositor);
}
}
// File contracts/interfaces/IERC20.sol
pragma solidity ^0.7.0;
interface IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/YakERC20.sol
pragma solidity ^0.7.0;
// pragma experimental ABIEncoderV2;
abstract contract YakERC20 {
using SafeMath for uint256;
string public name = "Yield Yak";
string public symbol = "YRT";
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping (address => mapping (address => uint256)) internal allowances;
mapping (address => uint256) internal balances;
bytes32 public constant DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
bytes32 public constant VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor() {}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* It is recommended to use increaseAllowance and decreaseAllowance instead
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool) {
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool) {
address spender = msg.sender;
uint256 spenderAllowance = allowances[src][spender];
if (spender != src && spenderAllowance != uint256(-1)) {
uint256 newAllowance = spenderAllowance.sub(amount, "transferFrom: transfer amount exceeds allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Approval implementation
* @param owner The address of the account which owns tokens
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (2^256-1 means infinite)
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "_approve::owner zero address");
require(spender != address(0), "_approve::spender zero address");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Transfer implementation
* @param from The address of the account which owns tokens
* @param to The address of the account which is receiving tokens
* @param value The number of tokens that are being transferred
*/
function _transferTokens(address from, address to, uint256 value) internal {
require(to != address(0), "_transferTokens: cannot transfer to the zero address");
balances[from] = balances[from].sub(value, "_transferTokens: transfer exceeds from balance");
balances[to] = balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balances[to] = balances[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balances[from] = balances[from].sub(value, "_burn: burn amount exceeds from balance");
totalSupply = totalSupply.sub(value, "_burn: burn amount exceeds total supply");
emit Transfer(from, address(0), value);
}
/**
* @notice Triggers an approval from owner to spender
* @param owner The address to approve from
* @param spender The address to be approved
* @param value The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, "permit::expired");
bytes32 encodeData = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline));
_validateSignedData(owner, encodeData, v, r, s);
_approve(owner, spender, value);
}
/**
* @notice Recovers address from signed data and validates the signature
* @param signer Address that signed the data
* @param encodeData Data signed by the address
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function _validateSignedData(address signer, bytes32 encodeData, uint8 v, bytes32 r, bytes32 s) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
getDomainSeparator(),
encodeData
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
// Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages
require(recoveredAddress != address(0) && recoveredAddress == signer, "Arch::validateSig: invalid signature");
}
/**
* @notice EIP-712 Domain separator
* @return Separator
*/
function getDomainSeparator() public view returns (bytes32) {
return keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
VERSION_HASH,
_getChainId(),
address(this)
)
);
}
/**
* @notice Current id of the chain where this contract is deployed
* @return Chain id
*/
function _getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File contracts/YakStrategy.sol
pragma solidity ^0.7.0;
/**
* @notice YakStrategy should be inherited by new strategies
*/
abstract contract YakStrategy is YakERC20, Ownable, Permissioned {
using SafeMath for uint;
uint public totalDeposits;
IERC20 public depositToken;
IERC20 public rewardToken;
address public devAddr;
uint public MIN_TOKENS_TO_REINVEST;
uint public MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST;
bool public DEPOSITS_ENABLED;
uint public REINVEST_REWARD_BIPS;
uint public ADMIN_FEE_BIPS;
uint public DEV_FEE_BIPS;
uint constant internal BIPS_DIVISOR = 10000;
uint constant internal MAX_UINT = uint(-1);
event Deposit(address indexed account, uint amount);
event Withdraw(address indexed account, uint amount);
event Reinvest(uint newTotalDeposits, uint newTotalSupply);
event Recovered(address token, uint amount);
event UpdateAdminFee(uint oldValue, uint newValue);
event UpdateDevFee(uint oldValue, uint newValue);
event UpdateReinvestReward(uint oldValue, uint newValue);
event UpdateMinTokensToReinvest(uint oldValue, uint newValue);
event UpdateMaxTokensToDepositWithoutReinvest(uint oldValue, uint newValue);
event UpdateDevAddr(address oldValue, address newValue);
event DepositsEnabled(bool newValue);
/**
* @notice Throws if called by smart contract
*/
modifier onlyEOA() {
require(tx.origin == msg.sender, "YakStrategy::onlyEOA");
_;
}
/**
* @notice Approve tokens for use in Strategy
* @dev Should use modifier `onlyOwner` to avoid griefing
*/
function setAllowances() public virtual;
/**
* @notice Revoke token allowance
* @param token address
* @param spender address
*/
function revokeAllowance(address token, address spender) external onlyOwner {
require(IERC20(token).approve(spender, 0));
}
/**
* @notice Deposit and deploy deposits tokens to the strategy
* @dev Must mint receipt tokens to `msg.sender`
* @param amount deposit tokens
*/
function deposit(uint amount) external virtual;
/**
* @notice Deposit using Permit
* @dev Should revert for tokens without Permit
* @param amount Amount of tokens to deposit
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function depositWithPermit(uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external virtual;
/**
* @notice Deposit on behalf of another account
* @dev Must mint receipt tokens to `account`
* @param account address to receive receipt tokens
* @param amount deposit tokens
*/
function depositFor(address account, uint amount) external virtual;
/**
* @notice Redeem receipt tokens for deposit tokens
* @param amount receipt tokens
*/
function withdraw(uint amount) external virtual;
/**
* @notice Reinvest reward tokens into deposit tokens
*/
function reinvest() external virtual;
/**
* @notice Estimate reinvest reward
* @return reward tokens
*/
function estimateReinvestReward() external view returns (uint) {
uint unclaimedRewards = checkReward();
if (unclaimedRewards >= MIN_TOKENS_TO_REINVEST) {
return unclaimedRewards.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR);
}
return 0;
}
/**
* @notice Reward tokens avialable to strategy, including balance
* @return reward tokens
*/
function checkReward() public virtual view returns (uint);
/**
* @notice Estimated deposit token balance deployed by strategy, excluding balance
* @return deposit tokens
*/
function estimateDeployedBalance() external virtual view returns (uint);
/**
* @notice Rescue all available deployed deposit tokens back to Strategy
* @param minReturnAmountAccepted min deposit tokens to receive
* @param disableDeposits bool
*/
function rescueDeployedFunds(uint minReturnAmountAccepted, bool disableDeposits) external virtual;
/**
* @notice Calculate receipt tokens for a given amount of deposit tokens
* @dev If contract is empty, use 1:1 ratio
* @dev Could return zero shares for very low amounts of deposit tokens
* @param amount deposit tokens
* @return receipt tokens
*/
function getSharesForDepositTokens(uint amount) public view returns (uint) {
if (totalSupply.mul(totalDeposits) == 0) {
return amount;
}
return amount.mul(totalSupply).div(totalDeposits);
}
/**
* @notice Calculate deposit tokens for a given amount of receipt tokens
* @param amount receipt tokens
* @return deposit tokens
*/
function getDepositTokensForShares(uint amount) public view returns (uint) {
if (totalSupply.mul(totalDeposits) == 0) {
return 0;
}
return amount.mul(totalDeposits).div(totalSupply);
}
/**
* @notice Update reinvest min threshold
* @param newValue threshold
*/
function updateMinTokensToReinvest(uint newValue) public onlyOwner {
emit UpdateMinTokensToReinvest(MIN_TOKENS_TO_REINVEST, newValue);
MIN_TOKENS_TO_REINVEST = newValue;
}
/**
* @notice Update reinvest max threshold before a deposit
* @param newValue threshold
*/
function updateMaxTokensToDepositWithoutReinvest(uint newValue) public onlyOwner {
emit UpdateMaxTokensToDepositWithoutReinvest(MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST, newValue);
MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST = newValue;
}
/**
* @notice Update developer fee
* @param newValue fee in BIPS
*/
function updateDevFee(uint newValue) public onlyOwner {
require(newValue.add(ADMIN_FEE_BIPS).add(REINVEST_REWARD_BIPS) <= BIPS_DIVISOR);
emit UpdateDevFee(DEV_FEE_BIPS, newValue);
DEV_FEE_BIPS = newValue;
}
/**
* @notice Update admin fee
* @param newValue fee in BIPS
*/
function updateAdminFee(uint newValue) public onlyOwner {
require(newValue.add(DEV_FEE_BIPS).add(REINVEST_REWARD_BIPS) <= BIPS_DIVISOR);
emit UpdateAdminFee(ADMIN_FEE_BIPS, newValue);
ADMIN_FEE_BIPS = newValue;
}
/**
* @notice Update reinvest reward
* @param newValue fee in BIPS
*/
function updateReinvestReward(uint newValue) public onlyOwner {
require(newValue.add(ADMIN_FEE_BIPS).add(DEV_FEE_BIPS) <= BIPS_DIVISOR);
emit UpdateReinvestReward(REINVEST_REWARD_BIPS, newValue);
REINVEST_REWARD_BIPS = newValue;
}
/**
* @notice Enable/disable deposits
* @param newValue bool
*/
function updateDepositsEnabled(bool newValue) public onlyOwner {
require(DEPOSITS_ENABLED != newValue);
DEPOSITS_ENABLED = newValue;
emit DepositsEnabled(newValue);
}
/**
* @notice Update devAddr
* @param newValue address
*/
function updateDevAddr(address newValue) public {
require(msg.sender == devAddr);
emit UpdateDevAddr(devAddr, newValue);
devAddr = newValue;
}
/**
* @notice Recover ERC20 from contract
* @param tokenAddress token address
* @param tokenAmount amount to recover
*/
function recoverERC20(address tokenAddress, uint tokenAmount) external onlyOwner {
require(tokenAmount > 0);
require(IERC20(tokenAddress).transfer(msg.sender, tokenAmount));
emit Recovered(tokenAddress, tokenAmount);
}
/**
* @notice Recover AVAX from contract
* @param amount amount
*/
function recoverAVAX(uint amount) external onlyOwner {
require(amount > 0);
msg.sender.transfer(amount);
emit Recovered(address(0), amount);
}
}
// File contracts/interfaces/IStakingRewards.sol
pragma solidity ^0.7.0;
interface IStakingRewards {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function earned(address account) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function stake(uint256 amount) external;
function stakeWithPermit(uint256 amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
function withdraw(uint256 amount) external;
function getReward() external;
function exit() external;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event RewardsDurationUpdated(uint256 newDuration);
event Recovered(address token, uint256 amount);
}
// File contracts/interfaces/IPair.sol
pragma solidity ^0.7.0;
interface IPair is IERC20 {
function token0() external pure returns (address);
function token1() external pure returns (address);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function mint(address to) external returns (uint liquidity);
}
// File contracts/strategies/DexStrategyV5.sol
pragma solidity ^0.7.0;
/**
* @notice Pool2 strategy for StakingRewards
*/
contract DexStrategyV5 is YakStrategy {
using SafeMath for uint;
IStakingRewards public stakingContract;
IPair private swapPairToken0;
IPair private swapPairToken1;
bytes private constant zeroBytes = new bytes(0);
constructor (
string memory _name,
address _depositToken,
address _rewardToken,
address _stakingContract,
address _swapPairToken0,
address _swapPairToken1,
address _timelock,
uint _minTokensToReinvest,
uint _adminFeeBips,
uint _devFeeBips,
uint _reinvestRewardBips
) {
name = _name;
depositToken = IERC20(_depositToken);
rewardToken = IERC20(_rewardToken);
stakingContract = IStakingRewards(_stakingContract);
devAddr = msg.sender;
assignSwapPairSafely(_swapPairToken0, _swapPairToken1, _rewardToken);
setAllowances();
updateMinTokensToReinvest(_minTokensToReinvest);
updateAdminFee(_adminFeeBips);
updateDevFee(_devFeeBips);
updateReinvestReward(_reinvestRewardBips);
updateDepositsEnabled(true);
transferOwnership(_timelock);
emit Reinvest(0, 0);
}
/**
* @notice Initialization helper for Pair deposit tokens
* @dev Checks that selected Pairs are valid for trading reward tokens
* @dev Assigns values to swapPairToken0 and swapPairToken1
*/
function assignSwapPairSafely(address _swapPairToken0, address _swapPairToken1, address _rewardToken) private {
if (_rewardToken != IPair(address(depositToken)).token0() && _rewardToken != IPair(address(depositToken)).token1()) {
// deployment checks for non-pool2
require(_swapPairToken0 > address(0), "Swap pair 0 is necessary but not supplied");
require(_swapPairToken1 > address(0), "Swap pair 1 is necessary but not supplied");
swapPairToken0 = IPair(_swapPairToken0);
swapPairToken1 = IPair(_swapPairToken1);
require(swapPairToken0.token0() == _rewardToken || swapPairToken0.token1() == _rewardToken, "Swap pair supplied does not have the reward token as one of it's pair");
require(
swapPairToken0.token0() == IPair(address(depositToken)).token0() || swapPairToken0.token1() == IPair(address(depositToken)).token0(),
"Swap pair 0 supplied does not match the pair in question"
);
require(
swapPairToken1.token0() == IPair(address(depositToken)).token1() || swapPairToken1.token1() == IPair(address(depositToken)).token1(),
"Swap pair 1 supplied does not match the pair in question"
);
} else if (_rewardToken == IPair(address(depositToken)).token0()) {
swapPairToken1 = IPair(address(depositToken));
} else if (_rewardToken == IPair(address(depositToken)).token1()) {
swapPairToken0 = IPair(address(depositToken));
}
}
function setAllowances() public override onlyOwner {
depositToken.approve(address(stakingContract), MAX_UINT);
}
function deposit(uint amount) external override {
_deposit(msg.sender, amount);
}
function depositWithPermit(uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {
depositToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_deposit(msg.sender, amount);
}
function depositFor(address account, uint amount) external override {
_deposit(account, amount);
}
function _deposit(address account, uint amount) private onlyAllowedDeposits {
require(DEPOSITS_ENABLED == true, "DexStrategyV5::_deposit");
if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) {
uint unclaimedRewards = checkReward();
if (unclaimedRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) {
_reinvest(unclaimedRewards);
}
}
require(depositToken.transferFrom(msg.sender, address(this), amount));
_stakeDepositTokens(amount);
_mint(account, getSharesForDepositTokens(amount));
totalDeposits = totalDeposits.add(amount);
emit Deposit(account, amount);
}
function withdraw(uint amount) external override {
uint depositTokenAmount = getDepositTokensForShares(amount);
if (depositTokenAmount > 0) {
_withdrawDepositTokens(depositTokenAmount);
_safeTransfer(address(depositToken), msg.sender, depositTokenAmount);
_burn(msg.sender, amount);
totalDeposits = totalDeposits.sub(depositTokenAmount);
emit Withdraw(msg.sender, depositTokenAmount);
}
}
function _withdrawDepositTokens(uint amount) private {
require(amount > 0, "DexStrategyV5::_withdrawDepositTokens");
stakingContract.withdraw(amount);
}
function reinvest() external override onlyEOA {
uint unclaimedRewards = checkReward();
require(unclaimedRewards >= MIN_TOKENS_TO_REINVEST, "DexStrategyV5::reinvest");
_reinvest(unclaimedRewards);
}
/**
* @notice Reinvest rewards from staking contract to deposit tokens
* @dev Reverts if the expected amount of tokens are not returned from `stakingContract`
* @param amount deposit tokens to reinvest
*/
function _reinvest(uint amount) private {
stakingContract.getReward();
uint devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR);
if (devFee > 0) {
_safeTransfer(address(rewardToken), devAddr, devFee);
}
uint adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR);
if (adminFee > 0) {
_safeTransfer(address(rewardToken), owner(), adminFee);
}
uint reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR);
if (reinvestFee > 0) {
_safeTransfer(address(rewardToken), msg.sender, reinvestFee);
}