@w3lib/evm-batch-call 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +79 -2
- package/dist/liquidity/common.d.ts +72 -0
- package/dist/liquidity/common.d.ts.map +1 -0
- package/dist/liquidity/common.js +271 -0
- package/dist/liquidity/common.js.map +1 -0
- package/dist/liquidity/concentrated.d.ts +19 -0
- package/dist/liquidity/concentrated.d.ts.map +1 -0
- package/dist/liquidity/concentrated.js +106 -0
- package/dist/liquidity/concentrated.js.map +1 -0
- package/dist/liquidity/index.d.ts +42 -0
- package/dist/liquidity/index.d.ts.map +1 -0
- package/dist/liquidity/index.js +143 -0
- package/dist/liquidity/index.js.map +1 -0
- package/dist/liquidity/types.d.ts +182 -0
- package/dist/liquidity/types.d.ts.map +1 -0
- package/dist/liquidity/types.js +2 -0
- package/dist/liquidity/types.js.map +1 -0
- package/dist/liquidity/v2.d.ts +5 -0
- package/dist/liquidity/v2.d.ts.map +1 -0
- package/dist/liquidity/v2.js +342 -0
- package/dist/liquidity/v2.js.map +1 -0
- package/dist/liquidity/v3.d.ts +6 -0
- package/dist/liquidity/v3.d.ts.map +1 -0
- package/dist/liquidity/v3.js +310 -0
- package/dist/liquidity/v3.js.map +1 -0
- package/dist/liquidity/v4.d.ts +5 -0
- package/dist/liquidity/v4.d.ts.map +1 -0
- package/dist/liquidity/v4.js +279 -0
- package/dist/liquidity/v4.js.map +1 -0
- package/dist/lp.d.ts +8 -1
- package/dist/lp.d.ts.map +1 -1
- package/dist/lp.js +29 -18
- package/dist/lp.js.map +1 -1
- package/dist/lpMath.d.ts +55 -0
- package/dist/lpMath.d.ts.map +1 -1
- package/dist/lpMath.js +209 -0
- package/dist/lpMath.js.map +1 -1
- package/dist/subpaths/liquidity.d.ts +24 -0
- package/dist/subpaths/liquidity.d.ts.map +1 -0
- package/dist/subpaths/liquidity.js +21 -0
- package/dist/subpaths/liquidity.js.map +1 -0
- package/dist/subpaths/lp.d.ts +1 -1
- package/dist/subpaths/lp.d.ts.map +1 -1
- package/dist/subpaths/lp.js +1 -1
- package/dist/subpaths/lp.js.map +1 -1
- package/dist/write/tron.d.ts +2 -0
- package/dist/write/tron.d.ts.map +1 -1
- package/dist/write/tron.js +4 -0
- package/dist/write/tron.js.map +1 -1
- package/package.json +20 -12
- package/src/liquidity/common.ts +314 -0
- package/src/liquidity/concentrated.ts +121 -0
- package/src/liquidity/index.ts +171 -0
- package/src/liquidity/types.ts +194 -0
- package/src/liquidity/v2.ts +371 -0
- package/src/liquidity/v3.ts +382 -0
- package/src/liquidity/v4.ts +348 -0
- package/src/lp.ts +36 -18
- package/src/lpMath.ts +223 -0
- package/src/subpaths/liquidity.ts +52 -0
- package/src/subpaths/lp.ts +20 -1
- package/src/write/tron.ts +5 -0
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import { Interface } from 'ethers'
|
|
2
|
+
|
|
3
|
+
import type { LpPosition, LpProtocol, LpToken } from '../lp.js'
|
|
4
|
+
import { getAmountsForLiquidity, getFeeGrowthInside, getFeesEarned, getMinAmounts, getMintAmounts, getSqrtRatioAtTick, getTickAtSqrtRatio } from '../lpMath.js'
|
|
5
|
+
import { liquidityFor, resolveRange, sqrtPriceOf, v3MinAmounts } from './concentrated.js'
|
|
6
|
+
import {
|
|
7
|
+
MAX_UINT128,
|
|
8
|
+
ZERO_ADDRESS,
|
|
9
|
+
approvals,
|
|
10
|
+
concentratedProtocol,
|
|
11
|
+
evm,
|
|
12
|
+
isNative,
|
|
13
|
+
makePlan,
|
|
14
|
+
out,
|
|
15
|
+
parseAmount,
|
|
16
|
+
priceFields,
|
|
17
|
+
removeAmount,
|
|
18
|
+
tokenIdOf,
|
|
19
|
+
tokenInfo,
|
|
20
|
+
type Ctx,
|
|
21
|
+
} from './common.js'
|
|
22
|
+
import type { IncreaseLiquidityParams, LiquidityPlan, LiquidityTx, NewPositionParams, PositionRef, RemoveLiquidityParams } from './types.js'
|
|
23
|
+
|
|
24
|
+
const npmInterface = new Interface([
|
|
25
|
+
'function WETH9() view returns (address)',
|
|
26
|
+
'function factory() view returns (address)',
|
|
27
|
+
'function ownerOf(uint256 tokenId) view returns (address)',
|
|
28
|
+
'function isApprovedForAll(address owner, address operator) view returns (bool)',
|
|
29
|
+
'function positions(uint256 tokenId) view returns (uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1)',
|
|
30
|
+
'function mint((address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline) params) payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)',
|
|
31
|
+
'function increaseLiquidity((uint256 tokenId, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, uint256 deadline) params) payable returns (uint128 liquidity, uint256 amount0, uint256 amount1)',
|
|
32
|
+
'function decreaseLiquidity((uint256 tokenId, uint128 liquidity, uint256 amount0Min, uint256 amount1Min, uint256 deadline) params) payable returns (uint256 amount0, uint256 amount1)',
|
|
33
|
+
'function collect((uint256 tokenId, address recipient, uint128 amount0Max, uint128 amount1Max) params) payable returns (uint256 amount0, uint256 amount1)',
|
|
34
|
+
'function burn(uint256 tokenId) payable',
|
|
35
|
+
'function multicall(bytes[] data) payable returns (bytes[] results)',
|
|
36
|
+
'function refundETH() payable',
|
|
37
|
+
'function unwrapWETH9(uint256 amountMinimum, address recipient) payable',
|
|
38
|
+
'function sweepToken(address token, uint256 amountMinimum, address recipient) payable',
|
|
39
|
+
'function createAndInitializePoolIfNecessary(address token0, address token1, uint24 fee, uint160 sqrtPriceX96) payable returns (address pool)',
|
|
40
|
+
])
|
|
41
|
+
const factoryInterface = new Interface([
|
|
42
|
+
'function getPool(address tokenA, address tokenB, uint24 fee) view returns (address)',
|
|
43
|
+
'function feeAmountTickSpacing(uint24 fee) view returns (int24)',
|
|
44
|
+
])
|
|
45
|
+
// 只声明前两个返回值:各分叉 slot0 后面的字段类型不同
|
|
46
|
+
const poolInterface = new Interface([
|
|
47
|
+
'function slot0() view returns (uint160 sqrtPriceX96, int24 tick)',
|
|
48
|
+
'function tickSpacing() view returns (int24)',
|
|
49
|
+
'function feeGrowthGlobal0X128() view returns (uint256)',
|
|
50
|
+
'function feeGrowthGlobal1X128() view returns (uint256)',
|
|
51
|
+
'function ticks(int24 tick) view returns (uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)',
|
|
52
|
+
])
|
|
53
|
+
|
|
54
|
+
const U128_MASK = MAX_UINT128
|
|
55
|
+
|
|
56
|
+
interface V3Pool {
|
|
57
|
+
address: string | null
|
|
58
|
+
sqrtPriceX96: bigint
|
|
59
|
+
tick: number
|
|
60
|
+
tickSpacing: number
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface V3Position {
|
|
64
|
+
protocol: LpProtocol
|
|
65
|
+
npm: string
|
|
66
|
+
tokenId: bigint
|
|
67
|
+
owner: string
|
|
68
|
+
operator: string
|
|
69
|
+
/** 发送者是不是被所有者 setApprovalForAll 授权的 operator */
|
|
70
|
+
approvedForAll: boolean
|
|
71
|
+
token0: string
|
|
72
|
+
token1: string
|
|
73
|
+
fee: number
|
|
74
|
+
tickLower: number
|
|
75
|
+
tickUpper: number
|
|
76
|
+
liquidity: bigint
|
|
77
|
+
pool: V3Pool & { address: string }
|
|
78
|
+
/** 未领取的手续费(含 tokensOwed) */
|
|
79
|
+
fees0: bigint
|
|
80
|
+
fees1: bigint
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function factoryOf(ctx: Ctx, protocol: LpProtocol): Promise<string> {
|
|
84
|
+
if (protocol.factory) {
|
|
85
|
+
return evm(protocol.factory)
|
|
86
|
+
}
|
|
87
|
+
return evm((await ctx.provider.call(ctx.provider.contract(protocol.positionManager as string, npmInterface).factory())) as string)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const wethOf = async (ctx: Ctx, npm: string) => evm((await ctx.provider.call(ctx.provider.contract(npm, npmInterface).WETH9())) as string)
|
|
91
|
+
|
|
92
|
+
/** 读已有的仓位:仓位信息、池子状态、未领取的手续费 */
|
|
93
|
+
async function readPosition(ctx: Ctx, ref: PositionRef | LpPosition): Promise<V3Position> {
|
|
94
|
+
const protocol = concentratedProtocol(ctx, ref)
|
|
95
|
+
const npm = evm(protocol.positionManager as string)
|
|
96
|
+
const tokenId = tokenIdOf(ref)
|
|
97
|
+
const c = ctx.provider.contract(npm, npmInterface)
|
|
98
|
+
const [factory, [owner, p]] = await Promise.all([
|
|
99
|
+
factoryOf(ctx, protocol),
|
|
100
|
+
ctx.provider.all([c.ownerOf(tokenId), c.positions(tokenId)]) as Promise<
|
|
101
|
+
[
|
|
102
|
+
string,
|
|
103
|
+
{
|
|
104
|
+
operator: string
|
|
105
|
+
token0: string
|
|
106
|
+
token1: string
|
|
107
|
+
fee: bigint
|
|
108
|
+
tickLower: bigint
|
|
109
|
+
tickUpper: bigint
|
|
110
|
+
liquidity: bigint
|
|
111
|
+
feeGrowthInside0LastX128: bigint
|
|
112
|
+
feeGrowthInside1LastX128: bigint
|
|
113
|
+
tokensOwed0: bigint
|
|
114
|
+
tokensOwed1: bigint
|
|
115
|
+
},
|
|
116
|
+
]
|
|
117
|
+
>,
|
|
118
|
+
])
|
|
119
|
+
const pool = evm((await ctx.provider.call(ctx.provider.contract(factory, factoryInterface).getPool(p.token0, p.token1, p.fee))) as string)
|
|
120
|
+
if (pool === ZERO_ADDRESS) {
|
|
121
|
+
throw new Error(`Cannot find the pool of position ${tokenId}`)
|
|
122
|
+
}
|
|
123
|
+
const tickLower = Number(p.tickLower)
|
|
124
|
+
const tickUpper = Number(p.tickUpper)
|
|
125
|
+
const pc = ctx.provider.contract(pool, poolInterface)
|
|
126
|
+
const [slot0, spacing, global0, global1, lower, upper, approvedForAll] = (await ctx.provider.all([
|
|
127
|
+
pc.slot0(),
|
|
128
|
+
pc.tickSpacing(),
|
|
129
|
+
pc.feeGrowthGlobal0X128(),
|
|
130
|
+
pc.feeGrowthGlobal1X128(),
|
|
131
|
+
pc.ticks(tickLower),
|
|
132
|
+
pc.ticks(tickUpper),
|
|
133
|
+
c.isApprovedForAll(owner, ctx.owner),
|
|
134
|
+
])) as [{ 0: bigint; 1: bigint }, bigint, bigint, bigint, { 2: bigint; 3: bigint }, { 2: bigint; 3: bigint }, boolean]
|
|
135
|
+
const tick = Number(slot0[1])
|
|
136
|
+
const inside0 = getFeeGrowthInside(tick, tickLower, tickUpper, global0, lower[2], upper[2])
|
|
137
|
+
const inside1 = getFeeGrowthInside(tick, tickLower, tickUpper, global1, lower[3], upper[3])
|
|
138
|
+
return {
|
|
139
|
+
protocol,
|
|
140
|
+
npm,
|
|
141
|
+
tokenId,
|
|
142
|
+
owner: evm(owner),
|
|
143
|
+
operator: evm(p.operator),
|
|
144
|
+
approvedForAll,
|
|
145
|
+
token0: evm(p.token0),
|
|
146
|
+
token1: evm(p.token1),
|
|
147
|
+
fee: Number(p.fee),
|
|
148
|
+
tickLower,
|
|
149
|
+
tickUpper,
|
|
150
|
+
liquidity: p.liquidity,
|
|
151
|
+
pool: { address: pool, sqrtPriceX96: slot0[0], tick, tickSpacing: Number(spacing) },
|
|
152
|
+
// 与仓位合约一致:tokensOwed += uint128(新增),按 uint128 回绕
|
|
153
|
+
fees0: (p.tokensOwed0 + (getFeesEarned(p.liquidity, inside0, p.feeGrowthInside0LastX128) & U128_MASK)) & U128_MASK,
|
|
154
|
+
fees1: (p.tokensOwed1 + (getFeesEarned(p.liquidity, inside1, p.feeGrowthInside1LastX128) & U128_MASK)) & U128_MASK,
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** 追加 / 移除 / 领取需要是仓位的所有者,或被授权的 operator(单个仓位的 approve 或 setApprovalForAll),与合约一致 */
|
|
159
|
+
function assertCanManage(ctx: Ctx, position: V3Position): void {
|
|
160
|
+
if (position.owner !== ctx.owner && position.operator !== ctx.owner && !position.approvedForAll) {
|
|
161
|
+
throw new Error(`${out(ctx, ctx.owner)} is not the owner of position ${position.tokenId} (owner: ${out(ctx, position.owner)})`)
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** 包装币那一边用主币时:确认池子里有包装币 */
|
|
166
|
+
async function nativeWeth(ctx: Ctx, npm: string, token0: string, token1: string): Promise<string | null> {
|
|
167
|
+
if (!ctx.options.native) {
|
|
168
|
+
return null
|
|
169
|
+
}
|
|
170
|
+
const weth = await wethOf(ctx, npm)
|
|
171
|
+
if (weth !== token0 && weth !== token1) {
|
|
172
|
+
throw new Error('native: true needs one side of the pool to be the wrapped native token')
|
|
173
|
+
}
|
|
174
|
+
return weth
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const call = (name: string, args: unknown[]) => npmInterface.encodeFunctionData(name, args)
|
|
178
|
+
/** 一个调用直接发,多个用仓位合约的 multicall 合成一笔 */
|
|
179
|
+
const wrap = (calls: string[]) => (calls.length === 1 ? (calls[0] as string) : npmInterface.encodeFunctionData('multicall', [calls]))
|
|
180
|
+
|
|
181
|
+
export async function v3Add(ctx: Ctx, params: IncreaseLiquidityParams | NewPositionParams): Promise<LiquidityPlan> {
|
|
182
|
+
let protocol: LpProtocol
|
|
183
|
+
let npm: string
|
|
184
|
+
let token0: string
|
|
185
|
+
let token1: string
|
|
186
|
+
let fee: number
|
|
187
|
+
let pool: V3Pool
|
|
188
|
+
let tickLower: number
|
|
189
|
+
let tickUpper: number
|
|
190
|
+
let tokenId: bigint | null = null
|
|
191
|
+
let createPrice: bigint | null = null
|
|
192
|
+
let weth: string | null
|
|
193
|
+
let t0: LpToken
|
|
194
|
+
let t1: LpToken
|
|
195
|
+
let given0: bigint | undefined
|
|
196
|
+
let given1: bigint | undefined
|
|
197
|
+
|
|
198
|
+
if ('position' in params) {
|
|
199
|
+
const position = await readPosition(ctx, params.position)
|
|
200
|
+
// 合约允许任何人往别人的仓位里加流动性:tokenId 写错时代币会白送给别人,这里只允许所有者 / operator
|
|
201
|
+
assertCanManage(ctx, position)
|
|
202
|
+
;({ protocol, npm, token0, token1, fee, pool, tickLower, tickUpper } = position)
|
|
203
|
+
tokenId = position.tokenId
|
|
204
|
+
weth = await nativeWeth(ctx, npm, token0, token1)
|
|
205
|
+
;[t0, t1] = (await tokenInfo(ctx, [token0, token1])) as [LpToken, LpToken]
|
|
206
|
+
given0 = parseAmount(params.amount0, params.amount0Formatted, t0, 'amount0')
|
|
207
|
+
given1 = parseAmount(params.amount1, params.amount1Formatted, t1, 'amount1')
|
|
208
|
+
} else {
|
|
209
|
+
protocol = params.protocol as LpProtocol
|
|
210
|
+
npm = evm(protocol.positionManager as string)
|
|
211
|
+
if (params.fee === undefined) {
|
|
212
|
+
throw new Error('fee is required for V3 (e.g. 500, 3000, 10000)')
|
|
213
|
+
}
|
|
214
|
+
fee = params.fee
|
|
215
|
+
let a = evm(params.tokenA)
|
|
216
|
+
let b = evm(params.tokenB)
|
|
217
|
+
weth = null
|
|
218
|
+
if (isNative(ctx, a) || isNative(ctx, b) || ctx.options.native) {
|
|
219
|
+
weth = await wethOf(ctx, npm)
|
|
220
|
+
a = isNative(ctx, a) ? weth : a
|
|
221
|
+
b = isNative(ctx, b) ? weth : b
|
|
222
|
+
if (a !== weth && b !== weth) {
|
|
223
|
+
throw new Error('native: true needs one side of the pool to be the wrapped native token')
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
if (a === b) {
|
|
227
|
+
throw new Error('tokenA and tokenB must be different')
|
|
228
|
+
}
|
|
229
|
+
const aIs0 = BigInt(a) < BigInt(b)
|
|
230
|
+
;[token0, token1] = aIs0 ? [a, b] : [b, a]
|
|
231
|
+
const factory = await factoryOf(ctx, protocol)
|
|
232
|
+
const f = ctx.provider.contract(factory, factoryInterface)
|
|
233
|
+
const [address, defaultSpacing] = (await ctx.provider.all([f.getPool(token0, token1, fee), f.feeAmountTickSpacing(fee)])) as [string, bigint]
|
|
234
|
+
pool = { address: evm(address) === ZERO_ADDRESS ? null : evm(address), sqrtPriceX96: 0n, tick: 0, tickSpacing: Number(defaultSpacing) }
|
|
235
|
+
if (pool.address) {
|
|
236
|
+
const pc = ctx.provider.contract(pool.address, poolInterface)
|
|
237
|
+
const [slot0, spacing] = (await ctx.provider.all([pc.slot0(), pc.tickSpacing()])) as [{ 0: bigint; 1: bigint }, bigint]
|
|
238
|
+
pool = { ...pool, sqrtPriceX96: slot0[0], tick: Number(slot0[1]), tickSpacing: Number(spacing) }
|
|
239
|
+
} else if (pool.tickSpacing <= 0) {
|
|
240
|
+
throw new Error(`Fee tier ${fee} is not enabled on ${protocol.id}`)
|
|
241
|
+
}
|
|
242
|
+
;[t0, t1] = (await tokenInfo(ctx, [token0, token1])) as [LpToken, LpToken]
|
|
243
|
+
if (pool.sqrtPriceX96 === 0n) {
|
|
244
|
+
// 池子不存在或还没初始化:用 initialPrice 创建
|
|
245
|
+
if (params.initialPrice === undefined) {
|
|
246
|
+
throw new Error(`The ${protocol.id} pool for this pair and fee ${fee} does not exist yet; pass initialPrice to create it`)
|
|
247
|
+
}
|
|
248
|
+
createPrice = sqrtPriceOf(params.initialPrice, aIs0, t0, t1, 'initialPrice')
|
|
249
|
+
pool = { ...pool, sqrtPriceX96: createPrice, tick: getTickAtSqrtRatio(createPrice) }
|
|
250
|
+
}
|
|
251
|
+
;[tickLower, tickUpper] = resolveRange(params, aIs0, t0, t1, pool.tickSpacing)
|
|
252
|
+
const amountA = parseAmount(params.amountA, params.amountAFormatted, aIs0 ? t0 : t1, 'amountA')
|
|
253
|
+
const amountB = parseAmount(params.amountB, params.amountBFormatted, aIs0 ? t1 : t0, 'amountB')
|
|
254
|
+
;[given0, given1] = aIs0 ? [amountA, amountB] : [amountB, amountA]
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const liquidity = liquidityFor(pool.sqrtPriceX96, tickLower, tickUpper, given0, given1, t0, t1)
|
|
258
|
+
const [amount0, amount1] = getMintAmounts(pool.sqrtPriceX96, getSqrtRatioAtTick(tickLower), getSqrtRatioAtTick(tickUpper), liquidity)
|
|
259
|
+
// 传给合约的数量:给了的按给的,另一边按算出来的(合约按两边较少的算流动性,结果就是上面的 liquidity)。
|
|
260
|
+
// 价格在区间外时用不到的一边为 0(不用授权 / 附带主币)
|
|
261
|
+
const desired0 = amount0 === 0n ? 0n : (given0 ?? amount0)
|
|
262
|
+
const desired1 = amount1 === 0n ? 0n : (given1 ?? amount1)
|
|
263
|
+
const [min0, min1] = v3MinAmounts(pool.sqrtPriceX96, tickLower, tickUpper, desired0, desired1, ctx.slippage)
|
|
264
|
+
|
|
265
|
+
const calls: string[] = []
|
|
266
|
+
if (createPrice !== null) {
|
|
267
|
+
calls.push(call('createAndInitializePoolIfNecessary', [token0, token1, fee, createPrice]))
|
|
268
|
+
}
|
|
269
|
+
if (tokenId === null) {
|
|
270
|
+
calls.push(call('mint', [{ token0, token1, fee, tickLower, tickUpper, amount0Desired: desired0, amount1Desired: desired1, amount0Min: min0, amount1Min: min1, recipient: ctx.recipient, deadline: ctx.deadline }]))
|
|
271
|
+
} else {
|
|
272
|
+
calls.push(call('increaseLiquidity', [{ tokenId, amount0Desired: desired0, amount1Desired: desired1, amount0Min: min0, amount1Min: min1, deadline: ctx.deadline }]))
|
|
273
|
+
}
|
|
274
|
+
// 主币:附带包装币那一边的数量,多余的退回
|
|
275
|
+
const value = weth === token0 ? desired0 : weth === token1 ? desired1 : 0n
|
|
276
|
+
if (value > 0n) {
|
|
277
|
+
calls.push(call('refundETH', []))
|
|
278
|
+
}
|
|
279
|
+
const main: LiquidityTx = { kind: 'add', to: out(ctx, npm), data: wrap(calls), value: value.toString() }
|
|
280
|
+
const approve = await approvals(
|
|
281
|
+
ctx,
|
|
282
|
+
[
|
|
283
|
+
{ token: token0, spender: npm, amount: desired0 },
|
|
284
|
+
{ token: token1, spender: npm, amount: desired1 },
|
|
285
|
+
].filter((i) => i.token !== weth),
|
|
286
|
+
)
|
|
287
|
+
return makePlan(ctx, {
|
|
288
|
+
action: 'add',
|
|
289
|
+
version: 'v3',
|
|
290
|
+
protocol: protocol.id,
|
|
291
|
+
protocolName: protocol.name,
|
|
292
|
+
pool: pool.address,
|
|
293
|
+
createPool: createPrice !== null,
|
|
294
|
+
token0: t0,
|
|
295
|
+
token1: t1,
|
|
296
|
+
tokenId: tokenId === null ? null : tokenId.toString(),
|
|
297
|
+
tickLower,
|
|
298
|
+
tickUpper,
|
|
299
|
+
tick: pool.tick,
|
|
300
|
+
...priceFields(t0, t1, pool.sqrtPriceX96, tickLower, tickUpper),
|
|
301
|
+
liquidity: liquidity.toString(),
|
|
302
|
+
amount0: amount0.toString(),
|
|
303
|
+
amount1: amount1.toString(),
|
|
304
|
+
amount0Max: desired0.toString(),
|
|
305
|
+
amount1Max: desired1.toString(),
|
|
306
|
+
amount0Min: null,
|
|
307
|
+
amount1Min: null,
|
|
308
|
+
// V3 追加流动性不会领取手续费(留在仓位里)
|
|
309
|
+
fees0: '0',
|
|
310
|
+
fees1: '0',
|
|
311
|
+
native: weth === null ? null : weth === token0 ? 'token0' : 'token1',
|
|
312
|
+
value: value.toString(),
|
|
313
|
+
transactions: [...approve, main],
|
|
314
|
+
})
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** 移除(liquidity > 0)/ 只领取手续费(collectOnly) */
|
|
318
|
+
export async function v3Remove(ctx: Ctx, params: RemoveLiquidityParams, collectOnly = false): Promise<LiquidityPlan> {
|
|
319
|
+
const position = await readPosition(ctx, params.position)
|
|
320
|
+
assertCanManage(ctx, position)
|
|
321
|
+
const { npm, token0, token1, tickLower, tickUpper, tokenId, pool } = position
|
|
322
|
+
let liquidity = 0n
|
|
323
|
+
if (!collectOnly) {
|
|
324
|
+
if (position.liquidity === 0n) {
|
|
325
|
+
throw new Error(`Position ${tokenId} has no liquidity; use collectFees to collect what is owed`)
|
|
326
|
+
}
|
|
327
|
+
liquidity = removeAmount(position.liquidity, params.percent, params.liquidity)
|
|
328
|
+
} else if (position.fees0 === 0n && position.fees1 === 0n) {
|
|
329
|
+
throw new Error(`Position ${tokenId} has no fees to collect`)
|
|
330
|
+
}
|
|
331
|
+
const burn = !collectOnly && !!params.burn
|
|
332
|
+
if (burn && liquidity !== position.liquidity) {
|
|
333
|
+
throw new Error('burn: true needs the whole position to be removed')
|
|
334
|
+
}
|
|
335
|
+
const weth = await nativeWeth(ctx, npm, token0, token1)
|
|
336
|
+
const [t0, t1] = (await tokenInfo(ctx, [token0, token1])) as [LpToken, LpToken]
|
|
337
|
+
const sqrtA = getSqrtRatioAtTick(tickLower)
|
|
338
|
+
const sqrtB = getSqrtRatioAtTick(tickUpper)
|
|
339
|
+
const [amount0, amount1] = getAmountsForLiquidity(pool.sqrtPriceX96, sqrtA, sqrtB, liquidity)
|
|
340
|
+
const [min0, min1] = getMinAmounts(pool.sqrtPriceX96, sqrtA, sqrtB, liquidity, ctx.slippage)
|
|
341
|
+
|
|
342
|
+
const calls: string[] = []
|
|
343
|
+
if (liquidity > 0n) {
|
|
344
|
+
calls.push(call('decreaseLiquidity', [{ tokenId, liquidity, amount0Min: min0, amount1Min: min1, deadline: ctx.deadline }]))
|
|
345
|
+
}
|
|
346
|
+
// 撤出的代币和手续费都要 collect 才会转出;包装币换成主币时先收到仓位合约(零地址)再转出
|
|
347
|
+
calls.push(call('collect', [{ tokenId, recipient: weth ? ZERO_ADDRESS : ctx.recipient, amount0Max: MAX_UINT128, amount1Max: MAX_UINT128 }]))
|
|
348
|
+
if (weth) {
|
|
349
|
+
calls.push(call('unwrapWETH9', [0n, ctx.recipient]))
|
|
350
|
+
calls.push(call('sweepToken', [weth === token0 ? token1 : token0, 0n, ctx.recipient]))
|
|
351
|
+
}
|
|
352
|
+
if (burn) {
|
|
353
|
+
calls.push(call('burn', [tokenId]))
|
|
354
|
+
}
|
|
355
|
+
return makePlan(ctx, {
|
|
356
|
+
action: collectOnly ? 'collect' : 'remove',
|
|
357
|
+
version: 'v3',
|
|
358
|
+
protocol: position.protocol.id,
|
|
359
|
+
protocolName: position.protocol.name,
|
|
360
|
+
pool: pool.address,
|
|
361
|
+
createPool: false,
|
|
362
|
+
token0: t0,
|
|
363
|
+
token1: t1,
|
|
364
|
+
tokenId: tokenId.toString(),
|
|
365
|
+
tickLower,
|
|
366
|
+
tickUpper,
|
|
367
|
+
tick: pool.tick,
|
|
368
|
+
...priceFields(t0, t1, pool.sqrtPriceX96, tickLower, tickUpper),
|
|
369
|
+
liquidity: liquidity.toString(),
|
|
370
|
+
amount0: amount0.toString(),
|
|
371
|
+
amount1: amount1.toString(),
|
|
372
|
+
amount0Max: null,
|
|
373
|
+
amount1Max: null,
|
|
374
|
+
amount0Min: min0.toString(),
|
|
375
|
+
amount1Min: min1.toString(),
|
|
376
|
+
fees0: position.fees0.toString(),
|
|
377
|
+
fees1: position.fees1.toString(),
|
|
378
|
+
native: weth === null ? null : weth === token0 ? 'token0' : 'token1',
|
|
379
|
+
value: '0',
|
|
380
|
+
transactions: [{ kind: collectOnly ? 'collect' : 'remove', to: out(ctx, npm), data: wrap(calls), value: '0' }],
|
|
381
|
+
})
|
|
382
|
+
}
|