/
range-order.ts
328 lines (300 loc) · 8.59 KB
/
range-order.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
import {
CurrencyAmount,
Fraction,
Percent,
Price,
Token,
} from '@uniswap/sdk-core'
import {
Position,
Pool,
nearestUsableTick,
priceToClosestTick,
NonfungiblePositionManager,
MintOptions,
CollectOptions,
RemoveLiquidityOptions,
tickToPrice,
} from '@uniswap/v3-sdk'
import { getPoolInfo, getPrice } from './pool'
import { CurrentConfig } from '../config'
import { fromReadableAmount } from './conversion'
import {
MAX_FEE_PER_GAS,
MAX_PRIORITY_FEE_PER_GAS,
NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS,
} from './constants'
import {
TransactionState,
getProvider,
getWallet,
getWalletAddress,
sendTransaction,
} from './providers'
import { getPositionInfo, getTokenTransferApproval } from './positions'
import JSBI from 'jsbi'
import { ethers } from 'ethers'
export interface TakeProfitOrder {
targetTick: number
targetPrice: Price<Token, Token>
position: Position
zeroForOne: boolean
}
export async function watchTakeProfitOrder(
positionId: number,
order: TakeProfitOrder
): Promise<TransactionState | void> {
const poolInfo = await getPoolInfo()
const currentPositionInfo = await getPositionInfo(positionId)
if (currentPositionInfo.liquidity === ethers.BigNumber.from(0)) {
return
}
const address = getWalletAddress()
const provider = getProvider()
if (!address || !provider) {
return TransactionState.Failed
}
if (
order.zeroForOne
? poolInfo.tick > currentPositionInfo.tickUpper
: poolInfo.tick < currentPositionInfo.tickLower
) {
const pool = new Pool(
CurrentConfig.tokens.token0,
CurrentConfig.tokens.token1,
poolInfo.fee,
poolInfo.sqrtPriceX96.toString(),
poolInfo.liquidity.toString(),
poolInfo.tick
)
const collectOptions: Omit<CollectOptions, 'tokenId'> = {
expectedCurrencyOwed0: CurrencyAmount.fromRawAmount(
CurrentConfig.tokens.token0,
JSBI.BigInt(currentPositionInfo.tokensOwed0.toString())
),
expectedCurrencyOwed1: CurrencyAmount.fromRawAmount(
CurrentConfig.tokens.token1,
JSBI.BigInt(currentPositionInfo.tokensOwed1.toString())
),
recipient: address,
}
const removeLiquidityOptions: RemoveLiquidityOptions = {
deadline: Math.floor(Date.now() / 1000) + 60 * 20,
slippageTolerance: new Percent(50, 10_000),
tokenId: positionId,
// percentage of liquidity to remove
liquidityPercentage: new Percent(1),
collectOptions,
}
const currentPosition = new Position({
pool,
liquidity: JSBI.BigInt(currentPositionInfo.liquidity.toString()),
tickLower: currentPositionInfo.tickLower,
tickUpper: currentPositionInfo.tickUpper,
})
const { calldata, value } = NonfungiblePositionManager.removeCallParameters(
currentPosition,
removeLiquidityOptions
)
const transaction = {
data: calldata,
to: NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS,
value: value,
from: address,
maxFeePerGas: MAX_FEE_PER_GAS,
maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS,
gasLimit: '1000000',
}
return sendTransaction(transaction)
} else {
return
}
}
export async function mintTakeProfitOrder(
order: TakeProfitOrder
): Promise<number | void> {
const address = getWalletAddress()
const provider = getProvider()
if (!address || !provider) {
return
}
const { amount0, amount1 } = order.position.mintAmounts
// Give approval to the contract to transfer tokens
const tokenInApproval = await getTokenTransferApproval(
NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS,
CurrentConfig.tokens.token0,
address,
JSBI.BigInt(amount0)
)
const tokenOutApproval = await getTokenTransferApproval(
NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS,
CurrentConfig.tokens.token1,
address,
JSBI.BigInt(amount1)
)
// Fail if transfer approvals do not go through
if (
tokenInApproval !== TransactionState.Sent ||
tokenOutApproval !== TransactionState.Sent
) {
return
}
const mintOptions: MintOptions = {
recipient: address,
deadline: Math.floor(Date.now() / 1000) + 60 * 20,
slippageTolerance: new Percent(50, 10_000),
}
// get calldata for minting a position
const { calldata, value } = NonfungiblePositionManager.addCallParameters(
order.position,
mintOptions
)
//build transaction
const transaction = {
data: calldata,
to: NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS,
value: ethers.BigNumber.from(value),
from: address,
maxFeePerGas: MAX_FEE_PER_GAS,
maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS,
gasLimit: '1000000',
}
const txRes = await getWallet().call(transaction)
const decodedRes = ethers.utils.defaultAbiCoder.decode(
['tuple(uint256, uint128, uint256, uint256)'],
txRes
)[0]
await sendTransaction(transaction)
return decodedRes[0].toNumber()
}
export async function constructTakeProfitOrder(
zeroForOne: boolean,
amount: number
): Promise<TakeProfitOrder> {
const poolInfo = await getPoolInfo()
const configuredPool = new Pool(
CurrentConfig.tokens.token0,
CurrentConfig.tokens.token1,
poolInfo.fee,
poolInfo.sqrtPriceX96.toString(),
poolInfo.liquidity.toString(),
poolInfo.tick
)
const current = await getPrice()
const priceTarget = zeroForOne
? new Price(
current.baseCurrency,
current.quoteCurrency,
current.asFraction.multiply(
new Fraction(100 + CurrentConfig.targetPercentageUp, 100)
).denominator,
current.asFraction.multiply(
new Fraction(100 + CurrentConfig.targetPercentageUp, 100)
).numerator
)
: new Price(
current.baseCurrency,
current.quoteCurrency,
current.asFraction.divide(
new Fraction(100 + CurrentConfig.targetPercentageUp, 100)
).denominator,
current.asFraction.divide(
new Fraction(100 + CurrentConfig.targetPercentageUp, 100)
).numerator
)
const targetTick = nearestUsableTick(
priceToClosestTick(priceTarget),
poolInfo.tickSpacing
)
const amount0 = zeroForOne
? CurrencyAmount.fromRawAmount(
CurrentConfig.tokens.token0,
fromReadableAmount(amount, CurrentConfig.tokens.token0.decimals)
)
: CurrencyAmount.fromRawAmount(CurrentConfig.tokens.token0, 0)
const amount1 = zeroForOne
? CurrencyAmount.fromRawAmount(CurrentConfig.tokens.token1, 0)
: CurrencyAmount.fromRawAmount(
CurrentConfig.tokens.token1,
fromReadableAmount(amount, CurrentConfig.tokens.token1.decimals)
)
const position = await constructRangeOrderPosition(
amount0,
amount1,
targetTick,
configuredPool,
zeroForOne
)
const closestTargetPrice = tickToPrice(
position.amount0.currency,
position.amount1.currency,
targetTick
)
return {
targetTick,
targetPrice: closestTargetPrice,
position,
zeroForOne,
}
}
async function constructRangeOrderPosition(
token0Amount: CurrencyAmount<Token>,
token1Amount: CurrencyAmount<Token>,
tickBoundary: number,
pool: Pool,
zeroForOne: boolean
): Promise<Position> {
if (zeroForOne) {
// Create position from next tick above or one tick above current tick to boundary tick
let tickUpper = tickBoundary
let tickLower = tickUpper - pool.tickSpacing
if (tickLower <= pool.tickCurrent) {
tickLower += pool.tickSpacing
tickUpper += pool.tickSpacing
}
return Position.fromAmounts({
pool: pool,
tickLower: tickLower,
tickUpper: tickUpper,
amount0: JSBI.BigInt(
token0Amount
.multiply(
JSBI.exponentiate(
JSBI.BigInt(10),
JSBI.BigInt(token0Amount.currency.decimals)
)
)
.toFixed(0)
),
amount1: JSBI.BigInt(
token1Amount
.multiply(
JSBI.exponentiate(
JSBI.BigInt(10),
JSBI.BigInt(token1Amount.currency.decimals)
)
)
.toFixed(0)
),
useFullPrecision: true,
})
} else {
// Create position from next tick below or one tick below the current tick to boundary tick
let tickLower = tickBoundary
let tickUpper = tickLower + pool.tickSpacing
if (tickUpper > pool.tickCurrent) {
tickUpper -= pool.tickSpacing
}
if (tickLower >= tickUpper) {
tickLower = tickUpper -= pool.tickSpacing
}
return Position.fromAmounts({
pool: pool,
tickLower: tickLower,
tickUpper: tickUpper,
amount0: token0Amount.quotient,
amount1: token1Amount.quotient,
useFullPrecision: true,
})
}
}