This repository has been archived by the owner on Apr 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 429
/
nonfungiblePositionManager.ts
438 lines (371 loc) · 12.3 KB
/
nonfungiblePositionManager.ts
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
import {
BigintIsh,
Percent,
Token,
CurrencyAmount,
validateAndParseAddress,
Currency,
NativeCurrency
} from '@uniswap/sdk-core'
import JSBI from 'jsbi'
import invariant from 'tiny-invariant'
import { Position } from './entities/position'
import { ONE, ZERO } from './internalConstants'
import { MethodParameters, toHex } from './utils/calldata'
import { Interface } from '@ethersproject/abi'
import INonfungiblePositionManager from '@uniswap/v3-periphery/artifacts/contracts/NonfungiblePositionManager.sol/NonfungiblePositionManager.json'
import { PermitOptions, SelfPermit } from './selfPermit'
import { ADDRESS_ZERO } from './constants'
import { Pool } from './entities'
import { Multicall } from './multicall'
import { Payments } from './payments'
const MaxUint128 = toHex(JSBI.subtract(JSBI.exponentiate(JSBI.BigInt(2), JSBI.BigInt(128)), JSBI.BigInt(1)))
export interface MintSpecificOptions {
/**
* The account that should receive the minted NFT.
*/
recipient: string
/**
* Creates pool if not initialized before mint.
*/
createPool?: boolean
}
export interface IncreaseSpecificOptions {
/**
* Indicates the ID of the position to increase liquidity for.
*/
tokenId: BigintIsh
}
/**
* Options for producing the calldata to add liquidity.
*/
export interface CommonAddLiquidityOptions {
/**
* How much the pool price is allowed to move.
*/
slippageTolerance: Percent
/**
* When the transaction expires, in epoch seconds.
*/
deadline: BigintIsh
/**
* Whether to spend ether. If true, one of the pool tokens must be WETH, by default false
*/
useNative?: NativeCurrency
/**
* The optional permit parameters for spending token0
*/
token0Permit?: PermitOptions
/**
* The optional permit parameters for spending token1
*/
token1Permit?: PermitOptions
}
export type MintOptions = CommonAddLiquidityOptions & MintSpecificOptions
export type IncreaseOptions = CommonAddLiquidityOptions & IncreaseSpecificOptions
export type AddLiquidityOptions = MintOptions | IncreaseOptions
export interface SafeTransferOptions {
/**
* The account sending the NFT.
*/
sender: string
/**
* The account that should receive the NFT.
*/
recipient: string
/**
* The id of the token being sent.
*/
tokenId: BigintIsh
/**
* The optional parameter that passes data to the `onERC721Received` call for the staker
*/
data?: string
}
// type guard
function isMint(options: AddLiquidityOptions): options is MintOptions {
return Object.keys(options).some(k => k === 'recipient')
}
export interface CollectOptions {
/**
* Indicates the ID of the position to collect for.
*/
tokenId: BigintIsh
/**
* Expected value of tokensOwed0, including as-of-yet-unaccounted-for fees/liquidity value to be burned
*/
expectedCurrencyOwed0: CurrencyAmount<Currency>
/**
* Expected value of tokensOwed1, including as-of-yet-unaccounted-for fees/liquidity value to be burned
*/
expectedCurrencyOwed1: CurrencyAmount<Currency>
/**
* The account that should receive the tokens.
*/
recipient: string
}
export interface NFTPermitOptions {
v: 0 | 1 | 27 | 28
r: string
s: string
deadline: BigintIsh
spender: string
}
/**
* Options for producing the calldata to exit a position.
*/
export interface RemoveLiquidityOptions {
/**
* The ID of the token to exit
*/
tokenId: BigintIsh
/**
* The percentage of position liquidity to exit.
*/
liquidityPercentage: Percent
/**
* How much the pool price is allowed to move.
*/
slippageTolerance: Percent
/**
* When the transaction expires, in epoch seconds.
*/
deadline: BigintIsh
/**
* Whether the NFT should be burned if the entire position is being exited, by default false.
*/
burnToken?: boolean
/**
* The optional permit of the token ID being exited, in case the exit transaction is being sent by an account that does not own the NFT
*/
permit?: NFTPermitOptions
/**
* Parameters to be passed on to collect
*/
collectOptions: Omit<CollectOptions, 'tokenId'>
}
export abstract class NonfungiblePositionManager {
public static INTERFACE: Interface = new Interface(INonfungiblePositionManager.abi)
/**
* Cannot be constructed.
*/
private constructor() {}
private static encodeCreate(pool: Pool): string {
return NonfungiblePositionManager.INTERFACE.encodeFunctionData('createAndInitializePoolIfNecessary', [
pool.token0.address,
pool.token1.address,
pool.fee,
toHex(pool.sqrtRatioX96)
])
}
public static createCallParameters(pool: Pool): MethodParameters {
return {
calldata: this.encodeCreate(pool),
value: toHex(0)
}
}
public static addCallParameters(position: Position, options: AddLiquidityOptions): MethodParameters {
invariant(JSBI.greaterThan(position.liquidity, ZERO), 'ZERO_LIQUIDITY')
const calldatas: string[] = []
// get amounts
const { amount0: amount0Desired, amount1: amount1Desired } = position.mintAmounts
// adjust for slippage
const minimumAmounts = position.mintAmountsWithSlippage(options.slippageTolerance)
const amount0Min = toHex(minimumAmounts.amount0)
const amount1Min = toHex(minimumAmounts.amount1)
const deadline = toHex(options.deadline)
// create pool if needed
if (isMint(options) && options.createPool) {
calldatas.push(this.encodeCreate(position.pool))
}
// permits if necessary
if (options.token0Permit) {
calldatas.push(SelfPermit.encodePermit(position.pool.token0, options.token0Permit))
}
if (options.token1Permit) {
calldatas.push(SelfPermit.encodePermit(position.pool.token1, options.token1Permit))
}
// mint
if (isMint(options)) {
const recipient: string = validateAndParseAddress(options.recipient)
calldatas.push(
NonfungiblePositionManager.INTERFACE.encodeFunctionData('mint', [
{
token0: position.pool.token0.address,
token1: position.pool.token1.address,
fee: position.pool.fee,
tickLower: position.tickLower,
tickUpper: position.tickUpper,
amount0Desired: toHex(amount0Desired),
amount1Desired: toHex(amount1Desired),
amount0Min,
amount1Min,
recipient,
deadline
}
])
)
} else {
// increase
calldatas.push(
NonfungiblePositionManager.INTERFACE.encodeFunctionData('increaseLiquidity', [
{
tokenId: toHex(options.tokenId),
amount0Desired: toHex(amount0Desired),
amount1Desired: toHex(amount1Desired),
amount0Min,
amount1Min,
deadline
}
])
)
}
let value: string = toHex(0)
if (options.useNative) {
const wrapped = options.useNative.wrapped
invariant(position.pool.token0.equals(wrapped) || position.pool.token1.equals(wrapped), 'NO_WETH')
const wrappedValue = position.pool.token0.equals(wrapped) ? amount0Desired : amount1Desired
// we only need to refund if we're actually sending ETH
if (JSBI.greaterThan(wrappedValue, ZERO)) {
calldatas.push(Payments.encodeRefundETH())
}
value = toHex(wrappedValue)
}
return {
calldata: Multicall.encodeMulticall(calldatas),
value
}
}
private static encodeCollect(options: CollectOptions): string[] {
const calldatas: string[] = []
const tokenId = toHex(options.tokenId)
const involvesETH =
options.expectedCurrencyOwed0.currency.isNative || options.expectedCurrencyOwed1.currency.isNative
const recipient = validateAndParseAddress(options.recipient)
// collect
calldatas.push(
NonfungiblePositionManager.INTERFACE.encodeFunctionData('collect', [
{
tokenId,
recipient: involvesETH ? ADDRESS_ZERO : recipient,
amount0Max: MaxUint128,
amount1Max: MaxUint128
}
])
)
if (involvesETH) {
const ethAmount = options.expectedCurrencyOwed0.currency.isNative
? options.expectedCurrencyOwed0.quotient
: options.expectedCurrencyOwed1.quotient
const token = options.expectedCurrencyOwed0.currency.isNative
? (options.expectedCurrencyOwed1.currency as Token)
: (options.expectedCurrencyOwed0.currency as Token)
const tokenAmount = options.expectedCurrencyOwed0.currency.isNative
? options.expectedCurrencyOwed1.quotient
: options.expectedCurrencyOwed0.quotient
calldatas.push(Payments.encodeUnwrapWETH9(ethAmount, recipient))
calldatas.push(Payments.encodeSweepToken(token, tokenAmount, recipient))
}
return calldatas
}
public static collectCallParameters(options: CollectOptions): MethodParameters {
const calldatas: string[] = NonfungiblePositionManager.encodeCollect(options)
return {
calldata: Multicall.encodeMulticall(calldatas),
value: toHex(0)
}
}
/**
* Produces the calldata for completely or partially exiting a position
* @param position The position to exit
* @param options Additional information necessary for generating the calldata
* @returns The call parameters
*/
public static removeCallParameters(position: Position, options: RemoveLiquidityOptions): MethodParameters {
const calldatas: string[] = []
const deadline = toHex(options.deadline)
const tokenId = toHex(options.tokenId)
// construct a partial position with a percentage of liquidity
const partialPosition = new Position({
pool: position.pool,
liquidity: options.liquidityPercentage.multiply(position.liquidity).quotient,
tickLower: position.tickLower,
tickUpper: position.tickUpper
})
invariant(JSBI.greaterThan(partialPosition.liquidity, ZERO), 'ZERO_LIQUIDITY')
// slippage-adjusted underlying amounts
const { amount0: amount0Min, amount1: amount1Min } = partialPosition.burnAmountsWithSlippage(
options.slippageTolerance
)
if (options.permit) {
calldatas.push(
NonfungiblePositionManager.INTERFACE.encodeFunctionData('permit', [
validateAndParseAddress(options.permit.spender),
tokenId,
toHex(options.permit.deadline),
options.permit.v,
options.permit.r,
options.permit.s
])
)
}
// remove liquidity
calldatas.push(
NonfungiblePositionManager.INTERFACE.encodeFunctionData('decreaseLiquidity', [
{
tokenId,
liquidity: toHex(partialPosition.liquidity),
amount0Min: toHex(amount0Min),
amount1Min: toHex(amount1Min),
deadline
}
])
)
const { expectedCurrencyOwed0, expectedCurrencyOwed1, ...rest } = options.collectOptions
calldatas.push(
...NonfungiblePositionManager.encodeCollect({
tokenId: toHex(options.tokenId),
// add the underlying value to the expected currency already owed
expectedCurrencyOwed0: expectedCurrencyOwed0.add(
CurrencyAmount.fromRawAmount(expectedCurrencyOwed0.currency, amount0Min)
),
expectedCurrencyOwed1: expectedCurrencyOwed1.add(
CurrencyAmount.fromRawAmount(expectedCurrencyOwed1.currency, amount1Min)
),
...rest
})
)
if (options.liquidityPercentage.equalTo(ONE)) {
if (options.burnToken) {
calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('burn', [tokenId]))
}
} else {
invariant(options.burnToken !== true, 'CANNOT_BURN')
}
return {
calldata: Multicall.encodeMulticall(calldatas),
value: toHex(0)
}
}
public static safeTransferFromParameters(options: SafeTransferOptions): MethodParameters {
const recipient = validateAndParseAddress(options.recipient)
const sender = validateAndParseAddress(options.sender)
let calldata: string
if (options.data) {
calldata = NonfungiblePositionManager.INTERFACE.encodeFunctionData(
'safeTransferFrom(address,address,uint256,bytes)',
[sender, recipient, toHex(options.tokenId), options.data]
)
} else {
calldata = NonfungiblePositionManager.INTERFACE.encodeFunctionData('safeTransferFrom(address,address,uint256)', [
sender,
recipient,
toHex(options.tokenId)
])
}
return {
calldata: calldata,
value: toHex(0)
}
}
}