-
Notifications
You must be signed in to change notification settings - Fork 196
/
UniswapV3Staker.sol
364 lines (310 loc) · 11.2 KB
/
UniswapV3Staker.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
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import './interfaces/IUniswapV3Staker.sol';
import './libraries/IncentiveHelper.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-core/contracts/interfaces/IERC20Minimal.sol';
import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol';
import '@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol';
import '@uniswap/v3-core/contracts/libraries/FixedPoint128.sol';
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/math/Math.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/utils/ReentrancyGuard.sol';
/**
@title Uniswap V3 canonical staking interface
*/
contract UniswapV3Staker is IUniswapV3Staker, IERC721Receiver, ReentrancyGuard {
struct Incentive {
uint128 totalRewardUnclaimed;
uint160 totalSecondsClaimedX128;
address rewardToken;
}
struct Deposit {
address owner;
uint32 numberOfStakes;
}
struct Stake {
uint160 secondsPerLiquidityInitialX128;
}
IUniswapV3Factory public immutable factory;
INonfungiblePositionManager public immutable nonfungiblePositionManager;
/// @dev bytes32 refers to the return value of IncentiveHelper.getIncentiveId
mapping(bytes32 => Incentive) public incentives;
/// @dev deposits[tokenId] => Deposit
mapping(uint256 => Deposit) public deposits;
/// @dev stakes[tokenId][incentiveHash] => Stake
mapping(uint256 => mapping(bytes32 => Stake)) public stakes;
/// @param _factory the Uniswap V3 factory
/// @param _nonfungiblePositionManager the NFT position manager contract address
constructor(address _factory, address _nonfungiblePositionManager) {
factory = IUniswapV3Factory(_factory);
nonfungiblePositionManager = INonfungiblePositionManager(
_nonfungiblePositionManager
);
}
/// @inheritdoc IUniswapV3Staker
function createIncentive(CreateIncentiveParams memory params)
external
override
{
require(
params.claimDeadline >= params.endTime,
'claimDeadline_not_gte_endTime'
);
require(params.endTime > params.startTime, 'endTime_not_gte_startTime');
bytes32 key =
IncentiveHelper.getIncentiveId(
msg.sender,
params.rewardToken,
params.pool,
params.startTime,
params.endTime,
params.claimDeadline
);
require(incentives[key].rewardToken == address(0), 'INCENTIVE_EXISTS');
require(params.rewardToken != address(0), 'INVALID_REWARD_ADDRESS');
require(params.totalReward > 0, 'INVALID_REWARD_AMOUNT');
require(
IERC20Minimal(params.rewardToken).transferFrom(
msg.sender,
address(this),
params.totalReward
),
'REWARD_TRANSFER_FAILED'
);
incentives[key] = Incentive(params.totalReward, 0, params.rewardToken);
emit IncentiveCreated(
params.rewardToken,
params.pool,
params.startTime,
params.endTime,
params.claimDeadline,
params.totalReward
);
}
/// @inheritdoc IUniswapV3Staker
function endIncentive(EndIncentiveParams memory params)
external
override
nonReentrant
{
require(
block.timestamp > params.claimDeadline,
'TIMESTAMP_LTE_CLAIMDEADLINE'
);
bytes32 key =
IncentiveHelper.getIncentiveId(
msg.sender,
params.rewardToken,
params.pool,
params.startTime,
params.endTime,
params.claimDeadline
);
Incentive memory incentive = incentives[key];
require(incentive.rewardToken != address(0), 'INVALID_INCENTIVE');
delete incentives[key];
// TODO: check for possible failures
IERC20Minimal(params.rewardToken).transfer(
msg.sender,
incentive.totalRewardUnclaimed
);
emit IncentiveEnded(
params.rewardToken,
params.pool,
params.startTime,
params.endTime
);
}
/// @inheritdoc IUniswapV3Staker
function depositToken(uint256 tokenId) external override {
nonfungiblePositionManager.safeTransferFrom(
msg.sender,
address(this),
tokenId
);
}
function onERC721Received(
address,
address from,
uint256 tokenId,
bytes calldata data
) external override returns (bytes4) {
require(
msg.sender == address(nonfungiblePositionManager),
'uniswap v3 nft only'
);
deposits[tokenId] = Deposit(from, 0);
emit TokenDeposited(tokenId, from);
if (data.length > 0) {
_stakeToken(abi.decode(data, (StakeTokenParams)));
}
return this.onERC721Received.selector;
}
/// @inheritdoc IUniswapV3Staker
function withdrawToken(uint256 tokenId, address to) external override {
Deposit memory deposit = deposits[tokenId];
require(deposit.numberOfStakes == 0, 'NUMBER_OF_STAKES_NOT_ZERO');
require(deposit.owner == msg.sender, 'NOT_YOUR_NFT');
nonfungiblePositionManager.safeTransferFrom(address(this), to, tokenId);
emit TokenWithdrawn(tokenId, to);
}
/// @inheritdoc IUniswapV3Staker
function stakeToken(StakeTokenParams memory params) external override {
require(
deposits[params.tokenId].owner == msg.sender,
'NOT_YOUR_DEPOSIT'
);
_stakeToken(params);
}
/// @inheritdoc IUniswapV3Staker
function unstakeToken(UnstakeTokenParams memory params)
external
override
nonReentrant
{
/*
Check:
* It checks that you are the owner of the Deposit,
* It checks that there exists a Stake for the provided key
(with non-zero secondsPerLiquidityInitialX128).
*/
require(
deposits[params.tokenId].owner == msg.sender,
'NOT_YOUR_DEPOSIT'
);
/*
Effects:
deposit.numberOfStakes -= 1 - Make sure this decrements properly
*/
deposits[params.tokenId].numberOfStakes -= 1;
// TODO: Zero-out the Stake with that key.
// stakes[tokenId]
/*
* It computes secondsPerLiquidityInPeriodX128 by computing
secondsPerLiquidityInsideX128 using the Uniswap v3 core contract
and subtracting secondsPerLiquidityInitialX128.
*/
// TODO: make sure not null
(
address poolAddress,
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) = _getPositionDetails(params.tokenId);
require(poolAddress != address(0), 'INVALID_POSITION');
IUniswapV3Pool pool = IUniswapV3Pool(poolAddress);
(, uint160 secondsPerLiquidityInsideX128, ) =
pool.snapshotCumulativesInside(tickLower, tickUpper);
bytes32 incentiveId =
IncentiveHelper.getIncentiveId(
params.creator,
params.rewardToken,
poolAddress,
params.startTime,
params.endTime,
params.claimDeadline
);
require(
incentives[incentiveId].rewardToken != address(0),
'BAD INCENTIVE'
);
uint160 secondsInPeriodX128 =
(secondsPerLiquidityInsideX128 -
stakes[params.tokenId][incentiveId]
.secondsPerLiquidityInitialX128) * liquidity;
/*
* It looks at the liquidity on the NFT itself and multiplies
that by secondsPerLiquidityInRangeX96 to get secondsX96.
* It computes reward rate for the Program and multiplies that
by secondsX96 to get reward.
* totalRewardsUnclaimed is decremented by reward. totalSecondsClaimed
is incremented by seconds.
*/
// TODO: check for overflows and integer types
// uint160 secondsX96 = FullMath.mulDiv(secondsPerLiquidityInStakingPeriodX128, , denominator);
// SafeMath.mul(secondsPerLiquidityInStakingPeriodX128, liquidity);
incentives[incentiveId].totalSecondsClaimedX128 += secondsInPeriodX128;
uint160 totalSecondsUnclaimedX128 =
uint32(Math.max(params.endTime, block.timestamp)) -
params.startTime -
incentives[incentiveId].totalSecondsClaimedX128;
// This is probably wrong
uint160 rewardRate =
uint160(
SafeMath.div(
incentives[incentiveId].totalRewardUnclaimed,
totalSecondsUnclaimedX128
)
);
uint256 reward = SafeMath.mul(secondsInPeriodX128, rewardRate);
// TODO: Before release: wrap this in try-catch properly
// try {
// TODO: incentive.rewardToken or rewardToken?
IERC20Minimal(incentives[incentiveId].rewardToken).transfer(
params.to,
reward
);
// } catch {}
emit TokenUnstaked(params.tokenId);
}
function _stakeToken(StakeTokenParams memory params) internal {
(address poolAddress, int24 tickLower, int24 tickUpper, ) =
_getPositionDetails(params.tokenId);
IUniswapV3Pool pool = IUniswapV3Pool(poolAddress);
bytes32 incentiveId =
IncentiveHelper.getIncentiveId(
params.creator,
params.rewardToken,
poolAddress,
params.startTime,
params.endTime,
params.claimDeadline
);
(, uint160 secondsPerLiquidityInsideX128, ) =
pool.snapshotCumulativesInside(tickLower, tickUpper);
stakes[params.tokenId][incentiveId] = Stake(
secondsPerLiquidityInsideX128
);
deposits[params.tokenId].numberOfStakes += 1;
emit TokenStaked(params.tokenId);
}
function _getPositionDetails(uint256 tokenId)
internal
view
returns (
address,
int24,
int24,
uint128
)
{
(
,
,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
,
,
,
) = nonfungiblePositionManager.positions(tokenId);
PoolAddress.PoolKey memory poolKey =
PoolAddress.getPoolKey(token0, token1, fee);
// Could do this via factory.getPool or locally via PoolAddress.
// TODO: what happens if this is null
return (
PoolAddress.computeAddress(address(factory), poolKey),
tickLower,
tickUpper,
liquidity
);
}
}