-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDEED-Staking.sol
603 lines (482 loc) · 18.3 KB
/
DEED-Staking.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
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.6.0;
interface IERC20 {
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);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call{value:amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
_notEntered = true;
}
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
contract StakingTokenWrapper is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public stakingToken;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
constructor(address _stakingToken) internal {
stakingToken = IERC20(_stakingToken);
}
function totalSupply()
public
view
returns (uint256)
{
return _totalSupply;
}
function balanceOf(address _account)
public
view
returns (uint256)
{
return _balances[_account];
}
function _stake(address _beneficiary, uint256 _amount)
internal
nonReentrant
{
_totalSupply = _totalSupply.add(_amount);
_balances[_beneficiary] = _balances[_beneficiary].add(_amount);
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
}
function _withdraw(uint256 _amount)
internal
nonReentrant
{
_totalSupply = _totalSupply.sub(_amount);
_balances[msg.sender] = _balances[msg.sender].sub(_amount);
stakingToken.safeTransfer(msg.sender, _amount);
}
}
interface IRewardsDistributionRecipient {
// function notifyRewardAmount(uint256 reward) external;
function getRewardToken() external view returns (IERC20);
}
abstract contract RewardsDistributionRecipient is IRewardsDistributionRecipient {
// @abstract
// function notifyRewardAmount(uint256 reward) external;
function getRewardToken() external virtual override view returns (IERC20);
// This address has the ability to distribute the rewards
address public rewardsDistributor;
/** @dev Recipient is a module, governed by mStable governance */
constructor(address _rewardsDistributor)
internal
{
rewardsDistributor = _rewardsDistributor;
}
/**
* @dev Only the rewards distributor can notify about rewards
*/
modifier onlyRewardsDistributor() {
require(msg.sender == rewardsDistributor, "Caller is not reward distributor");
_;
}
}
library StableMath {
using SafeMath for uint256;
uint256 private constant FULL_SCALE = 1e18;
uint256 private constant RATIO_SCALE = 1e8;
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
function scaleInteger(uint256 x)
internal
pure
returns (uint256)
{
return x.mul(FULL_SCALE);
}
function mulTruncate(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return mulTruncateScale(x, y, FULL_SCALE);
}
function mulTruncateScale(uint256 x, uint256 y, uint256 scale)
internal
pure
returns (uint256)
{
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
function mulRatioTruncate(uint256 x, uint256 ratio)
internal
pure
returns (uint256 c)
{
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
function mulRatioTruncateCeil(uint256 x, uint256 ratio)
internal
pure
returns (uint256)
{
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x.mul(ratio);
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled.add(RATIO_SCALE.sub(1));
// return 100..00.999e8 / 1e8 = 1e18
return ceil.div(RATIO_SCALE);
}
function divRatioPrecisely(uint256 x, uint256 ratio)
internal
pure
returns (uint256 c)
{
// e.g. 1e14 * 1e8 = 1e22
uint256 y = x.mul(RATIO_SCALE);
// return 1e22 / 1e12 = 1e10
return y.div(ratio);
}
function min(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return x > y ? y : x;
}
function max(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return x > y ? x : y;
}
function clamp(uint256 x, uint256 upperBound)
internal
pure
returns (uint256)
{
return x > upperBound ? upperBound : x;
}
}
contract Staking is StakingTokenWrapper, RewardsDistributionRecipient {
using StableMath for uint256;
IERC20 public rewardsToken;
// uint256 public constant ONE_DAY = 86400; // in seconds
// uint256 public constant ONE_DAY = 60; // 1 mins in seconds
uint256 public minStakingAmount = 10*10**18;
uint256 public maxStakingAmount = 10000000*10**18;
uint256 public sixMonthRewardPercent = 5 * 1e18; // 5%
uint256 public twelveMonthRewardPercent = 10 * 1e18; // 10%
// Timestamps of staking duration
uint256 public constant SIX_MONTHS_DURATION = 180 days;
uint256 public constant TWELVE_MONTHS_DURATION = 360 days;
uint256 public stakingDuration = 0;
// Amount the user has staked
mapping(address => uint256) public userStakedTokens;
// Reward the user will get after staking period ends
mapping(address => uint256) public rewards;
// Rewards paid to user
mapping(address => uint256) public userRewardsPaid;
// Stake starting timestamp
mapping(address => uint256) public stakeStarted;
// Stake ending timestamp
mapping(address => uint256) public stakeEnded;
event Staked(address indexed user, uint256 amount, uint256 reward,uint256 time);
event Withdrawn(address indexed user, uint256 amount,uint256 time);
event RewardPaid(address indexed user, uint256 reward,uint256 time);
/***************************************
CONSTRUCTOR
****************************************/
constructor (
address _stakingToken,
address _rewardsToken,
address _rewardsDistributor
)
public
StakingTokenWrapper(_stakingToken)
RewardsDistributionRecipient(_rewardsDistributor)
{
rewardsToken = IERC20(_rewardsToken);
}
/***************************************
MODIFIERS
****************************************/
modifier isAccount(address _account) {
require(!Address.isContract(_account), "Only external owned accounts allowed");
_;
}
/***************************************
ACTIONS
****************************************/
function stake6m(address _beneficiary, uint256 _amount)
external
{
__stake(_beneficiary, _amount, SIX_MONTHS_DURATION);
}
function stake12m(address _beneficiary, uint256 _amount)
external
{
__stake(_beneficiary, _amount, TWELVE_MONTHS_DURATION);
}
function unstake()
external
{
require(block.timestamp >= stakeEnded[msg.sender], "Reward cannot be claimed before staking ends");
withdraw(balanceOf(msg.sender));
claimReward();
stakeStarted[msg.sender] = 0;
stakeEnded[msg.sender] = 0;
}
function __stake(address _beneficiary, uint256 _amount, uint256 _period)
internal
isAccount(_beneficiary)
{
require(
_amount <= maxStakingAmount &&
_amount >= minStakingAmount,
"Invalid staking amount"
);
require(
_period == SIX_MONTHS_DURATION ||
_period == TWELVE_MONTHS_DURATION,
"Invalid staking period"
);
super._stake(_beneficiary, _amount);
stakeStarted[_beneficiary] = block.timestamp;
userStakedTokens[_beneficiary] = userStakedTokens[_beneficiary].add(_amount);
uint256 __userAmount = userStakedTokens[_beneficiary];
// calculation is on the basis:
// reward = (monthPercentageInWei * stakedAmountInWei) / 1e20
// e.g: (2.5% * 1e18 * 100 * 1e18) / 1e20 = 2.5 * 1e18
uint256 _rewardAmount;
if (_period == SIX_MONTHS_DURATION) {
_rewardAmount = (sixMonthRewardPercent * __userAmount) / 1e20;
rewards[_beneficiary] += _rewardAmount;
stakeEnded[_beneficiary] = (block.timestamp).add(SIX_MONTHS_DURATION);
} else if (_period == TWELVE_MONTHS_DURATION) {
_rewardAmount = (twelveMonthRewardPercent * __userAmount) / 1e20;
rewards[_beneficiary] += _rewardAmount;
stakeEnded[_beneficiary] = (block.timestamp).add(TWELVE_MONTHS_DURATION);
} else {
revert("Error: duration not allowed!");
}
emit Staked(_beneficiary, _amount, _rewardAmount,now);
}
function withdraw(uint256 _amount)
internal
isAccount(msg.sender)
{
require(_amount > 0, "Cannot withdraw 0");
require(block.timestamp >= stakeEnded[msg.sender], "Reward cannot be claimed before staking ends");
userStakedTokens[msg.sender] = userStakedTokens[msg.sender].sub(_amount);
_withdraw(_amount);
emit Withdrawn(msg.sender, _amount,now);
}
function claimReward()
internal
isAccount(msg.sender)
{
require(block.timestamp >= stakeEnded[msg.sender], "Reward cannot be claimed before staking ends");
uint256 reward = rewards[msg.sender];
if (reward > 0) {
rewards[msg.sender] = 0;
rewardsToken.transfer(msg.sender, reward);
userRewardsPaid[msg.sender] = userRewardsPaid[msg.sender].add(reward);
emit RewardPaid(msg.sender, reward,now);
}
}
/***************************************
GETTERS
****************************************/
function getRewardToken()
external
override
view
returns (IERC20)
{
return rewardsToken;
}
function earned(address _account)
public
view
returns (uint256)
{
return rewards[_account];
}
function tokensStaked(address _account)
public
view
returns (uint256)
{
return userStakedTokens[_account];
}
/***************************************
ADMIN
****************************************/
function sendRewardTokens(uint256 _amount)
public
onlyRewardsDistributor
{
require(rewardsToken.transferFrom(msg.sender, address(this), _amount), "Transfering not approved!");
}
function withdrawRewardTokens(address receiver, uint256 _amount)
public
onlyRewardsDistributor
{
require(rewardsToken.transfer(receiver, _amount), "Not enough tokens on contract!");
}
function withdrawFarmTokens(address receiver, uint256 _amount)
public
onlyRewardsDistributor
{
require(stakingToken.transfer(receiver, _amount), "Not enough tokens on contract!");
}
}