-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathVestingToken.sol
261 lines (198 loc) · 8.06 KB
/
VestingToken.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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Initializable} from "@oz-upgradeable/contracts/proxy/utils/Initializable.sol";
import {ERC20Upgradeable} from "@oz-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol";
import {Vesting, Schedule} from "./IVestingToken.sol";
/**
* @title Контракт share-токена (вестинг-токен)
* @notice Отвечает за логику блокировки/разблокировки средств
* @dev Код предоставлен исключительно в ознакомительных целях и не протестирован
* Из контракта убрано все лишнее, включая некоторые проверки, геттеры/сеттеры и события
*/
contract VestingToken is Initializable, ERC20Upgradeable {
using SafeERC20 for IERC20;
uint256 private constant BASIS_POINTS = 10_000;
address private _minter;
address private _vestingManager;
IERC20 private _baseToken;
Vesting private _vesting;
uint256 private _initialLockedSupply;
constructor() {
_disableInitializers();
}
mapping(address => uint256) private _initialLocked;
mapping(address => uint256) private _released;
// region - Errors
/////////////////////
// Errors //
/////////////////////
error OnlyMinter();
error OnlyVestingManager();
error NotEnoughTokensToClaim();
error StartTimeAlreadyElapsed();
error CliffBeforeStartTime();
error IncorrectSchedulePortions();
error IncorrectScheduleTime(uint256 incorrectTime);
error TransfersNotAllowed();
error MintingAfterCliffIsForbidden();
// endregion
// region - Modifiers
modifier onlyMinter() {
if (msg.sender != _minter) {
revert OnlyMinter();
}
_;
}
modifier onlyVestingManager() {
if (msg.sender != _vestingManager) {
revert OnlyVestingManager();
}
_;
}
// endregion
// region - Initialize
/**
* @notice Так как это прокси, нужно выполнить инициализацию
* @dev Создается и инициализируется только контрактом VestingManager
*/
function initialize(string calldata name, string calldata symbol, address minter, address baseToken)
public
initializer
{
__ERC20_init(name, symbol);
_minter = minter;
_baseToken = IERC20(baseToken);
_vestingManager = msg.sender;
}
// endregion
// region - Set vesting schedule
/**
* @notice Установка расписания также выполняется контрактом VestingManager
* @dev Здесь важно проверить что расписание было передано корректное
*/
function setVestingSchedule(uint256 startTime, uint256 cliff, Schedule[] calldata schedule)
external
onlyVestingManager
{
uint256 scheduleLength = schedule.length;
_checkVestingSchedule(startTime, cliff, schedule, scheduleLength);
_vesting.startTime = startTime;
_vesting.cliff = cliff;
for (uint256 i = 0; i < scheduleLength; i++) {
_vesting.schedule.push(schedule[i]);
}
}
function _checkVestingSchedule(
uint256 startTime,
uint256 cliff,
Schedule[] calldata schedule,
uint256 scheduleLength
) private view {
if (startTime < block.timestamp) {
revert StartTimeAlreadyElapsed();
}
if (startTime > cliff) {
revert CliffBeforeStartTime();
}
uint256 totalPercent;
for (uint256 i = 0; i < scheduleLength; i++) {
totalPercent += schedule[i].portion;
bool isEndTimeOutOfOrder = (i != 0) && schedule[i - 1].endTime >= schedule[i].endTime;
if (cliff >= schedule[i].endTime || isEndTimeOutOfOrder) {
revert IncorrectScheduleTime(schedule[i].endTime);
}
}
if (totalPercent != BASIS_POINTS) {
revert IncorrectSchedulePortions();
}
}
// endregion
// region - Mint
/**
* @notice Списываем токен который будем блокировать и минтим share-токен
*/
function mint(address to, uint256 amount) external onlyMinter {
if (block.timestamp >= _vesting.cliff) {
revert MintingAfterCliffIsForbidden();
}
_baseToken.safeTransferFrom(msg.sender, address(this), amount);
_mint(to, amount);
_initialLocked[to] += amount;
_initialLockedSupply += amount;
}
// endregion
// region - Claim
/**
* @notice Сжигаем share-токен и переводим бенефициару разблокированные базовые токены
*/
function claim() external {
uint256 releasable = availableBalanceOf(msg.sender);
if (releasable == 0) {
revert NotEnoughTokensToClaim();
}
_released[msg.sender] += releasable;
_burn(msg.sender, releasable);
_baseToken.safeTransfer(msg.sender, releasable);
}
// endregion
// region - Vesting getters
function getVestingSchedule() public view returns (Vesting memory) {
return _vesting;
}
function unlockedSupply() external view returns (uint256) {
return _totalUnlocked();
}
function lockedSupply() external view returns (uint256) {
return _initialLockedSupply - _totalUnlocked();
}
function availableBalanceOf(address account) public view returns (uint256 releasable) {
releasable = _unlockedOf(account) - _released[account];
}
// endregion
// region - Private functions
function _unlockedOf(address account) private view returns (uint256) {
return _computeUnlocked(_initialLocked[account], block.timestamp);
}
function _totalUnlocked() private view returns (uint256) {
return _computeUnlocked(_initialLockedSupply, block.timestamp);
}
/**
* @notice Основная функция для расчета разблокированных токенов
* @dev Проверяется сколько прошло полных периодов и сколько времени прошло
* после последнего полного периода.
*/
function _computeUnlocked(uint256 lockedTokens, uint256 time) private view returns (uint256 unlockedTokens) {
if (time < _vesting.cliff) {
return 0;
}
uint256 currentPeriodStart = _vesting.cliff;
Schedule[] memory schedule = _vesting.schedule;
uint256 scheduleLength = schedule.length;
for (uint256 i = 0; i < scheduleLength; i++) {
Schedule memory currentPeriod = schedule[i];
uint256 currentPeriodEnd = currentPeriod.endTime;
uint256 currentPeriodPortion = currentPeriod.portion;
if (time < currentPeriodEnd) {
uint256 elapsedPeriodTime = time - currentPeriodStart;
uint256 periodDuration = currentPeriodEnd - currentPeriodStart;
unlockedTokens +=
(lockedTokens * elapsedPeriodTime * currentPeriodPortion) / (periodDuration * BASIS_POINTS);
break;
} else {
unlockedTokens += (lockedTokens * currentPeriodPortion) / BASIS_POINTS;
currentPeriodStart = currentPeriodEnd;
}
}
}
/**
* @notice Трансферить токены нельзя, только минтить и сжигать
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override {
super._beforeTokenTransfer(from, to, amount);
if (from != address(0) && to != address(0)) {
revert TransfersNotAllowed();
}
}
// endregion
}