-
Notifications
You must be signed in to change notification settings - Fork 47
/
FourYearVestingLogic.sol
357 lines (323 loc) · 14.6 KB
/
FourYearVestingLogic.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
pragma solidity ^0.5.17;
pragma experimental ABIEncoderV2;
import "./IFourYearVesting.sol";
import "../../ApprovalReceiver.sol";
import "./FourYearVestingStorage.sol";
import "../../../openzeppelin/SafeMath.sol";
/**
* @title Four Year Vesting Logic contract.
* @notice Staking, delegating and withdrawal functionality.
* @dev Deployed by FourYearVestingFactory contract.
* */
contract FourYearVestingLogic is IFourYearVesting, FourYearVestingStorage, ApprovalReceiver {
using SafeMath for uint256;
/* Events */
event TokensStaked(address indexed caller, uint256 amount);
event VotesDelegated(address indexed caller, address delegatee);
event TokensWithdrawn(address indexed caller, address receiver);
event DividendsCollected(
address indexed caller,
address loanPoolToken,
address receiver,
uint32 maxCheckpoints
);
event MigratedToNewStakingContract(address indexed caller, address newStakingContract);
event TokenOwnerChanged(address indexed newOwner, address indexed oldOwner);
/* Modifiers */
/**
* @dev Throws if called by any account other than the token owner or the contract owner.
*/
modifier onlyOwners() {
require(msg.sender == tokenOwner || isOwner(), "unauthorized");
_;
}
/**
* @dev Throws if called by any account other than the token owner.
*/
modifier onlyTokenOwner() {
require(msg.sender == tokenOwner, "unauthorized");
_;
}
/* Functions */
/**
* @notice Sets the max interval.
* @param _interval Max interval for which tokens scheduled shall be staked.
* */
function setMaxInterval(uint256 _interval) external onlyOwner {
require(_interval.mod(FOUR_WEEKS) == 0, "invalid interval");
maxInterval = _interval;
}
/**
* @notice Stakes tokens according to the vesting schedule.
* @param _amount The amount of tokens to stake.
* @param _restartStakeSchedule The time from which staking schedule restarts.
* The issue is that we can only stake tokens for a max duration. Thus, we need to restart
* from the lastSchedule.
* @return lastSchedule The max duration for which tokens were staked.
* @return remainingAmount The amount outstanding - to be staked.
* */
function stakeTokens(
uint256 _amount,
uint256 _restartStakeSchedule
) external returns (uint256 lastSchedule, uint256 remainingAmount) {
(lastSchedule, remainingAmount) = _stakeTokens(msg.sender, _amount, _restartStakeSchedule);
}
/**
* @notice Stakes tokens according to the vesting schedule.
* @dev This function will be invoked from receiveApproval.
* @dev SOV.approveAndCall -> this.receiveApproval -> this.stakeTokensWithApproval
* @param _sender The sender of SOV.approveAndCall
* @param _amount The amount of tokens to stake.
* @param _restartStakeSchedule The time from which staking schedule restarts.
* The issue is that we can only stake tokens for a max duration. Thus, we need to restart
* from the lastSchedule.
* @return lastSchedule The max duration for which tokens were staked.
* @return remainingAmount The amount outstanding - to be staked.
* */
function stakeTokensWithApproval(
address _sender,
uint256 _amount,
uint256 _restartStakeSchedule
) external onlyThisContract returns (uint256 lastSchedule, uint256 remainingAmount) {
(lastSchedule, remainingAmount) = _stakeTokens(_sender, _amount, _restartStakeSchedule);
}
/**
* @notice Delegate votes from `msg.sender` which are locked until lockDate
* to `delegatee`.
* @param _delegatee The address to delegate votes to.
* */
function delegate(address _delegatee) external onlyTokenOwner {
require(_delegatee != address(0), "delegatee address invalid");
uint256 stakingEndDate = endDate;
/// @dev Withdraw for each unlocked position.
/// @dev Don't change FOUR_WEEKS to TWO_WEEKS, a lot of vestings already deployed with FOUR_WEEKS
/// workaround found, but it doesn't work with TWO_WEEKS
for (uint256 i = startDate.add(cliff); i <= stakingEndDate; i += FOUR_WEEKS) {
staking.delegate(_delegatee, i);
}
emit VotesDelegated(msg.sender, _delegatee);
}
/**
* @notice Withdraws unlocked tokens from the staking contract and
* forwards them to an address specified by the token owner.
* @param receiver The receiving address.
* */
function withdrawTokens(address receiver) external onlyTokenOwner {
_withdrawTokens(receiver, false);
}
/**
* @notice Collect dividends from fee sharing proxy.
* @param _loanPoolToken The loan pool token address.
* @param _maxCheckpoints Maximum number of checkpoints to be processed.
* @param _receiver The receiver of tokens or msg.sender
* */
function collectDividends(
address _loanPoolToken,
uint32 _maxCheckpoints,
address _receiver
) external onlyTokenOwner {
require(_receiver != address(0), "receiver address invalid");
/// @dev Invokes the fee sharing proxy.
feeSharingCollector.withdraw(_loanPoolToken, _maxCheckpoints, _receiver);
emit DividendsCollected(msg.sender, _loanPoolToken, _receiver, _maxCheckpoints);
}
/**
* @notice Change token owner - only vesting owner is allowed to change.
* @dev Modifies token owner. This must be followed by approval
* from token owner.
* @param _newTokenOwner Address of new token owner.
* */
function changeTokenOwner(address _newTokenOwner) public onlyOwner {
require(_newTokenOwner != address(0), "invalid new token owner address");
require(_newTokenOwner != tokenOwner, "same owner not allowed");
newTokenOwner = _newTokenOwner;
}
/**
* @notice Approve token owner change - only token Owner.
* @dev Token owner can only be modified
* when both vesting owner and token owner have approved. This
* function ascertains the approval of token owner.
* */
function approveOwnershipTransfer() public onlyTokenOwner {
require(newTokenOwner != address(0), "invalid address");
tokenOwner = newTokenOwner;
newTokenOwner = address(0);
emit TokenOwnerChanged(tokenOwner, msg.sender);
}
/**
* @notice Set address of the implementation - only Token Owner.
* @dev This function sets the new implementation address.
* It must also be approved by the Vesting owner.
* @param _newImplementation Address of the new implementation.
* */
function setImpl(address _newImplementation) public onlyTokenOwner {
require(_newImplementation != address(0), "invalid new implementation address");
newImplementation = _newImplementation;
}
/**
* @notice Allows the owners to migrate the positions
* to a new staking contract.
* */
function migrateToNewStakingContract() external onlyOwners {
staking.migrateToNewStakingContract();
staking = IStaking(staking.newStakingContract());
emit MigratedToNewStakingContract(msg.sender, address(staking));
}
/**
* @notice Extends stakes(unlocked till timeDuration) for four year vesting contracts.
* @dev Tokens are vested for 4 years. Since the max staking
* period is 3 years and the tokens are unlocked only after the first year(timeDuration) is
* passed, hence, we usually extend the duration of staking for all unlocked tokens for the first
* year by 3 years. In some cases, the timeDuration can differ.
* */
function extendStaking() external {
uint256 timeDuration = startDate.add(extendDurationFor);
uint256[] memory dates;
uint96[] memory stakes;
(dates, stakes) = staking.getStakes(address(this));
for (uint256 i = 0; i < dates.length; i++) {
if ((dates[i] < block.timestamp) && (dates[i] <= timeDuration) && (stakes[i] > 0)) {
staking.extendStakingDuration(dates[i], dates[i].add(156 weeks));
endDate = dates[i].add(156 weeks);
} else {
break;
}
}
}
/**
* @notice Stakes tokens according to the vesting schedule. Low level function.
* @dev Once here the allowance of tokens is taken for granted.
* @param _sender The sender of tokens to stake.
* @param _amount The amount of tokens to stake.
* @param _restartStakeSchedule The time from which staking schedule restarts.
* The issue is that we can only stake tokens for a max duration. Thus, we need to restart
* from the lastSchedule.
* @return lastSchedule The max duration for which tokens were staked.
* @return remainingAmount The amount outstanding - to be staked.
* */
function _stakeTokens(
address _sender,
uint256 _amount,
uint256 _restartStakeSchedule
) internal returns (uint256 lastSchedule, uint256 remainingAmount) {
// Creating a new staking schedule for the same vesting contract is disallowed unlike normal vesting
require(
(startDate == 0) ||
(startDate > 0 && remainingStakeAmount > 0 && _restartStakeSchedule > 0),
"create new vesting address"
);
uint256 restartDate;
uint256 relativeAmount;
// Calling the _stakeTokens function first time for the vesting contract
// Runs for maxInterval only (consider maxInterval = 18 * 4 = 72 weeks)
if (startDate == 0 && _restartStakeSchedule == 0) {
startDate = staking.timestampToLockDate(block.timestamp); // Set only once
durationLeft = duration; // We do not touch duration and cliff as they are used throughout
cliffAdded = cliff; // Hence, durationLeft and cliffAdded is created
}
// Calling the _stakeTokens second/third time - we start from the end of previous interval
// and the remaining amount(amount left after tokens are staked in the previous interval)
if (_restartStakeSchedule > 0) {
require(
_restartStakeSchedule == lastStakingSchedule && _amount == remainingStakeAmount,
"invalid params"
);
restartDate = _restartStakeSchedule;
} else {
restartDate = startDate;
}
// Runs only once when the _stakeTokens is called for the first time
if (endDate == 0) {
endDate = staking.timestampToLockDate(block.timestamp.add(duration));
}
uint256 addedMaxInterval = restartDate.add(maxInterval); // run for maxInterval
if (addedMaxInterval < endDate) {
// Runs for max interval
lastStakingSchedule = addedMaxInterval;
relativeAmount = (_amount.mul(maxInterval)).div(durationLeft); // (_amount * 18) / 39
durationLeft = durationLeft.sub(maxInterval); // durationLeft - 18 periods(72 weeks)
remainingStakeAmount = _amount.sub(relativeAmount); // Amount left to be staked in subsequent intervals
} else {
// Normal run
lastStakingSchedule = endDate; // if staking intervals left < 18 periods(72 weeks)
remainingStakeAmount = 0;
durationLeft = 0;
relativeAmount = _amount; // Stake all amount left
}
/// @dev Transfer the tokens to this contract.
bool success = SOV.transferFrom(_sender, address(this), relativeAmount);
require(success, "transfer failed");
/// @dev Allow the staking contract to access them.
SOV.approve(address(staking), relativeAmount);
staking.stakesBySchedule(
relativeAmount,
cliffAdded,
duration.sub(durationLeft),
FOUR_WEEKS,
address(this),
tokenOwner
);
if (durationLeft == 0) {
// All tokens staked
cliffAdded = 0;
} else {
cliffAdded = cliffAdded.add(maxInterval); // Add cliff to the end of previous maxInterval
}
emit TokensStaked(_sender, relativeAmount);
return (lastStakingSchedule, remainingStakeAmount);
}
/**
* @notice Withdraws tokens from the staking contract and forwards them
* to an address specified by the token owner. Low level function.
* @dev Once here the caller permission is taken for granted.
* @param receiver The receiving address.
* @param isGovernance Whether all tokens (true)
* or just unlocked tokens (false).
* */
function _withdrawTokens(address receiver, bool isGovernance) internal {
require(receiver != address(0), "receiver address invalid");
uint96 stake;
/// @dev Usually we just need to iterate over the possible dates until now.
uint256 end;
/// @dev In the unlikely case that all tokens have been unlocked early,
/// allow to withdraw all of them.
if (staking.allUnlocked() || isGovernance) {
end = endDate;
} else {
end = block.timestamp;
}
/// @dev Withdraw for each unlocked position.
/// @dev Don't change FOUR_WEEKS to TWO_WEEKS, a lot of vestings already deployed with FOUR_WEEKS
/// workaround found, but it doesn't work with TWO_WEEKS
/// @dev For four year vesting, withdrawal of stakes for the first year is not allowed. These
/// stakes are extended for three years. In some cases the withdrawal may be allowed at a different
/// time and hence we use extendDurationFor.
for (uint256 i = startDate.add(extendDurationFor); i <= end; i += FOUR_WEEKS) {
/// @dev Read amount to withdraw.
stake = staking.getPriorUserStakeByDate(address(this), i, block.number.sub(1));
/// @dev Withdraw if > 0
if (stake > 0) {
staking.withdraw(stake, i, receiver);
}
}
emit TokensWithdrawn(msg.sender, receiver);
}
/**
* @notice Overrides default ApprovalReceiver._getToken function to
* register SOV token on this contract.
* @return The address of SOV token.
* */
function _getToken() internal view returns (address) {
return address(SOV);
}
/**
* @notice Overrides default ApprovalReceiver._getSelectors function to
* register stakeTokensWithApproval selector on this contract.
* @return The array of registered selectors on this contract.
* */
function _getSelectors() internal pure returns (bytes4[] memory) {
bytes4[] memory selectors = new bytes4[](1);
selectors[0] = this.stakeTokensWithApproval.selector;
return selectors;
}
}