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
use std::collections::HashSet;

use alloy::{
    network::Ethereum,
    primitives::{Address, U256},
    providers::DynProvider,
};
use anyhow::{Context, Result};
use async_trait::async_trait;
use tracing::{debug, info, instrument};
use uniswap_sdk_core::prelude::{BigInt, Currency, CurrencyAmount, ToBig};

use crate::{
    pool_swappers::common::{
        build_transaction_with_gas_prices, send_and_wait_for_transaction, MethodParameters,
    },
    traits::pool_harvester::{
        HarvestFeesAndRewardsParams, HarvestFeesAndRewardsResult, HarvestPositionResult,
        HarvestQuoteData, PoolHarvester,
    },
};

/// Shadow (Ramses V3) Pool Harvester implementation
#[derive(Clone)]
pub struct ShadowPoolHarvester {
    pub position_manager_address: Address,
    pub voter_address: Address,
    pub sender_address: Address,
    pub chain_id: u64,
    pub provider: DynProvider<Ethereum>,
}

impl ShadowPoolHarvester {
    /// Create a new Shadow pool harvester
    pub fn new(
        position_manager_address: Address,
        voter_address: Address,
        sender_address: Address,
        chain_id: u64,
        provider: DynProvider<Ethereum>,
    ) -> Self {
        Self { position_manager_address, voter_address, sender_address, chain_id, provider }
    }

    /// Get the sender address
    pub fn sender_address(&self) -> Address { self.sender_address }

    /// Get the position manager address
    pub fn position_manager_address(&self) -> Address { self.position_manager_address }

    /// Get the voter address
    pub fn voter_address(&self) -> Address { self.voter_address }

    /// Get the chain ID
    pub fn chain_id(&self) -> u64 { self.chain_id }
}

#[async_trait]
impl PoolHarvester for ShadowPoolHarvester {
    #[instrument(skip(self), fields(
        position_manager_address = ?self.position_manager_address,
        token_ids_count = token_ids.len()
    ))]
    async fn get_quote_data(&self, token_ids: &[U256]) -> Result<Vec<HarvestQuoteData>> {
        info!("Getting quote data for {} Shadow positions", token_ids.len());

        if token_ids.is_empty() {
            return Ok(Vec::new());
        }

        // Get positions for all token_ids
        let positions = waterpump_evm_shadow_client::common::position::get_positions(
            &self.provider,
            self.position_manager_address,
            token_ids,
            None,
        )
        .await
        .context("Failed to get positions")?;

        // Get reward quotes using shadow-lib
        use std::collections::{HashMap, HashSet};

        use waterpump_evm_shadow_client::common::reward;

        // Prepare gauge rewards items
        let items = reward::prepare_gauge_rewards_items(
            &self.provider,
            self.voter_address,
            &positions,
            token_ids,
        )
        .await
        .context("Failed to prepare gauge rewards items")?;

        // Quote rewards
        let reward_quotes = if !items.is_empty() {
            reward::quote_rewards(&self.provider, &items, None)
                .await
                .context("Failed to quote rewards")?
        } else {
            Vec::new()
        };

        // Build a map of (token_id, reward_token) -> amount for efficient lookup
        let mut reward_map: HashMap<(U256, Address), U256> = HashMap::new();
        for quote in &reward_quotes {
            let key = (quote.token_id, quote.token);
            *reward_map.entry(key).or_insert(U256::ZERO) += quote.amount;
        }

        let mut quote_data = Vec::with_capacity(token_ids.len());

        for (token_id, position_data) in token_ids.iter().zip(positions.iter()) {
            // Get Currency objects from token addresses
            let currencies = waterpump_evm_uniswap_v3_client::get_currencies(
                &self.provider,
                &[position_data.token0, position_data.token1],
                self.chain_id,
            )
            .await
            .context("Failed to get currencies")?;

            let token0 = currencies.first().context("Expected token0 currency")?.clone();
            let token1 = currencies.get(1).context("Expected token1 currency")?.clone();

            // Get fees from position data (tokensOwed0 and tokensOwed1)
            let fee_amount0 = CurrencyAmount::from_raw_amount(
                token0.clone(),
                BigInt::from(position_data.tokensOwed0),
            )
            .context("Failed to create CurrencyAmount for token0 fees")?;
            let fee_amount1 = CurrencyAmount::from_raw_amount(
                token1.clone(),
                BigInt::from(position_data.tokensOwed1),
            )
            .context("Failed to create CurrencyAmount for token1 fees")?;

            // Sum up rewards for this position (if any reward tokens match token0 or
            // token1) For now, we only include fees in the quote. Rewards are
            // separate tokens. The total harvestable amount is fees + rewards,
            // but rewards are in different tokens. We'll return fees as
            // amount0/amount1, and rewards would need to be handled separately.

            // Get reward amounts for this position from reward_quotes
            let position_rewards: Vec<_> = reward_quotes
                .iter()
                .filter(|q| q.token_id == *token_id && q.amount > U256::ZERO)
                .collect();

            let reward_amounts = if !position_rewards.is_empty() {
                // Get unique reward token addresses for this position
                let reward_token_addresses: Vec<Address> = position_rewards
                    .iter()
                    .map(|q| q.token)
                    .collect::<HashSet<_>>()
                    .into_iter()
                    .collect();

                // Get Currency objects for reward tokens
                let reward_currencies = waterpump_evm_uniswap_v3_client::get_currencies(
                    &self.provider,
                    &reward_token_addresses,
                    self.chain_id,
                )
                .await
                .context("Failed to get currencies for reward tokens")?;

                // Create a map from token address to Currency
                let mut token_to_currency: HashMap<Address, Currency> = HashMap::new();
                for (addr, currency) in reward_token_addresses.iter().zip(reward_currencies.iter())
                {
                    token_to_currency.insert(*addr, currency.clone());
                }

                // Convert quotes to CurrencyAmount, grouping by token
                let mut reward_map: HashMap<Address, U256> = HashMap::new();
                for quote in position_rewards {
                    *reward_map.entry(quote.token).or_insert(U256::ZERO) += quote.amount;
                }

                // Convert to Vec<CurrencyAmount>
                let mut reward_amounts_vec = Vec::new();
                for (token_addr, total_amount) in reward_map {
                    if let Some(currency) = token_to_currency.get(&token_addr) {
                        if let Ok(amount) = CurrencyAmount::from_raw_amount(
                            currency.clone(),
                            total_amount.to_big_int(),
                        ) {
                            reward_amounts_vec.push(amount);
                        }
                    }
                }

                if reward_amounts_vec.is_empty() {
                    None
                } else {
                    Some(reward_amounts_vec)
                }
            } else {
                None
            };

            quote_data.push(HarvestQuoteData {
                token_id: *token_id,
                amount0: fee_amount0,
                amount1: fee_amount1,
                reward_amounts,
            });
        }

        debug!(
            num_quotes = quote_data.len(),
            "Retrieved quote data for {} Shadow positions",
            quote_data.len()
        );

        Ok(quote_data)
    }

    #[instrument(skip(self), fields(
        position_manager_address = ?self.position_manager_address,
        token_ids_count = params.token_ids.len(),
        recipient = ?params.recipient
    ))]
    async fn harvest_fees_and_rewards(
        &self,
        params: HarvestFeesAndRewardsParams,
    ) -> Result<HarvestFeesAndRewardsResult> {
        info!("Harvesting fees and rewards for {} Shadow positions", params.token_ids.len());

        if params.token_ids.is_empty() {
            return Err(anyhow::anyhow!("No token IDs provided for harvest"));
        }

        // For Shadow, we need to:
        // 1. Collect fees using position manager's collect function (batch via
        //    multicall)
        // 2. Claim rewards using voter contract's claimRewards function
        // We'll do both in separate transactions

        // First, collect fees for all positions using multicall
        use waterpump_evm_shadow_client::transactions::claim_rewards::claim_rewards;

        // Build claim rewards transaction using shadow-lib
        let claim_tx = claim_rewards(
            &self.provider,
            self.voter_address,
            self.position_manager_address,
            self.sender_address,
            &params.token_ids,
        )
        .await
        .context("Failed to build claim rewards transaction")?;

        // Convert claim rewards transaction input to bytes
        let claim_rewards_calldata: alloy::primitives::Bytes = claim_tx
            .request
            .input
            .into_input()
            .ok_or(anyhow::anyhow!("Failed to convert TransactionInput to Bytes"))?;

        // Now send reward claiming transaction
        let reward_method_params = MethodParameters {
            calldata: claim_rewards_calldata,
            value: claim_tx.request.value.unwrap_or_default(),
        };

        let reward_tx = build_transaction_with_gas_prices(
            &self.provider,
            self.sender_address,
            self.voter_address,
            reward_method_params,
            None::<crate::types::swap_params::GasPriceOptions>,
        )
        .await?;

        let reward_receipt = send_and_wait_for_transaction(
            &self.provider,
            reward_tx,
            Some(std::time::Duration::from_secs(60)),
            None::<fn(Box<dyn std::fmt::Display + Send + Sync>) -> anyhow::Error>,
        )
        .await?;

        info!(
            tx_hash = ?reward_receipt.transaction_hash,
            block_number = ?reward_receipt.block_number,
            gas_used = ?reward_receipt.gas_used,
            status = ?reward_receipt.status(),
            "Reward claiming transaction confirmed"
        );

        if !reward_receipt.status() {
            return Err(anyhow::anyhow!("Reward claiming transaction failed"));
        }

        // Build results from claim_tx quotes
        let positions = waterpump_evm_shadow_client::common::position::get_positions(
            &self.provider,
            self.position_manager_address,
            &params.token_ids,
            None,
        )
        .await
        .context("Failed to get positions for results")?;

        // Extract reward amounts from claim_tx.quote, grouped by position ID
        use std::collections::HashMap;

        // Group quotes by position ID and token address
        let mut position_rewards: HashMap<U256, HashMap<Address, U256>> = HashMap::new();
        for quote in &claim_tx.quote {
            if params.token_ids.contains(&quote.token_id) && quote.amount > U256::ZERO {
                let position_map = position_rewards.entry(quote.token_id).or_default();
                *position_map.entry(quote.token).or_insert(U256::ZERO) += quote.amount;
            }
        }

        // Get unique reward token addresses across all positions
        let all_reward_tokens: Vec<Address> = position_rewards
            .values()
            .flat_map(|reward_map| reward_map.keys())
            .copied()
            .collect::<HashSet<_>>()
            .into_iter()
            .collect();

        // Get Currency objects for all reward tokens (batch fetch)
        let reward_currencies = if !all_reward_tokens.is_empty() {
            waterpump_evm_uniswap_v3_client::get_currencies(
                &self.provider,
                &all_reward_tokens,
                self.chain_id,
            )
            .await
            .context("Failed to get currencies for reward tokens")?
        } else {
            Vec::new()
        };

        // Create a map from token address to Currency
        let mut token_to_currency: HashMap<Address, Currency> = HashMap::new();
        for (addr, currency) in all_reward_tokens.iter().zip(reward_currencies.iter()) {
            token_to_currency.insert(*addr, currency.clone());
        }

        // Build results for each position
        let mut results = Vec::new();
        for (token_id, position_data) in params.token_ids.iter().zip(positions.iter()) {
            // Get Currency objects from token addresses
            let currencies = waterpump_evm_uniswap_v3_client::get_currencies(
                &self.provider,
                &[position_data.token0, position_data.token1],
                self.chain_id,
            )
            .await
            .context("Failed to get currencies for results")?;

            let token0 = currencies.first().context("Expected token0 currency")?.clone();
            let token1 = currencies.get(1).context("Expected token1 currency")?.clone();

            // Get reward amounts for this position from claim_tx
            let reward_amounts = if let Some(reward_map) = position_rewards.get(token_id) {
                // Convert to Vec<CurrencyAmount>
                let mut reward_amounts_vec = Vec::new();
                for (token_addr, total_amount) in reward_map {
                    if let Some(currency) = token_to_currency.get(token_addr) {
                        if let Ok(amount) = CurrencyAmount::from_raw_amount(
                            currency.clone(),
                            total_amount.to_big_int(),
                        ) {
                            reward_amounts_vec.push(amount);
                        }
                    }
                }

                if reward_amounts_vec.is_empty() {
                    None
                } else {
                    Some(reward_amounts_vec)
                }
            } else {
                None
            };

            // Create result with zero fees (since we only claimed rewards)
            results.push(HarvestPositionResult {
                token_id: *token_id,
                amount0: CurrencyAmount::from_raw_amount(token0, BigInt::from(0))
                    .context("Failed to create CurrencyAmount for token0")?,
                amount1: CurrencyAmount::from_raw_amount(token1, BigInt::from(0))
                    .context("Failed to create CurrencyAmount for token1")?,
                reward_amounts,
            });
        }

        debug!(
            reward_tx_hash = ?reward_receipt.transaction_hash,
            "Rewards claimed for {} positions",
            params.token_ids.len()
        );

        Ok(HarvestFeesAndRewardsResult {
            results,
            tx_hash: reward_receipt.transaction_hash,
            receipt: reward_receipt,
        })
    }
}