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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
use std::time::Duration;

use alloy::{
    network::Ethereum,
    primitives::{
        aliases::{I24, U160},
        Address, Bytes, TxHash, I256, U256,
    },
    providers::{PendingTransactionConfig, Provider},
    rpc::types::{TransactionReceipt, TransactionRequest},
};
use anyhow::{Context, Result};
use tracing::{debug, error, info, trace};

/// Represents method call parameters including calldata and value.
#[derive(Debug, Clone)]
pub struct MethodParameters {
    pub calldata: Bytes,
    pub value: U256,
}

use super::{adjust_gas_prices, AdjustedGasPrices};
use crate::types::{
    swap_params::GasPriceOptions,
    swap_results::{V3SwapResult, V3SwapWithIntermediateResult},
};

/// Send a transaction, wait for confirmation, and retrieve the receipt.
///
/// This function:
/// 1. Sends the transaction to the network
/// 2. Waits for confirmation with an optional timeout
/// 3. Retrieves and returns the transaction receipt
///
/// # Arguments
///
/// * `provider` - The Ethereum provider to send transactions through
/// * `tx` - The transaction request to send
/// * `timeout` - Optional timeout for waiting for transaction confirmation
///   (defaults to 30 seconds)
/// * `error_handler` - Optional function to handle errors when sending the
///   transaction (must accept a displayable error)
///
/// # Returns
///
/// Returns the transaction receipt if successful, or an error if any step
/// fails.
///
/// # Example
///
/// ```ignore
/// let receipt = send_and_wait_for_transaction(
///     &provider,
///     tx,
///     Some(Duration::from_secs(30)),
///     Some(handle_uniswap_v3_error)
/// ).await?;
/// ```
#[tracing::instrument(skip(provider, tx, error_handler))]
pub async fn send_and_wait_for_transaction<P, F>(
    provider: &P,
    tx: TransactionRequest,
    timeout: Option<Duration>,
    error_handler: Option<F>,
) -> Result<TransactionReceipt>
where
    P: Provider<Ethereum> + ?Sized,
    F: FnOnce(Box<dyn std::fmt::Display + Send + Sync>) -> anyhow::Error,
{
    let pending_tx = if let Some(handler) = error_handler {
        provider.send_transaction(tx).await.map_err(|e| handler(Box::new(e)))?
    } else {
        provider
            .send_transaction(tx)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to send transaction: {}", e))?
    };

    let tx_hash = pending_tx.tx_hash();
    info!(tx_hash = ?tx_hash, "Transaction sent, waiting for confirmation");

    let timeout_duration = timeout.unwrap_or(Duration::from_secs(120));
    let pending_tx_config =
        PendingTransactionConfig::new(*tx_hash).with_timeout(Some(timeout_duration));

    match provider.watch_pending_transaction(pending_tx_config).await?.await {
        Ok(tx_hash) => info!(tx_hash = ?tx_hash, "Transaction confirmed"),
        Err(e) => {
            error!(error = ?e, "Failed to watch pending transaction");
        }
    };

    info!(
        tx_hash = ?tx_hash,
        timeout_seconds = timeout_duration.as_secs(),
        "Transaction confirmed or timed out"
    );

    let error_message = format!("Failed to get transaction receipt: {}", tx_hash);
    let receipt = provider
        .get_transaction_receipt(*tx_hash)
        .await
        .context(error_message.clone())?
        .context(error_message)?;

    info!(
        tx_hash = ?receipt.transaction_hash,
        block_number = ?receipt.block_number,
        gas_used = ?receipt.gas_used,
        status = ?receipt.status(),
        "Transaction receipt retrieved"
    );

    Ok(receipt)
}

/// Build a transaction request with gas price configuration.
///
/// This function:
/// 1. Gets the current nonce for the sender address
/// 2. Adjusts gas prices based on provided options and network conditions
/// 3. Creates a transaction request with all parameters set
///
/// # Arguments
///
/// * `provider` - The Ethereum provider
/// * `sender_address` - The address sending the transaction
/// * `to_address` - The address to send the transaction to
/// * `method_params` - The method parameters containing calldata and value
/// * `gas_price_options` - Optional gas price configuration
///
/// # Returns
///
/// Returns a `TransactionRequest` with nonce and gas prices configured.
///
/// # Example
///
/// ```ignore
/// let tx = build_transaction_with_gas_prices(
///     &provider,
///     sender_address,
///     router_address,
///     method_params,
///     gas_price_options
/// ).await?;
/// ```
#[tracing::instrument(skip(provider, method_params, gas_price_options), fields(
    sender_address = ?sender_address,
    to_address = ?to_address,
    value = ?method_params.value
))]
pub async fn build_transaction_with_gas_prices<P: Provider<Ethereum> + ?Sized>(
    provider: &P,
    sender_address: Address,
    to_address: Address,
    method_params: MethodParameters,
    gas_price_options: Option<GasPriceOptions>,
) -> Result<TransactionRequest> {
    // Extract gas fee fields from gas_price_options parameter
    let provided_max_priority_fee_per_gas =
        gas_price_options.as_ref().and_then(|g| g.max_priority_fee_per_gas);
    let provided_max_fee_per_gas = gas_price_options.as_ref().and_then(|g| g.max_fee_per_gas);
    let gas_price_buffer_multiplier =
        gas_price_options.as_ref().and_then(|g| g.gas_price_buffer_multiplier);

    // Get the current nonce for the sender address
    let nonce = provider.get_transaction_count(sender_address).await?;
    info!(nonce = ?nonce, "Fetched transaction nonce");

    // Dynamically adjust gas prices based on current network conditions
    let AdjustedGasPrices { max_priority_fee_per_gas, max_fee_per_gas } =
        if let Some(buffer_multiplier) = gas_price_buffer_multiplier {
            adjust_gas_prices(
                provider,
                provided_max_priority_fee_per_gas,
                provided_max_fee_per_gas,
                buffer_multiplier,
            )
            .await?
        } else {
            AdjustedGasPrices {
                max_priority_fee_per_gas: provided_max_priority_fee_per_gas,
                max_fee_per_gas: provided_max_fee_per_gas,
            }
        };

    // Build the transaction request
    let mut tx = TransactionRequest::default()
        .from(sender_address)
        .to(to_address)
        .input(method_params.calldata.into())
        .value(method_params.value)
        .nonce(nonce);

    // Set priority gas fee (maxPriorityFeePerGas) if provided
    if let Some(max_priority_fee) = max_priority_fee_per_gas {
        // Convert U256 to u128 (gas fees fit in u128)
        let priority_fee_u128 = max_priority_fee.to::<u128>();
        tx = tx.max_priority_fee_per_gas(priority_fee_u128);
        debug!(max_priority_fee_per_gas = ?max_priority_fee, "Priority gas fee set");
    }

    // Set max fee per gas if provided
    if let Some(max_fee) = max_fee_per_gas {
        // Convert U256 to u128 (gas fees fit in u128)
        let max_fee_u128 = max_fee.to::<u128>();
        tx = tx.max_fee_per_gas(max_fee_u128);
        debug!(max_fee_per_gas = ?max_fee, "Max fee per gas set");
    }

    info!(value = ?method_params.value, "Transaction built with gas prices");
    Ok(tx)
}

/// Swap event data structure
pub struct SwapEventData {
    pub sender: Address,
    pub recipient: Address,
    pub amount0: I256,
    pub amount1: I256,
    pub sqrt_price_x96: U160,
    pub liquidity: u128,
    pub tick: I24,
}

/// Find and decode event from transaction receipt logs
///
/// This function:
/// 1. Iterates through all logs in the transaction receipt
/// 2. Attempts to decode each log using the provided decoder function
/// 3. Returns the result if found
///
/// # Arguments
///
/// * `receipt` - The transaction receipt containing logs
/// * `decode_fn` - A function that attempts to decode a log and returns the
///   result type
///
/// # Returns
///
/// Returns the result type `R` if an event is found, or an error if not found.
///
/// # Example
///
/// ```ignore
/// let swap_result = find_event(
///     &receipt,
///     |log, tx_hash| {
///         let decoded = log.log_decode::<Swap>()?;
///         let swap_data = SwapEventData {
///             sender: decoded.inner.sender,
///             recipient: decoded.inner.recipient,
///             amount0: decoded.inner.amount0,
///             amount1: decoded.inner.amount1,
///             sqrt_price_x96: decoded.inner.sqrtPriceX96,
///             liquidity: decoded.inner.liquidity,
///             tick: decoded.inner.tick,
///         };
///         let (amount_in, amount_out) = if is_to_b {
///             (swap_data.amount0.unsigned_abs(), swap_data.amount1.unsigned_abs())
///         } else {
///             (swap_data.amount1.unsigned_abs(), swap_data.amount0.unsigned_abs())
///         };
///         Ok(V3SwapResult {
///             tx_hash,
///             sender: swap_data.sender,
///             recipient: swap_data.recipient,
///             amount_in,
///             amount_out,
///             sqrt_price_x96: swap_data.sqrt_price_x96,
///             liquidity: U128::from(swap_data.liquidity),
///             tick: swap_data.tick,
///         })
///     }
/// )?;
/// ```
#[tracing::instrument(skip(receipt, decode_fn), fields(
    tx_hash = ?receipt.transaction_hash,
    log_count = receipt.logs().len()
))]
pub fn find_event<F, R>(receipt: &TransactionReceipt, decode_fn: F) -> Result<R>
where
    F: Fn(&alloy::rpc::types::Log, TxHash) -> Result<R>,
{
    let tx_hash = receipt.transaction_hash;
    info!(
        tx_hash = ?tx_hash,
        log_count = receipt.logs().len(),
        "Processing transaction logs"
    );

    for log in receipt.logs() {
        match decode_fn(log, tx_hash) {
            Ok(result) => {
                info!(
                    tx_hash = ?tx_hash,
                    "Event decoded successfully"
                );
                return Ok(result);
            }
            Err(e) => {
                trace!(error = ?e, "Log is not a matching event, skipping");
                continue;
            }
        }
    }

    error!(
        tx_hash = ?tx_hash,
        log_count = receipt.logs().len(),
        "No matching event found in transaction receipt"
    );
    Err(anyhow::anyhow!("No matching event found in transaction receipt"))
}

/// Find and decode events from transaction receipt logs using a decoder
///
/// This function applies a decoder function to all logs and collects all
/// successful results. For each log in the receipt, it attempts to decode using
/// the provided decoder function, collecting all successful decodings into an
/// array.
///
/// This function:
/// 1. Iterates through all logs in the transaction receipt
/// 2. For each log, attempts to decode using the decoder function
/// 3. Collects all successful results into a vector
/// 4. Returns the vector of all successfully decoded events
///
/// # Arguments
///
/// * `receipt` - The transaction receipt containing logs
/// * `decoder` - A decoder function that attempts to decode a log
///
/// # Returns
///
/// Returns a vector of result type `R` containing all successfully decoded
/// events. Returns an error if no events are found.
///
/// # Example
///
/// ```ignore
/// use waterpump_evm_pool_sdk::pool_swappers::v3::decoder::decode_swap_event_to_result;
///
/// let swap_results = find_events(
///     &receipt,
///     |log, tx_hash| decode_swap_event_to_result(log, tx_hash, is_to_b)
/// )?;
/// // swap_results is a Vec<R> containing all successfully decoded events
/// ```
#[tracing::instrument(skip(receipt, decoder), fields(
    tx_hash = ?receipt.transaction_hash,
    log_count = receipt.logs().len()
))]
pub fn find_events<F, R>(receipt: &TransactionReceipt, decoder: F) -> Result<Vec<R>>
where
    F: Fn(&alloy::rpc::types::Log, TxHash) -> Result<R>,
{
    let tx_hash = receipt.transaction_hash;
    info!(
        tx_hash = ?tx_hash,
        log_count = receipt.logs().len(),
        "Processing transaction logs with decoder"
    );

    let mut results = Vec::new();

    for log in receipt.logs() {
        match decoder(log, tx_hash) {
            Ok(result) => {
                info!(
                    tx_hash = ?tx_hash,
                    "Event decoded successfully"
                );
                results.push(result);
            }
            Err(e) => {
                trace!(
                    error = ?e,
                    "Failed to decode log, skipping"
                );
                continue;
            }
        }
    }

    if results.is_empty() {
        error!(
            tx_hash = ?tx_hash,
            log_count = receipt.logs().len(),
            "No matching event found in transaction receipt"
        );
        Err(anyhow::anyhow!("No matching event found in transaction receipt"))
    } else {
        info!(
            tx_hash = ?tx_hash,
            result_count = results.len(),
            "Found {} events using decoder",
            results.len()
        );
        Ok(results)
    }
}

/// Merge two swap results from a two-hop swap into a single result
///
/// This function combines two swap results representing a two-hop swap:
/// - First swap: input token -> intermediate token (is_to_intermediate = true)
/// - Second swap: intermediate token -> output token (is_to_intermediate =
///   false)
///
/// The merged result represents the complete two-hop swap with:
/// - Total input amount from the first swap
/// - Total output amount from the second swap
/// - Final pool state (sqrt_price_x96, liquidity, tick) from the second swap
///
/// # Arguments
///
/// * `swap_results` - A vector containing exactly 2 swap results with
///   intermediate flags
/// * `tx_hash` - The transaction hash for the merged result
///
/// # Returns
///
/// Returns a merged `V3SwapResult` representing the complete two-hop swap.
/// Returns an error if the vector doesn't contain exactly 2 swap results or if
/// the intermediate flags don't identify first and second hops correctly.
///
/// # Example
///
/// ```ignore
/// let swap_results = find_events(&receipt, &decoder)?;
/// let merged_result = merge_two_hop_swap_results(swap_results, receipt.transaction_hash)?;
/// ```
#[tracing::instrument(skip(swap_results), fields(
    tx_hash = ?tx_hash,
    swap_count = swap_results.len()
))]
pub fn merge_two_hop_swap_results(
    swap_results: Vec<V3SwapWithIntermediateResult>,
    tx_hash: TxHash,
) -> Result<V3SwapResult> {
    if swap_results.len() < 2 {
        error!(
            tx_hash = ?tx_hash,
            found_events = swap_results.len(),
            "Expected 2 swap events for two-hop swap, found {}",
            swap_results.len()
        );
        return Err(anyhow::anyhow!(
            "Expected 2 swap events for two-hop swap, found {}",
            swap_results.len()
        ));
    }

    // Identify first and second swaps using is_to_intermediate flag
    // First swap: is_to_intermediate = true (input token -> intermediate token)
    // Second swap: is_to_intermediate = false (intermediate token -> output token)
    let (first_swap, second_swap) = if swap_results[0].is_to_intermediate {
        if swap_results[1].is_to_intermediate {
            error!(
                tx_hash = ?tx_hash,
                "Both swap results have is_to_intermediate = true, expected one true and one false"
            );
            return Err(anyhow::anyhow!(
                "Both swap results have is_to_intermediate = true, expected one true and one false"
            ));
        }
        (&swap_results[0], &swap_results[1])
    } else {
        if !swap_results[1].is_to_intermediate {
            error!(
                tx_hash = ?tx_hash,
                "Both swap results have is_to_intermediate = false, expected one true and one false"
            );
            return Err(anyhow::anyhow!(
                "Both swap results have is_to_intermediate = false, expected one true and one \
                 false"
            ));
        }
        (&swap_results[1], &swap_results[0])
    };

    // The total amount_in is from the first swap
    // The total amount_out is from the second swap
    // Use the final state (sqrt_price_x96, liquidity, tick) from the second swap
    info!(
        tx_hash = ?tx_hash,
        first_amount_in = ?first_swap.amount_in,
        first_amount_out = ?first_swap.amount_out,
        second_amount_in = ?second_swap.amount_in,
        second_amount_out = ?second_swap.amount_out,
        first_is_to_intermediate = first_swap.is_to_intermediate,
        second_is_to_intermediate = second_swap.is_to_intermediate,
        "Merging two-hop swap results"
    );

    Ok(V3SwapResult {
        sender: first_swap.sender,
        recipient: second_swap.recipient,
        amount_in: first_swap.amount_in.clone(),
        amount_out: second_swap.amount_out.clone(),
        sqrt_price_x96: second_swap.sqrt_price_x96,
        liquidity: second_swap.liquidity,
        tick: second_swap.tick,
        tx_hash,
    })
}