evm-dex-pool 1.2.2

Reusable EVM DEX pool implementations (UniswapV2, UniswapV3, ERC4626) with traits and math
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
use crate::contracts::{IUniswapV2Pair, IV2PairUint256};
use crate::pool::base::{EventApplicable, PoolInterface, PoolTypeTrait, TopicList};
use crate::pool::PoolType;
use alloy::sol_types::SolEvent;
use alloy::{
    primitives::{Address, FixedBytes, U256},
    rpc::types::Log,
};
use anyhow::{anyhow, Result};
use log::{debug, trace};
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::fmt;

const FEE_DENOMINATOR: u128 = 1000000;
const EXP18: u128 = 1_000_000_000_000_000_000;

/// Enum representing the type of V2 pool
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum V2PoolType {
    UniswapV2,
    Stable,
}

/// UniswapV2 Pool implementation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UniswapV2Pool {
    /// Pool type
    pub pool_type: V2PoolType,
    /// Pool address
    pub address: Address,
    /// First token address in the pool
    pub token0: Address,
    /// Second token address in the pool
    pub token1: Address,
    /// Decimals of token0
    pub decimals0: u128,
    /// Decimals of token1
    pub decimals1: u128,
    /// Reserve of token0
    pub reserve0: U256,
    /// Reserve of token1
    pub reserve1: U256,
    /// Pool fee (e.g., 0.003 for 0.3%)
    pub fee: U256,
    /// Last update timestamp
    pub last_updated: u64,
    /// Creation timestamp or block
    pub created_at: u64,
}

impl UniswapV2Pool {
    /// Create a new V2 pool
    pub fn new(
        pool_type: V2PoolType,
        address: Address,
        token0: Address,
        token1: Address,
        decimals_0: u8,
        decimals_1: u8,
        reserve0: U256,
        reserve1: U256,
        fee: U256,
    ) -> Self {
        let current_time = chrono::Utc::now().timestamp() as u64;
        Self {
            pool_type,
            address,
            token0,
            token1,
            decimals0: 10_u128.pow(decimals_0 as u32),
            decimals1: 10_u128.pow(decimals_1 as u32),
            reserve0,
            reserve1,
            fee,
            last_updated: current_time,
            created_at: current_time,
        }
    }

    /// Update pool reserves
    pub fn update_reserves(&mut self, reserve0: U256, reserve1: U256) -> Result<()> {
        self.reserve0 = reserve0;
        self.reserve1 = reserve1;
        self.last_updated = chrono::Utc::now().timestamp() as u64;
        Ok(())
    }

    /// Calculate the constant product k = x * y
    pub fn constant_product(&self) -> U256 {
        self.reserve0 * self.reserve1
    }

    /// Get the exp18 value
    pub fn exp18() -> U256 {
        U256::from(EXP18)
    }

    /// Check if the pool is valid (has non-zero reserves)
    pub fn is_valid(&self) -> bool {
        !self.reserve0.is_zero() && !self.reserve1.is_zero()
    }

    /// Calculate the output amount for a swap (token0 -> token1)
    fn calculate_output_0_to_1(&self, amount_in: U256) -> Result<U256> {
        if amount_in.is_zero() {
            return Err(anyhow!("Input amount cannot be zero"));
        }

        if !self.is_valid() {
            return Err(anyhow!("Pool reserves are invalid"));
        }
        match self.pool_type {
            V2PoolType::UniswapV2 => {
                let amount_in_with_fee: alloy::primitives::Uint<256, 4> =
                    amount_in.saturating_mul(U256::from(U256::from(FEE_DENOMINATOR) - (self.fee)));
                let numerator = amount_in_with_fee * self.reserve1;
                let denominator = self.reserve0 * U256::from(FEE_DENOMINATOR) + amount_in_with_fee;
                let output = numerator / denominator;
                if output >= self.reserve1 {
                    return Err(anyhow!("Insufficient liquidity for swap"));
                }
                Ok(output)
            }
            V2PoolType::Stable => self.calculate_stable_output(amount_in, true),
        }
    }

    /// Calculate the output amount for a swap (token1 -> token0)
    fn calculate_output_1_to_0(&self, amount_in: U256) -> Result<U256> {
        if amount_in.is_zero() {
            return Err(anyhow!("Input amount cannot be zero"));
        }

        if !self.is_valid() {
            return Err(anyhow!("Pool reserves are invalid"));
        }

        match self.pool_type {
            V2PoolType::UniswapV2 => {
                let amount_in_with_fee =
                    amount_in.saturating_mul(U256::from(U256::from(FEE_DENOMINATOR) - (self.fee)));
                let numerator = amount_in_with_fee * self.reserve0;
                let denominator = self.reserve1 * U256::from(FEE_DENOMINATOR) + amount_in_with_fee;
                let output = numerator / denominator;
                if output >= self.reserve0 {
                    return Err(anyhow!("Insufficient liquidity for swap"));
                }
                Ok(output)
            }
            V2PoolType::Stable => self.calculate_stable_output(amount_in, false),
        }
    }

    /// Unified stable swap output calculation (R7 refactoring)
    fn calculate_stable_output(&self, amount_in: U256, zero_for_one: bool) -> Result<U256> {
        let amount_in_with_fee: alloy::primitives::Uint<256, 4> = amount_in
            .saturating_mul(U256::from(U256::from(FEE_DENOMINATOR) - (self.fee)))
            .checked_div(U256::from(FEE_DENOMINATOR))
            .unwrap();
        let exp18 = Self::exp18();
        let xy = self.k(self.reserve0, self.reserve1);
        let reserve0 = (self.reserve0 * exp18) / U256::from(self.decimals0);
        let reserve1 = (self.reserve1 * exp18) / U256::from(self.decimals1);

        let (reserve_a, reserve_b, decimals_in, decimals_out) = if zero_for_one {
            (reserve0, reserve1, self.decimals0, self.decimals1)
        } else {
            (reserve1, reserve0, self.decimals1, self.decimals0)
        };

        let amount_in_parsed = (amount_in_with_fee * exp18) / U256::from(decimals_in);
        let y = reserve_b - self.get_y(amount_in_parsed + reserve_a, xy, reserve_b)?;
        let output = (y * U256::from(decimals_out)) / exp18;

        Ok(output)
    }

    fn k(&self, x: U256, y: U256) -> U256 {
        if self.pool_type == V2PoolType::Stable {
            let exp18 = Self::exp18();
            let _x = (x * exp18) / U256::from(self.decimals0);
            let _y = (y * exp18) / U256::from(self.decimals1);
            let _a = (_x * _y) / exp18;
            let _b = (_x * _x) / exp18 + (_y * _y) / exp18;
            return (_a * _b) / exp18; // x3y+y3x >= k
        } else {
            return x * y;
        }
    }

    pub fn f(x0: U256, y: U256) -> U256 {
        let exp18 = Self::exp18();
        let _a = (x0 * y) / exp18;
        let _b = (x0 * x0) / exp18 + (y * y) / exp18;
        return (_a * _b) / exp18;
    }

    fn d(x0: U256, y: U256) -> U256 {
        let exp18 = Self::exp18();
        return (U256::from(3) * x0 * ((y * y) / exp18)) / exp18
            + ((((x0 * x0) / exp18) * x0) / exp18);
    }

    fn get_y(&self, x0: U256, xy: U256, mut y: U256) -> Result<U256> {
        let exp18 = Self::exp18();
        for _ in 0..255 {
            let k = Self::f(x0, y);
            if k < xy {
                let mut dy = ((xy - k) * exp18) / Self::d(x0, y);
                if dy.is_zero() {
                    if k == xy {
                        return Ok(y);
                    }
                    if self.k(x0, y + U256::ONE) > xy {
                        return Ok(y + U256::ONE);
                    }
                    dy = U256::ONE;
                }
                y = y + dy;
            } else {
                let mut dy = ((k - xy) * exp18) / Self::d(x0, y);
                if dy.is_zero() {
                    if k == xy || Self::f(x0, y - U256::ONE) < xy {
                        return Ok(y);
                    }
                    dy = U256::ONE;
                }
                y = y - dy;
            }
        }
        return Err(anyhow!("!y"));
    }

    fn calculate_input_0_to_1(&self, amount_out: U256) -> Result<U256> {
        if amount_out.is_zero() {
            return Err(anyhow!("Output amount cannot be zero"));
        }
        if !self.is_valid() {
            return Err(anyhow!("Pool reserves are invalid"));
        }
        if amount_out >= self.reserve1 {
            return Err(anyhow!("Insufficient liquidity for swap"));
        }
        let numerator = self.reserve0 * amount_out * U256::from(FEE_DENOMINATOR);
        let denominator = (self.reserve1 - amount_out) * (U256::from(FEE_DENOMINATOR) - self.fee);
        let input = (numerator / denominator) + U256::from(1);
        Ok(input)
    }

    fn calculate_input_1_to_0(&self, amount_out: U256) -> Result<U256> {
        if amount_out.is_zero() {
            return Err(anyhow!("Output amount cannot be zero"));
        }
        if !self.is_valid() {
            return Err(anyhow!("Pool reserves are invalid"));
        }
        if amount_out >= self.reserve0 {
            return Err(anyhow!("Insufficient liquidity for swap"));
        }
        let numerator = self.reserve1 * amount_out * U256::from(FEE_DENOMINATOR);
        let denominator = (self.reserve0 - amount_out) * (U256::from(FEE_DENOMINATOR) - self.fee);
        let input = (numerator / denominator) + U256::from(1);
        Ok(input)
    }
}

impl PoolInterface for UniswapV2Pool {
    fn calculate_output(&self, token_in: &Address, amount_in: U256) -> Result<U256> {
        if token_in == &self.token0 {
            self.calculate_output_0_to_1(amount_in)
        } else if token_in == &self.token1 {
            self.calculate_output_1_to_0(amount_in)
        } else {
            Err(anyhow!("Token not in pool"))
        }
    }

    fn calculate_input(&self, token_out: &Address, amount_out: U256) -> Result<U256> {
        if token_out == &self.token0 {
            self.calculate_input_1_to_0(amount_out)
        } else if token_out == &self.token1 {
            self.calculate_input_0_to_1(amount_out)
        } else {
            Err(anyhow!("Token not in pool"))
        }
    }

    fn apply_swap(&mut self, token_in: &Address, amount_in: U256, amount_out: U256) -> Result<()> {
        if token_in == &self.token0 {
            if amount_out >= self.reserve1 {
                return Err(anyhow!("Insufficient liquidity for swap"));
            }
            self.reserve0 += amount_in;
            self.reserve1 -= amount_out;
        } else if token_in == &self.token1 {
            if amount_out >= self.reserve0 {
                return Err(anyhow!("Insufficient liquidity for swap"));
            }
            self.reserve1 += amount_in;
            self.reserve0 -= amount_out;
        } else {
            return Err(anyhow!("Token not in pool"));
        }
        self.last_updated = chrono::Utc::now().timestamp() as u64;
        Ok(())
    }

    fn address(&self) -> Address {
        self.address
    }

    fn tokens(&self) -> (Address, Address) {
        (self.token0, self.token1)
    }

    fn fee(&self) -> f64 {
        self.fee.to::<u128>() as f64 / FEE_DENOMINATOR as f64
    }

    fn fee_raw(&self) -> u64 {
        self.fee.to::<u128>() as u64
    }

    fn id(&self) -> String {
        format!("v2-{}-{}-{}", self.address, self.token0, self.token1)
    }

    fn log_summary(&self) -> String {
        format!(
            "V2 Pool {} - {} <> {} (reserves: {}, {})",
            self.address, self.token0, self.token1, self.reserve0, self.reserve1
        )
    }

    fn contains_token(&self, token: &Address) -> bool {
        *token == self.token0 || *token == self.token1
    }

    fn clone_box(&self) -> Box<dyn PoolInterface + Send + Sync> {
        Box::new(self.clone())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

impl EventApplicable for UniswapV2Pool {
    fn apply_log(&mut self, log: &Log) -> Result<()> {
        match log.topic0() {
            Some(&IUniswapV2Pair::Sync::SIGNATURE_HASH) => {
                let sync_data: IUniswapV2Pair::Sync = log.log_decode()?.inner.data;
                debug!(
                    "Applying V2Sync event to pool {}: reserve0={}, reserve1={}",
                    self.address, sync_data.reserve0, sync_data.reserve1
                );
                self.update_reserves(
                    U256::from(sync_data.reserve0),
                    U256::from(sync_data.reserve1),
                )?;
                Ok(())
            }
            Some(&IV2PairUint256::Sync::SIGNATURE_HASH) => {
                let sync_data: IV2PairUint256::Sync = log.log_decode()?.inner.data;
                debug!(
                    "Applying V2Sync event to pool {}: reserve0={}, reserve1={}",
                    self.address, sync_data.reserve0, sync_data.reserve1
                );
                self.update_reserves(sync_data.reserve0, sync_data.reserve1)?;
                Ok(())
            }
            Some(&IUniswapV2Pair::Swap::SIGNATURE_HASH) => Ok(()),
            _ => {
                trace!("Ignoring unknown event for V2 pool");
                Ok(())
            }
        }
    }
}

impl TopicList for UniswapV2Pool {
    fn topics() -> Vec<FixedBytes<32>> {
        vec![
            IUniswapV2Pair::Swap::SIGNATURE_HASH,
            IUniswapV2Pair::Sync::SIGNATURE_HASH,
            IV2PairUint256::Sync::SIGNATURE_HASH,
        ]
    }

    fn profitable_topics() -> Vec<FixedBytes<32>> {
        vec![IUniswapV2Pair::Swap::SIGNATURE_HASH]
    }
}

impl fmt::Display for UniswapV2Pool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "V2 Pool {} - {} <> {} (reserves: {}, {})",
            self.address, self.token0, self.token1, self.reserve0, self.reserve1
        )
    }
}

impl PoolTypeTrait for UniswapV2Pool {
    fn pool_type(&self) -> PoolType {
        PoolType::UniswapV2
    }
}