waterpump-evm-pool-sdk 0.1.0

EVM pool SDK — viewers, infusers, harvesters, swappers for Uniswap V3/V4, PancakeSwap, Slipstream, Shadow, Algebra
Documentation
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
439
440
//! Call builder for Ramses V3 pool infuser operations
//!
//! Uses shadow-lib bindings for Ramses V3-specific interfaces.

use alloy::primitives::{
    aliases::{I24, U160},
    Address, Bytes, U256,
};
use alloy_sol_types::SolCall;
use anyhow::{Context, Result};
use uniswap_sdk_core::{
    entities::{BaseCurrency, FractionBase},
    utils::FromBig,
};
use uniswap_v3_sdk::prelude::{encode_multicall, encode_permit, encode_refund_eth, IERC721Permit};
use waterpump_evm_shadow_client::interfaces::INonfungiblePositionManager;

use crate::{
    common::{mint_amounts_utils::calculate_mint_amounts, slippage_utils::ratios_after_slippage},
    pool_infusers::common::{
        calculate_position_amounts, calculate_slippage_context, AddLiquidityAmounts,
    },
    pool_swappers::common::MethodParameters,
    traits::pool_infuser::{
        AddBatchLiquidityParams, AddLiquidityOptions, AddLiquidityParams,
        AddLiquiditySpecificOptions, CollectOptions, CollectParams, RemoveBatchLiquidityParams,
        RemoveLiquidityOptions, RemoveLiquidityParams,
    },
    types::v3_pool_key::V3PoolKey,
};

/// Build calldata for mint or increase liquidity operation
fn build_add_liquidity_calldata(
    pool_key: &V3PoolKey,
    tick_spacing: I24,
    tick_lower: I24,
    tick_upper: I24,
    amounts: &AddLiquidityAmounts,
    specific_opts: AddLiquiditySpecificOptions,
    deadline: U256,
) -> Bytes {
    match specific_opts {
        AddLiquiditySpecificOptions::Mint(opts) => INonfungiblePositionManager::mintCall {
            params: INonfungiblePositionManager::MintParams {
                token0: pool_key.token_a.address(),
                token1: pool_key.token_b.address(),
                tickSpacing: tick_spacing,
                tickLower: tick_lower,
                tickUpper: tick_upper,
                amount0Desired: amounts.amount0_desired,
                amount1Desired: amounts.amount1_desired,
                amount0Min: amounts.amount0_min,
                amount1Min: amounts.amount1_min,
                recipient: opts.recipient,
                deadline,
            },
        }
        .abi_encode()
        .into(),
        AddLiquiditySpecificOptions::Increase(opts) => {
            INonfungiblePositionManager::increaseLiquidityCall {
                params: INonfungiblePositionManager::IncreaseLiquidityParams {
                    tokenId: opts.token_id,
                    amount0Desired: amounts.amount0_desired,
                    amount1Desired: amounts.amount1_desired,
                    amount0Min: amounts.amount0_min,
                    amount1Min: amounts.amount1_min,
                    deadline,
                },
            }
            .abi_encode()
            .into()
        }
    }
}

/// Build call parameters for adding liquidity (mint or increase)
///
/// Uses Position::mint_amounts_with_slippage approach with
/// ratios_after_slippage for accurate minimum amounts calculation.
pub fn build_add_liquidity_call_parameters(
    pool_key: &V3PoolKey,
    tick_spacing: I24,
    params: AddLiquidityParams,
    options: AddLiquidityOptions,
) -> Result<MethodParameters> {
    let mut calldatas: Vec<Bytes> = Vec::with_capacity(5);

    let deadline = options.deadline;
    let amount0_desired = U256::from_big_int(params.amount0.quotient());
    let amount1_desired = U256::from_big_int(params.amount1.quotient());

    // Calculate slippage context
    let slippage_ctx =
        calculate_slippage_context(&params.token0_price, &options.slippage_tolerance)?;

    // Calculate position amounts with slippage
    let amounts = calculate_position_amounts(
        params.tick_lower,
        params.tick_upper,
        amount0_desired,
        amount1_desired,
        &slippage_ctx,
    )?;

    // Permits if necessary
    if let Some(permit) = options.token0_permit {
        calldatas.push(encode_permit(&pool_key.token_a, permit));
    }
    if let Some(permit) = options.token1_permit {
        calldatas.push(encode_permit(&pool_key.token_b, permit));
    }

    // Mint or increase liquidity
    calldatas.push(build_add_liquidity_calldata(
        pool_key,
        tick_spacing,
        params.tick_lower,
        params.tick_upper,
        &amounts,
        params.specific_opts,
        deadline,
    ));

    let mut value = U256::ZERO;

    // Handle native ETH if needed
    if let Some(ether) = options.use_native {
        let wrapped = ether.wrapped();
        let wrapped_value = if pool_key.token_a.equals(wrapped) {
            amounts.amount0_desired
        } else if pool_key.token_b.equals(wrapped) {
            amounts.amount1_desired
        } else {
            return Err(anyhow::anyhow!("NO_WETH: Pool tokens don't match WETH"));
        };

        if wrapped_value > U256::ZERO {
            calldatas.push(encode_refund_eth());
        }

        value = wrapped_value;
    }

    Ok(MethodParameters { calldata: encode_multicall(calldatas), value })
}

/// Build call parameters for adding batch liquidity (multiple positions in one
/// transaction)
///
/// Uses multicall to batch multiple mint operations together for gas
/// efficiency. Uses a shared token0_price for all positions.
pub fn build_add_batch_liquidity_call_parameters(
    pool_key: &V3PoolKey,
    tick_spacing: I24,
    params: AddBatchLiquidityParams,
    options: AddLiquidityOptions,
) -> Result<MethodParameters> {
    let mut calldatas: Vec<Bytes> = Vec::with_capacity(params.items.len() + 4);
    let mut total_value = U256::ZERO;

    let deadline = options.deadline;

    // Calculate shared slippage context once
    let slippage_ctx =
        calculate_slippage_context(&params.token0_price, &options.slippage_tolerance)?;

    // Permits if necessary (once for all positions)
    if let Some(permit) = options.token0_permit {
        calldatas.push(encode_permit(&pool_key.token_a, permit));
    }
    if let Some(permit) = options.token1_permit {
        calldatas.push(encode_permit(&pool_key.token_b, permit));
    }

    for item in &params.items {
        let amount0_desired = U256::from_big_int(item.amount0.quotient());
        let amount1_desired = U256::from_big_int(item.amount1.quotient());

        // Calculate position amounts with slippage
        let amounts = calculate_position_amounts(
            item.tick_lower,
            item.tick_upper,
            amount0_desired,
            amount1_desired,
            &slippage_ctx,
        )?;

        // Mint or increase liquidity
        calldatas.push(build_add_liquidity_calldata(
            pool_key,
            tick_spacing,
            item.tick_lower,
            item.tick_upper,
            &amounts,
            item.specific_opts,
            deadline,
        ));

        // Handle native ETH if needed
        if let Some(ref ether) = options.use_native {
            let wrapped = ether.wrapped();
            let wrapped_value = if pool_key.token_a.equals(wrapped) {
                amounts.amount0_desired
            } else if pool_key.token_b.equals(wrapped) {
                amounts.amount1_desired
            } else {
                return Err(anyhow::anyhow!("NO_WETH: Pool tokens don't match WETH"));
            };
            total_value += wrapped_value;
        }
    }

    // Add refund ETH call at the end if any native ETH was used
    if total_value > U256::ZERO {
        calldatas.push(encode_refund_eth());
    }

    Ok(MethodParameters { calldata: encode_multicall(calldatas), value: total_value })
}

/// Parameters for building remove liquidity calldata for a single position
struct RemovePositionParams {
    token_id: U256,
    liquidity: U256,
    tick_lower: I24,
    tick_upper: I24,
    recipient: Address,
    deadline: U256,
    burn_token: bool,
}

/// Build calldatas for removing liquidity from a single position (internal
/// helper)
///
/// Generates decrease liquidity, collect, and optionally burn calldatas.
fn build_remove_position_calldatas(
    pool_key: &V3PoolKey,
    params: &RemovePositionParams,
    sqrt_ratio_x96_lower_slippage: U160,
    sqrt_ratio_x96_upper_slippage: U160,
    collect_options: &CollectOptions,
) -> Result<Vec<Bytes>> {
    let mut calldatas: Vec<Bytes> = Vec::with_capacity(4);

    // Calculate minimum amounts with slippage following
    // Position::burn_amounts_with_slippage:
    // - amount0 is smaller when price is higher (use upper slippage price)
    // - amount1 is smaller when price is lower (use lower slippage price)
    let mint_amounts_upper = calculate_mint_amounts(
        params.tick_lower,
        params.tick_upper,
        params.liquidity.to::<u128>(),
        sqrt_ratio_x96_upper_slippage,
    )
    .context("Failed to calculate mint amounts at upper slippage price")?;

    let mint_amounts_lower = calculate_mint_amounts(
        params.tick_lower,
        params.tick_upper,
        params.liquidity.to::<u128>(),
        sqrt_ratio_x96_lower_slippage,
    )
    .context("Failed to calculate mint amounts at lower slippage price")?;

    let amount0_min = mint_amounts_upper.amount0;
    let amount1_min = mint_amounts_lower.amount1;

    tracing::info!("Amount0 min: {:?}", amount0_min);
    tracing::info!("Amount1 min: {:?}", amount1_min);

    // Decrease liquidity
    calldatas.push(
        INonfungiblePositionManager::decreaseLiquidityCall {
            params: INonfungiblePositionManager::DecreaseLiquidityParams {
                tokenId: params.token_id,
                liquidity: params.liquidity.to::<u128>(),
                amount0Min: amount0_min,
                amount1Min: amount1_min,
                deadline: params.deadline,
            },
        }
        .abi_encode()
        .into(),
    );

    // Collect
    let collect_params = CollectParams { token_id: params.token_id, recipient: params.recipient };
    let collect_calldatas = build_collect_calldatas(pool_key, &collect_params, collect_options)?;
    calldatas.extend(collect_calldatas);

    // Burn token if needed
    if params.burn_token {
        calldatas.push(
            INonfungiblePositionManager::burnCall { tokenId: params.token_id }.abi_encode().into(),
        );
    }

    Ok(calldatas)
}

/// Build call parameters for removing liquidity
pub fn build_remove_liquidity_call_parameters(
    pool_key: &V3PoolKey,
    params: RemoveLiquidityParams,
    options: RemoveLiquidityOptions,
) -> Result<MethodParameters> {
    let mut calldatas: Vec<Bytes> = Vec::with_capacity(6);

    // NFT permit if needed
    if let Some(permit) = options.permit {
        calldatas.push(
            IERC721Permit::permitCall {
                spender: permit.spender,
                tokenId: params.token_id,
                deadline: permit.deadline,
                v: permit.signature.v() as u8 + 27,
                r: permit.signature.r().into(),
                s: permit.signature.s().into(),
            }
            .abi_encode()
            .into(),
        );
    }

    // Get slippage-adjusted sqrt ratios
    let (sqrt_ratio_x96_lower_slippage, sqrt_ratio_x96_upper_slippage) =
        ratios_after_slippage(&params.token0_price, &options.slippage_tolerance)
            .context("Failed to calculate ratios after slippage")?;

    // Build remove position calldatas
    let remove_params = RemovePositionParams {
        token_id: params.token_id,
        liquidity: params.liquidity,
        tick_lower: params.tick_lower,
        tick_upper: params.tick_upper,
        recipient: params.recipient,
        deadline: params.deadline,
        burn_token: options.burn_token,
    };

    let remove_calldatas = build_remove_position_calldatas(
        pool_key,
        &remove_params,
        sqrt_ratio_x96_lower_slippage,
        sqrt_ratio_x96_upper_slippage,
        &options.collect_options,
    )?;
    calldatas.extend(remove_calldatas);

    Ok(MethodParameters { calldata: encode_multicall(calldatas), value: U256::ZERO })
}

/// Build call parameters for removing batch liquidity (multiple positions in
/// one transaction)
pub fn build_remove_batch_liquidity_call_parameters(
    pool_key: &V3PoolKey,
    params: RemoveBatchLiquidityParams,
    options: RemoveLiquidityOptions,
) -> Result<MethodParameters> {
    let mut calldatas: Vec<Bytes> = Vec::with_capacity(params.items.len() * 3 + 1);

    // Get slippage-adjusted sqrt ratios (shared for all positions)
    let (sqrt_ratio_x96_lower_slippage, sqrt_ratio_x96_upper_slippage) =
        ratios_after_slippage(&params.token0_price, &options.slippage_tolerance)
            .context("Failed to calculate ratios after slippage")?;

    for item in &params.items {
        let remove_params = RemovePositionParams {
            token_id: item.token_id,
            liquidity: item.liquidity,
            tick_lower: item.tick_lower,
            tick_upper: item.tick_upper,
            recipient: params.recipient,
            deadline: params.deadline,
            burn_token: item.burn_token,
        };

        let remove_calldatas = build_remove_position_calldatas(
            pool_key,
            &remove_params,
            sqrt_ratio_x96_lower_slippage,
            sqrt_ratio_x96_upper_slippage,
            &options.collect_options,
        )?;
        calldatas.extend(remove_calldatas);
    }

    Ok(MethodParameters { calldata: encode_multicall(calldatas), value: U256::ZERO })
}

/// Build calldatas for collecting fees from a position
fn build_collect_calldatas(
    _pool_key: &V3PoolKey,
    params: &CollectParams,
    options: &CollectOptions,
) -> Result<Vec<Bytes>> {
    let mut calldatas: Vec<Bytes> = Vec::with_capacity(1);

    // Determine max amounts to collect
    let amount0_max = options
        .expected_currency_owed0
        .as_ref()
        .map(|c| U256::from_big_int(c.quotient()))
        .unwrap_or(U256::MAX);
    let amount1_max = options
        .expected_currency_owed1
        .as_ref()
        .map(|c| U256::from_big_int(c.quotient()))
        .unwrap_or(U256::MAX);

    // Convert to u128 (max values for collect)
    let amount0_max_u128 = amount0_max.min(U256::from(u128::MAX)).to::<u128>();
    let amount1_max_u128 = amount1_max.min(U256::from(u128::MAX)).to::<u128>();

    calldatas.push(
        INonfungiblePositionManager::collectCall {
            params: INonfungiblePositionManager::CollectParams {
                tokenId: params.token_id,
                recipient: params.recipient,
                amount0Max: amount0_max_u128,
                amount1Max: amount1_max_u128,
            },
        }
        .abi_encode()
        .into(),
    );

    Ok(calldatas)
}

/// Build call parameters for collecting fees
pub fn build_collect_call_parameters(
    pool_key: &V3PoolKey,
    params: &CollectParams,
    options: &CollectOptions,
) -> Result<MethodParameters> {
    let calldatas = build_collect_calldatas(pool_key, params, options)?;
    Ok(MethodParameters { calldata: encode_multicall(calldatas), value: U256::ZERO })
}