-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathpositions.ts
217 lines (192 loc) · 5.56 KB
/
positions.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
import { CurrencyAmount, Percent, Token } from '@uniswap/sdk-core'
import {
MintOptions,
nearestUsableTick,
NonfungiblePositionManager,
Pool,
Position,
} from '@uniswap/v3-sdk'
import { BigNumber, ethers } from 'ethers'
import { CurrentConfig } from '../config'
import {
ERC20_ABI,
MAX_FEE_PER_GAS,
MAX_PRIORITY_FEE_PER_GAS,
NONFUNGIBLE_POSITION_MANAGER_ABI,
NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS,
} from './constants'
import { TOKEN_AMOUNT_TO_APPROVE_FOR_TRANSFER } from './constants'
import { fromReadableAmount } from './conversion'
import { getPoolInfo } from './pool'
import {
getProvider,
getWalletAddress,
sendTransaction,
TransactionState,
} from './providers'
export interface PositionInfo {
tickLower: number
tickUpper: number
liquidity: BigNumber
feeGrowthInside0LastX128: BigNumber
feeGrowthInside1LastX128: BigNumber
tokensOwed0: BigNumber
tokensOwed1: BigNumber
}
export async function mintPosition(): Promise<TransactionState> {
const address = getWalletAddress()
const provider = getProvider()
if (!address || !provider) {
return TransactionState.Failed
}
// Give approval to the contract to transfer tokens
const tokenInApproval = await getTokenTransferApproval(
CurrentConfig.tokens.token0
)
const tokenOutApproval = await getTokenTransferApproval(
CurrentConfig.tokens.token1
)
// Fail if transfer approvals do not go through
if (
tokenInApproval !== TransactionState.Sent ||
tokenOutApproval !== TransactionState.Sent
) {
return TransactionState.Failed
}
const positionToMint = await constructPosition(
CurrencyAmount.fromRawAmount(
CurrentConfig.tokens.token0,
fromReadableAmount(
CurrentConfig.tokens.token0Amount,
CurrentConfig.tokens.token0.decimals
)
),
CurrencyAmount.fromRawAmount(
CurrentConfig.tokens.token1,
fromReadableAmount(
CurrentConfig.tokens.token1Amount,
CurrentConfig.tokens.token1.decimals
)
)
)
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(
positionToMint,
mintOptions
)
// build transaction
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,
}
return sendTransaction(transaction)
}
export async function constructPosition(
token0Amount: CurrencyAmount<Token>,
token1Amount: CurrencyAmount<Token>
): Promise<Position> {
// get pool info
const poolInfo = await getPoolInfo()
// construct pool instance
const configuredPool = new Pool(
token0Amount.currency,
token1Amount.currency,
poolInfo.fee,
poolInfo.sqrtPriceX96.toString(),
poolInfo.liquidity.toString(),
poolInfo.tick
)
// create position using the maximum liquidity from input amounts
return Position.fromAmounts({
pool: configuredPool,
tickLower:
nearestUsableTick(poolInfo.tick, poolInfo.tickSpacing) -
poolInfo.tickSpacing * 2,
tickUpper:
nearestUsableTick(poolInfo.tick, poolInfo.tickSpacing) +
poolInfo.tickSpacing * 2,
amount0: token0Amount.quotient,
amount1: token1Amount.quotient,
useFullPrecision: true,
})
}
export async function getPositionIds(): Promise<number[]> {
const provider = getProvider()
const address = getWalletAddress()
if (!provider || !address) {
throw new Error('No provider available')
}
const positionContract = new ethers.Contract(
NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS,
NONFUNGIBLE_POSITION_MANAGER_ABI,
provider
)
// Get number of positions
const balance: number = await positionContract.balanceOf(address)
// Get all positions
const tokenIds = []
for (let i = 0; i < balance; i++) {
const tokenOfOwnerByIndex: number =
await positionContract.tokenOfOwnerByIndex(address, i)
tokenIds.push(tokenOfOwnerByIndex)
}
return tokenIds
}
export async function getPositionInfo(tokenId: number): Promise<PositionInfo> {
const provider = getProvider()
if (!provider) {
throw new Error('No provider available')
}
const positionContract = new ethers.Contract(
NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS,
NONFUNGIBLE_POSITION_MANAGER_ABI,
provider
)
const position = await positionContract.positions(tokenId)
return {
tickLower: position.tickLower,
tickUpper: position.tickUpper,
liquidity: position.liquidity,
feeGrowthInside0LastX128: position.feeGrowthInside0LastX128,
feeGrowthInside1LastX128: position.feeGrowthInside1LastX128,
tokensOwed0: position.tokensOwed0,
tokensOwed1: position.tokensOwed1,
}
}
export async function getTokenTransferApproval(
token: Token
): Promise<TransactionState> {
const provider = getProvider()
const address = getWalletAddress()
if (!provider || !address) {
console.log('No Provider Found')
return TransactionState.Failed
}
try {
const tokenContract = new ethers.Contract(
token.address,
ERC20_ABI,
provider
)
const transaction = await tokenContract.populateTransaction.approve(
NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS,
TOKEN_AMOUNT_TO_APPROVE_FOR_TRANSFER
)
return sendTransaction({
...transaction,
from: address,
})
} catch (e) {
console.error(e)
return TransactionState.Failed
}
}