-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTokenDistributor.sol
396 lines (308 loc) · 14.3 KB
/
TokenDistributor.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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ILooksRareToken} from "../interfaces/ILooksRareToken.sol";
/**
* @title TokenDistributor
* @notice It handles the distribution of LOOKS token.
* It auto-adjusts block rewards over a set number of periods.
*/
contract TokenDistributor is ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeERC20 for ILooksRareToken;
struct StakingPeriod {
uint256 rewardPerBlockForStaking;
uint256 rewardPerBlockForOthers;
uint256 periodLengthInBlock;
}
struct UserInfo {
uint256 amount; // Amount of staked tokens provided by user
uint256 rewardDebt; // Reward debt
}
// Precision factor for calculating rewards
uint256 public constant PRECISION_FACTOR = 10**12;
ILooksRareToken public immutable looksRareToken;
address public immutable tokenSplitter;
// Number of reward periods
uint256 public immutable NUMBER_PERIODS;
// Block number when rewards start
uint256 public immutable START_BLOCK;
// Accumulated tokens per share
uint256 public accTokenPerShare;
// Current phase for rewards
uint256 public currentPhase;
// Block number when rewards end
uint256 public endBlock;
// Block number of the last update
uint256 public lastRewardBlock;
// Tokens distributed per block for other purposes (team + treasury + trading rewards)
uint256 public rewardPerBlockForOthers;
// Tokens distributed per block for staking
uint256 public rewardPerBlockForStaking;
// Total amount staked
uint256 public totalAmountStaked;
mapping(uint256 => StakingPeriod) public stakingPeriod;
mapping(address => UserInfo) public userInfo;
event Compound(address indexed user, uint256 harvestedAmount);
event Deposit(address indexed user, uint256 amount, uint256 harvestedAmount);
event NewRewardsPerBlock(
uint256 indexed currentPhase,
uint256 startBlock,
uint256 rewardPerBlockForStaking,
uint256 rewardPerBlockForOthers
);
event Withdraw(address indexed user, uint256 amount, uint256 harvestedAmount);
/**
* @notice Constructor
* @param _looksRareToken LOOKS token address
* @param _tokenSplitter token splitter contract address (for team and trading rewards)
* @param _startBlock start block for reward program
* @param _rewardsPerBlockForStaking array of rewards per block for staking
* @param _rewardsPerBlockForOthers array of rewards per block for other purposes (team + treasury + trading rewards)
* @param _periodLengthesInBlocks array of period lengthes
* @param _numberPeriods number of periods with different rewards/lengthes (e.g., if 3 changes --> 4 periods)
*/
constructor(
address _looksRareToken,
address _tokenSplitter,
uint256 _startBlock,
uint256[] memory _rewardsPerBlockForStaking,
uint256[] memory _rewardsPerBlockForOthers,
uint256[] memory _periodLengthesInBlocks,
uint256 _numberPeriods
) {
require(
(_periodLengthesInBlocks.length == _numberPeriods) &&
(_rewardsPerBlockForStaking.length == _numberPeriods) &&
(_rewardsPerBlockForStaking.length == _numberPeriods),
"Distributor: Lengthes must match numberPeriods"
);
// 1. Operational checks for supply
uint256 nonCirculatingSupply = ILooksRareToken(_looksRareToken).SUPPLY_CAP() -
ILooksRareToken(_looksRareToken).totalSupply();
uint256 amountTokensToBeMinted;
for (uint256 i = 0; i < _numberPeriods; i++) {
amountTokensToBeMinted +=
(_rewardsPerBlockForStaking[i] * _periodLengthesInBlocks[i]) +
(_rewardsPerBlockForOthers[i] * _periodLengthesInBlocks[i]);
stakingPeriod[i] = StakingPeriod({
rewardPerBlockForStaking: _rewardsPerBlockForStaking[i],
rewardPerBlockForOthers: _rewardsPerBlockForOthers[i],
periodLengthInBlock: _periodLengthesInBlocks[i]
});
}
require(amountTokensToBeMinted == nonCirculatingSupply, "Distributor: Wrong reward parameters");
// 2. Store values
looksRareToken = ILooksRareToken(_looksRareToken);
tokenSplitter = _tokenSplitter;
rewardPerBlockForStaking = _rewardsPerBlockForStaking[0];
rewardPerBlockForOthers = _rewardsPerBlockForOthers[0];
START_BLOCK = _startBlock;
endBlock = _startBlock + _periodLengthesInBlocks[0];
NUMBER_PERIODS = _numberPeriods;
// Set the lastRewardBlock as the startBlock
lastRewardBlock = _startBlock;
}
/**
* @notice Deposit staked tokens and compounds pending rewards
* @param amount amount to deposit (in LOOKS)
*/
function deposit(uint256 amount) external nonReentrant {
require(amount > 0, "Deposit: Amount must be > 0");
// Update pool information
_updatePool();
// Transfer LOOKS tokens to this contract
looksRareToken.safeTransferFrom(msg.sender, address(this), amount);
uint256 pendingRewards;
// If not new deposit, calculate pending rewards (for auto-compounding)
if (userInfo[msg.sender].amount > 0) {
pendingRewards =
((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) -
userInfo[msg.sender].rewardDebt;
}
// Adjust user information
userInfo[msg.sender].amount += (amount + pendingRewards);
userInfo[msg.sender].rewardDebt = (userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR;
// Increase totalAmountStaked
totalAmountStaked += (amount + pendingRewards);
emit Deposit(msg.sender, amount, pendingRewards);
}
/**
* @notice Compound based on pending rewards
*/
function harvestAndCompound() external nonReentrant {
// Update pool information
_updatePool();
// Calculate pending rewards
uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) -
userInfo[msg.sender].rewardDebt;
// Return if no pending rewards
if (pendingRewards == 0) {
// It doesn't throw revertion (to help with the fee-sharing auto-compounding contract)
return;
}
// Adjust user amount for pending rewards
userInfo[msg.sender].amount += pendingRewards;
// Adjust totalAmountStaked
totalAmountStaked += pendingRewards;
// Recalculate reward debt based on new user amount
userInfo[msg.sender].rewardDebt = (userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR;
emit Compound(msg.sender, pendingRewards);
}
/**
* @notice Update pool rewards
*/
function updatePool() external nonReentrant {
_updatePool();
}
/**
* @notice Withdraw staked tokens and compound pending rewards
* @param amount amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(
(userInfo[msg.sender].amount >= amount) && (amount > 0),
"Withdraw: Amount must be > 0 or lower than user balance"
);
// Update pool
_updatePool();
// Calculate pending rewards
uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) -
userInfo[msg.sender].rewardDebt;
// Adjust user information
userInfo[msg.sender].amount = userInfo[msg.sender].amount + pendingRewards - amount;
userInfo[msg.sender].rewardDebt = (userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR;
// Adjust total amount staked
totalAmountStaked = totalAmountStaked + pendingRewards - amount;
// Transfer LOOKS tokens to the sender
looksRareToken.safeTransfer(msg.sender, amount);
emit Withdraw(msg.sender, amount, pendingRewards);
}
/**
* @notice Withdraw all staked tokens and collect tokens
*/
function withdrawAll() external nonReentrant {
require(userInfo[msg.sender].amount > 0, "Withdraw: Amount must be > 0");
// Update pool
_updatePool();
// Calculate pending rewards and amount to transfer (to the sender)
uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) -
userInfo[msg.sender].rewardDebt;
uint256 amountToTransfer = userInfo[msg.sender].amount + pendingRewards;
// Adjust total amount staked
totalAmountStaked = totalAmountStaked - userInfo[msg.sender].amount;
// Adjust user information
userInfo[msg.sender].amount = 0;
userInfo[msg.sender].rewardDebt = 0;
// Transfer LOOKS tokens to the sender
looksRareToken.safeTransfer(msg.sender, amountToTransfer);
emit Withdraw(msg.sender, amountToTransfer, pendingRewards);
}
/**
* @notice Calculate pending rewards for a user
* @param user address of the user
* @return Pending rewards
*/
function calculatePendingRewards(address user) external view returns (uint256) {
if ((block.number > lastRewardBlock) && (totalAmountStaked != 0)) {
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 tokenRewardForStaking = multiplier * rewardPerBlockForStaking;
uint256 adjustedEndBlock = endBlock;
uint256 adjustedCurrentPhase = currentPhase;
// Check whether to adjust multipliers and reward per block
while ((block.number > adjustedEndBlock) && (adjustedCurrentPhase < (NUMBER_PERIODS - 1))) {
// Update current phase
adjustedCurrentPhase++;
// Update rewards per block
uint256 adjustedRewardPerBlockForStaking = stakingPeriod[adjustedCurrentPhase].rewardPerBlockForStaking;
// Calculate adjusted block number
uint256 previousEndBlock = adjustedEndBlock;
// Update end block
adjustedEndBlock = previousEndBlock + stakingPeriod[adjustedCurrentPhase].periodLengthInBlock;
// Calculate new multiplier
uint256 newMultiplier = (block.number <= adjustedEndBlock)
? (block.number - previousEndBlock)
: stakingPeriod[adjustedCurrentPhase].periodLengthInBlock;
// Adjust token rewards for staking
tokenRewardForStaking += (newMultiplier * adjustedRewardPerBlockForStaking);
}
uint256 adjustedTokenPerShare = accTokenPerShare +
(tokenRewardForStaking * PRECISION_FACTOR) /
totalAmountStaked;
return (userInfo[user].amount * adjustedTokenPerShare) / PRECISION_FACTOR - userInfo[user].rewardDebt;
} else {
return (userInfo[user].amount * accTokenPerShare) / PRECISION_FACTOR - userInfo[user].rewardDebt;
}
}
/**
* @notice Update reward variables of the pool
*/
function _updatePool() internal {
if (block.number <= lastRewardBlock) {
return;
}
if (totalAmountStaked == 0) {
lastRewardBlock = block.number;
return;
}
// Calculate multiplier
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
// Calculate rewards for staking and others
uint256 tokenRewardForStaking = multiplier * rewardPerBlockForStaking;
uint256 tokenRewardForOthers = multiplier * rewardPerBlockForOthers;
// Check whether to adjust multipliers and reward per block
while ((block.number > endBlock) && (currentPhase < (NUMBER_PERIODS - 1))) {
// Update rewards per block
_updateRewardsPerBlock(endBlock);
uint256 previousEndBlock = endBlock;
// Adjust the end block
endBlock += stakingPeriod[currentPhase].periodLengthInBlock;
// Adjust multiplier to cover the missing periods with other lower inflation schedule
uint256 newMultiplier = _getMultiplier(previousEndBlock, block.number);
// Adjust token rewards
tokenRewardForStaking += (newMultiplier * rewardPerBlockForStaking);
tokenRewardForOthers += (newMultiplier * rewardPerBlockForOthers);
}
// Mint tokens only if token rewards for staking are not null
if (tokenRewardForStaking > 0) {
// It allows protection against potential issues to prevent funds from being locked
bool mintStatus = looksRareToken.mint(address(this), tokenRewardForStaking);
if (mintStatus) {
accTokenPerShare = accTokenPerShare + ((tokenRewardForStaking * PRECISION_FACTOR) / totalAmountStaked);
}
looksRareToken.mint(tokenSplitter, tokenRewardForOthers);
}
// Update last reward block only if it wasn't updated after or at the end block
if (lastRewardBlock <= endBlock) {
lastRewardBlock = block.number;
}
}
/**
* @notice Update rewards per block
* @dev Rewards are halved by 2 (for staking + others)
*/
function _updateRewardsPerBlock(uint256 _newStartBlock) internal {
// Update current phase
currentPhase++;
// Update rewards per block
rewardPerBlockForStaking = stakingPeriod[currentPhase].rewardPerBlockForStaking;
rewardPerBlockForOthers = stakingPeriod[currentPhase].rewardPerBlockForOthers;
emit NewRewardsPerBlock(currentPhase, _newStartBlock, rewardPerBlockForStaking, rewardPerBlockForOthers);
}
/**
* @notice Return reward multiplier over the given "from" to "to" block.
* @param from block to start calculating reward
* @param to block to finish calculating reward
* @return the multiplier for the period
*/
function _getMultiplier(uint256 from, uint256 to) internal view returns (uint256) {
if (to <= endBlock) {
return to - from;
} else if (from >= endBlock) {
return 0;
} else {
return endBlock - from;
}
}
}