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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
//! V3 Pool Maker implementation
//!
//! This implementation treats Uniswap V3 concentrated liquidity positions as
//! limit orders:
//! - Place order = Mint a single-tick range position
//! - Fulfill order = Remove liquidity when price crosses through the tick
//! - Cancel order = Burn the position

use alloy::{
    eips::BlockId,
    network::Ethereum,
    primitives::{aliases::I24, Address, TxHash, U256},
    providers::DynProvider,
};
use anyhow::Result;
use async_trait::async_trait;
use tracing::{debug, info, instrument};
use uniswap_sdk_core::{
    entities::BaseCurrency,
    prelude::{Currency, CurrencyAmount, Price, ToBig},
};

use crate::{
    impl_pool_base, impl_position_viewer_helpers, impl_token_helper, impl_v3_pool_infuser,
    impl_v3_pool_state, impl_v3_pool_viewer,
    pool_makers::common::{can_fulfill_order_range, can_place_order_range},
    traits::{
        pool_infuser::{
            AddLiquidityOptions, AddLiquidityParams, AddLiquiditySpecificOptions,
            MintSpecificOptions, PoolInfuser, RemoveLiquidityOptions, RemoveLiquidityParams,
        },
        pool_maker::{
            CancelBatchOrdersResult, CancelOrderResult, CancelOrderResultItem,
            FulfillBatchOrdersResult, FulfillOrderOptions, FulfillOrderParams, FulfillOrderResult,
            OrderInfo, OrderMetadata, OrderPriceRange, OrderSide, PlaceBatchOrdersResult,
            PlaceOrderOptions, PlaceOrderParams, PlaceOrderResult, PoolMaker, PositionInfo,
            PriceCheckInput, PriceCheckResult, PricePlaceableResult, RestrictedPriceRange,
        },
        pool_state::PoolState,
        pool_viewer::PoolViewer,
    },
    types::v3_pool_key::V3PoolKey,
};

/// V3 Pool Maker - implements limit orders using concentrated liquidity
/// positions
///
/// In Uniswap V3, we can simulate limit orders by:
/// - Creating single-tick range positions (tick_lower to tick_lower +
///   tick_spacing)
/// - When price crosses through the tick, the position becomes filled
/// - The position can be removed to collect the swapped tokens
#[derive(Clone, Debug)]
pub struct V3PoolMaker {
    pub pool_key: V3PoolKey,
    pub pool_address: Address,
    pub position_manager_address: Address,
    pub sender_address: Address,
    /// Tick spacing for the pool (determines minimum order price granularity)
    pub tick_spacing: i32,
    /// Number of tick spacings that an order spans (defaults to 1)
    /// This determines the width of the liquidity position for each limit order
    pub order_tick_count: i32,
    /// Whether token_a is the base currency (true) or token_b is the base
    /// currency (false)
    pub is_token_a_base: bool,
    pub provider: DynProvider<Ethereum>,
}

impl V3PoolMaker {
    #[instrument(skip(pool_key), fields(
        pool_address = ?pool_address,
        position_manager_address = ?position_manager_address,
        token_a = ?pool_key.token_a.address(),
        token_b = ?pool_key.token_b.address(),
        fee = ?pool_key.fee,
        sender_address = ?sender_address,
        is_token_a_base = is_token_a_base
    ))]
    pub fn new(
        pool_key: V3PoolKey,
        pool_address: Address,
        position_manager_address: Address,
        sender_address: Address,
        tick_spacing: i32,
        is_token_a_base: bool,
        provider: DynProvider<Ethereum>,
    ) -> Self {
        Self::new_with_order_tick_count(
            pool_key,
            pool_address,
            position_manager_address,
            sender_address,
            tick_spacing,
            2, // Default to 2 tick spacing per order
            is_token_a_base,
            provider,
        )
    }

    #[allow(clippy::too_many_arguments)]
    pub fn new_with_order_tick_count(
        pool_key: V3PoolKey,
        pool_address: Address,
        position_manager_address: Address,
        sender_address: Address,
        tick_spacing: i32,
        order_tick_count: i32,
        is_token_a_base: bool,
        provider: DynProvider<Ethereum>,
    ) -> Self {
        debug!(
            pool_address = ?pool_address,
            position_manager_address = ?position_manager_address,
            tick_spacing = tick_spacing,
            order_tick_count = order_tick_count,
            is_token_a_base = is_token_a_base,
            "Creating V3PoolMaker"
        );
        Self {
            pool_key,
            pool_address,
            position_manager_address,
            sender_address,
            tick_spacing,
            order_tick_count,
            is_token_a_base,
            provider,
        }
    }

    /// Check if token_a is the base currency
    pub fn is_token_a_base(&self) -> bool { self.is_token_a_base }

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

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

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

    /// Get the pool key
    pub fn pool_key(&self) -> &V3PoolKey { &self.pool_key }

    /// Get the tick spacing
    pub fn tick_spacing(&self) -> i32 { self.tick_spacing }

    /// Get the order tick count (number of tick spacings per order)
    pub fn order_tick_count(&self) -> i32 { self.order_tick_count }

    /// Get tick range for a limit order at a specific tick
    pub fn get_order_tick_range(&self, order_tick: i32, side: OrderSide) -> Result<(I24, I24)> {
        // Round to tick spacing for valid position
        let rounded_tick = (order_tick / self.tick_spacing) * self.tick_spacing;
        let rounded_tick_i24 = I24::try_from(rounded_tick)?;

        // Calculate the tick span and half span for centering
        let order_tick_span = self.tick_spacing * self.order_tick_count;
        let half_span = order_tick_span / 2;
        let half_span_i24 = I24::try_from(half_span)?;

        // Center the range around the rounded tick
        let tick_lower = rounded_tick_i24 - half_span_i24;
        let tick_upper = rounded_tick_i24 + half_span_i24;

        match side {
            // Buy order: place liquidity below current price
            // When price drops to this level, we buy base currency
            OrderSide::Buy => Ok((tick_lower, tick_upper)),
            // Sell order: place liquidity above current price
            // When price rises to this level, we sell base currency
            OrderSide::Sell => Ok((tick_lower, tick_upper)),
        }
    }

    fn get_order_tick_range_checked(
        &self,
        current_tick: i32,
        order_tick: i32,
        side: OrderSide,
    ) -> Result<(I24, I24)> {
        let restricted_range = self.get_restricted_tick_range(current_tick)?;
        let (tick_lower, tick_upper) = self.get_order_tick_range(order_tick, side)?;
        let tick_lower_i32 = tick_lower.as_i32();
        let tick_upper_i32 = tick_upper.as_i32();

        // Use can_place_order_range to check if the order range can be safely placed
        if !self.can_place_order_range(&restricted_range, tick_lower_i32, tick_upper_i32, side) {
            return Err(anyhow::anyhow!(
                "Order range [{}, {}) cannot be placed: it overlaps with restricted range [{}, \
                 {}) for {:?} order",
                tick_lower_i32,
                tick_upper_i32,
                restricted_range.tick_lower,
                restricted_range.tick_upper,
                side
            ));
        }

        Ok((tick_lower, tick_upper))
    }

    /// Check if an order can be fulfilled based on current tick, position tick
    /// range, and order side
    ///
    /// For limit orders:
    /// - Buy order: can be fulfilled when position is below restricted range
    ///   (price dropped)
    /// - Sell order: can be fulfilled when position is above restricted range
    ///   (price rose)
    ///
    /// This considers `is_token_a_base` for proper tick direction handling.
    pub fn can_fulfill_order(
        &self,
        current_tick: i32,
        tick_lower: i32,
        tick_upper: i32,
        order_side: OrderSide,
    ) -> Result<bool> {
        let restricted_range = self.get_restricted_tick_range(current_tick)?;

        Ok(self.can_fulfill_order_range(&restricted_range, tick_lower, tick_upper, order_side))
    }

    /// Check if an order range can be fulfilled based on restricted price range
    ///
    /// Delegates to the common `can_fulfill_order_range` function.
    pub fn can_fulfill_order_range(
        &self,
        restricted_range: &RestrictedPriceRange,
        tick_lower: i32,
        tick_upper: i32,
        order_side: OrderSide,
    ) -> bool {
        can_fulfill_order_range(
            restricted_range,
            tick_lower,
            tick_upper,
            order_side,
            self.is_token_a_base,
        )
    }

    /// Check if an order range can be safely placed based on restricted price
    /// range
    ///
    /// Delegates to the common `can_place_order_range` function.
    pub fn can_place_order_range(
        &self,
        restricted_range: &RestrictedPriceRange,
        tick_lower: i32,
        tick_upper: i32,
        order_side: OrderSide,
    ) -> bool {
        can_place_order_range(
            restricted_range,
            tick_lower,
            tick_upper,
            order_side,
            self.is_token_a_base,
        )
    }

    /// Get the restricted tick range around the current tick
    fn get_restricted_tick_range(&self, current_tick: i32) -> Result<RestrictedPriceRange> {
        let tick_lower = (current_tick / self.tick_spacing) * self.tick_spacing - self.tick_spacing;
        let tick_upper = tick_lower + 2 * self.tick_spacing;

        let lower_price_i24 = I24::try_from(tick_lower)?;
        let upper_price_i24 = I24::try_from(tick_upper)?;

        let lower_price = self.tick_to_base_price(lower_price_i24)?;
        let upper_price = self.tick_to_base_price(upper_price_i24)?;

        Ok(RestrictedPriceRange { lower_price, upper_price, tick_lower, tick_upper })
    }

    /// Convert a tick to base price (price of base currency in terms of quote
    /// currency)
    ///
    /// This considers `is_token_a_base`:
    /// - If token_a is base: returns token_a price in terms of token_b (normal
    ///   tick_to_price)
    /// - If token_b is base: returns token_b price in terms of token_a
    ///   (inverted)
    pub fn tick_to_base_price(&self, tick: I24) -> Result<Price<Currency, Currency>> {
        let price = self.tick_to_price(tick)?;

        if self.is_token_a_base {
            // token_a is base, price is already base/quote
            Ok(price)
        } else {
            // token_b is base, need to invert the price
            Ok(price.invert())
        }
    }

    /// Convert a base price to the closest tick
    ///
    /// This considers `is_token_a_base`:
    /// - If token_a is base: converts directly using price_to_closest_tick
    /// - If token_b is base: inverts the price first, then converts
    pub fn base_price_to_closest_tick(&self, price: &Price<Currency, Currency>) -> Result<I24> {
        let pool_price = if self.is_token_a_base {
            // token_a is base, price is base/quote = token_a/token_b
            price.clone()
        } else {
            // token_b is base, price is base/quote = token_b/token_a
            // Need to invert to get token_a/token_b for tick calculation
            price.invert()
        };

        // Use the helper from impl_position_viewer_helpers
        self.price_to_closest_tick(pool_price)
    }

    /// Calculate amount0 and amount1 for a limit order based on is_token_a_base
    /// and order side
    ///
    /// For limit orders, we provide liquidity in one token only:
    /// - Buy order: provide quote currency to receive base currency when price
    ///   drops
    /// - Sell order: provide base currency to receive quote currency when price
    ///   rises
    pub fn get_order_amounts(
        &self,
        base_amount: &CurrencyAmount<Currency>,
        price: &Price<Currency, Currency>,
        side: OrderSide,
    ) -> Result<(CurrencyAmount<Currency>, CurrencyAmount<Currency>)> {
        // Calculate quote amount from base amount using the order price
        let quote_amount = price.quote(base_amount)?;

        match (self.is_token_a_base, side) {
            // token_a is base, Buy: provide token_b (quote), receive token_a (base)
            (true, OrderSide::Buy) => Ok((
                CurrencyAmount::from_raw_amount(self.pool_key.token_a.clone(), 0)?,
                quote_amount,
            )),
            // token_a is base, Sell: provide token_a (base), receive token_b (quote)
            (true, OrderSide::Sell) => Ok((
                base_amount.clone(),
                CurrencyAmount::from_raw_amount(self.pool_key.token_b.clone(), 0)?,
            )),
            // token_b is base, Buy: provide token_a (quote), receive token_b (base)
            (false, OrderSide::Buy) => Ok((
                quote_amount,
                CurrencyAmount::from_raw_amount(self.pool_key.token_b.clone(), 0)?,
            )),
            // token_b is base, Sell: provide token_b (base), receive token_a (quote)
            (false, OrderSide::Sell) => Ok((
                CurrencyAmount::from_raw_amount(self.pool_key.token_a.clone(), 0)?,
                base_amount.clone(),
            )),
        }
    }

    /// Calculate position info from raw position data
    ///
    /// This helper function handles the common logic for calculating token
    /// amounts and building `PositionInfo` from position data.
    #[allow(clippy::too_many_arguments)]
    fn calculate_position_info(
        &self,
        token_id: U256,
        tick_lower: i32,
        tick_upper: i32,
        liquidity: u128,
        tokens_owed0: u128,
        tokens_owed1: u128,
        sqrt_price_x96: alloy::primitives::aliases::U160,
    ) -> Result<PositionInfo> {
        use waterpump_evm_amm_math::{
            sqrt_price_math::{get_amount_0_delta, get_amount_1_delta},
            tick_math::{get_sqrt_ratio_at_tick, get_tick_at_sqrt_ratio},
        };

        let sqrt_ratio_lower = get_sqrt_ratio_at_tick(tick_lower)?;
        let sqrt_ratio_upper = get_sqrt_ratio_at_tick(tick_upper)?;

        // Get current tick from sqrt ratio
        let sqrt_price_u256 = U256::from(sqrt_price_x96);
        let current_tick = get_tick_at_sqrt_ratio(sqrt_price_u256)?;

        // Calculate amounts based on current tick position
        let (amount0_raw, amount1_raw) = if current_tick < tick_lower {
            // Position is entirely below current price - only token0
            let amount0 = get_amount_0_delta(sqrt_ratio_lower, sqrt_ratio_upper, liquidity, true)?;
            (amount0, U256::ZERO)
        } else if current_tick < tick_upper {
            // Position spans current price - both tokens
            let amount0 = get_amount_0_delta(sqrt_price_u256, sqrt_ratio_upper, liquidity, true)?;
            let amount1 = get_amount_1_delta(sqrt_ratio_lower, sqrt_price_u256, liquidity, true)?;
            (amount0, amount1)
        } else {
            // Position is entirely above current price - only token1
            let amount1 = get_amount_1_delta(sqrt_ratio_lower, sqrt_ratio_upper, liquidity, true)?;
            (U256::ZERO, amount1)
        };

        // Convert to CurrencyAmount
        let amount0 = CurrencyAmount::from_raw_amount(
            self.pool_key.token_a.clone(),
            amount0_raw.to_big_int(),
        )?;
        let amount1 = CurrencyAmount::from_raw_amount(
            self.pool_key.token_b.clone(),
            amount1_raw.to_big_int(),
        )?;

        // Get fees owed
        let fees_owed0 = CurrencyAmount::from_raw_amount(
            self.pool_key.token_a.clone(),
            U256::from(tokens_owed0).to_big_int(),
        )?;
        let fees_owed1 = CurrencyAmount::from_raw_amount(
            self.pool_key.token_b.clone(),
            U256::from(tokens_owed1).to_big_int(),
        )?;

        Ok(PositionInfo {
            token_id,
            tick_lower,
            tick_upper,
            liquidity,
            amount0,
            amount1,
            fees_owed0,
            fees_owed1,
        })
    }
}

impl_pool_base!(V3PoolMaker);
impl_token_helper!(V3PoolMaker);
impl_v3_pool_viewer!(V3PoolMaker);
impl_v3_pool_state!(V3PoolMaker);
impl_v3_pool_infuser!(V3PoolMaker);
impl_position_viewer_helpers!(V3PoolMaker);

#[async_trait]
impl PoolMaker for V3PoolMaker {
    fn base_currency(&self) -> Currency {
        if self.is_token_a_base {
            self.pool_key.token_a.clone()
        } else {
            self.pool_key.token_b.clone()
        }
    }

    fn quote_currency(&self) -> Currency {
        if self.is_token_a_base {
            self.pool_key.token_b.clone()
        } else {
            self.pool_key.token_a.clone()
        }
    }

    #[instrument(skip(self, params, options), fields(
        position_manager_address = ?self.position_manager_address(),
        side = ?params.side,
        amount = ?params.base_amount
    ))]
    async fn place_order(
        &self,
        params: PlaceOrderParams,
        options: PlaceOrderOptions,
    ) -> Result<PlaceOrderResult> {
        let currency0_price = PoolViewer::currency0_price(self, None).await?;

        // Check if order tick is valid (not within restricted range)
        let current_tick = self.price_to_closest_tick(currency0_price.clone())?.as_i32();
        let order_tick = self.base_price_to_closest_tick(&params.price)?.as_i32();
        let (tick_lower, tick_upper) =
            self.get_order_tick_range_checked(current_tick, order_tick, params.side)?;

        // Determine amount0 and amount1 based on is_token_a_base and order side
        let (amount0, amount1) =
            self.get_order_amounts(&params.base_amount, &params.price, params.side)?;

        let add_liquidity_params = AddLiquidityParams {
            amount0,
            amount1,
            tick_upper,
            tick_lower,
            token0_price: currency0_price,
            specific_opts: AddLiquiditySpecificOptions::Mint(MintSpecificOptions {
                recipient: params.recipient,
                create_pool: false,
            }),
        };

        let add_liquidity_options = AddLiquidityOptions {
            slippage_tolerance: options.slippage_tolerance,
            deadline: params.deadline,
            use_native: None,
            token0_permit: None,
            token1_permit: None,
        };

        // Use PoolInfuser::add_liquidity
        let result =
            PoolInfuser::add_liquidity(self, add_liquidity_params, add_liquidity_options).await?;

        let timestamp = chrono::Utc::now().timestamp();

        Ok(PlaceOrderResult {
            token_id: result.token_id,
            tx_hash: result.tx_hash,
            price: params.price,
            base_amount: params.base_amount,
            side: params.side,
            tick_lower: tick_lower.as_i32(),
            tick_upper: tick_upper.as_i32(),
            timestamp,
        })
    }

    #[instrument(skip(self, params, options), fields(
        position_manager_address = ?self.position_manager_address(),
        num_orders = params.items.len()
    ))]
    async fn place_batch_orders(
        &self,
        params: crate::traits::pool_maker::PlaceBatchOrdersParams,
        options: PlaceOrderOptions,
    ) -> Result<PlaceBatchOrdersResult> {
        use crate::traits::{
            pool_infuser::{AddBatchLiquidityItem, AddBatchLiquidityParams, AddLiquidityOptions},
            pool_maker::PlaceOrderResultItem,
        };

        if params.items.is_empty() {
            return Ok(PlaceBatchOrdersResult {
                tx_hash: TxHash::default(),
                orders: Vec::new(),
                timestamp: chrono::Utc::now().timestamp(),
            });
        }

        // Get current price and tick once for all orders
        let currency0_price = PoolViewer::currency0_price(self, None).await?;
        let current_tick = self.price_to_closest_tick(currency0_price.clone())?.as_i32();

        // Build batch liquidity items and store tick ranges
        let mut batch_items = Vec::with_capacity(params.items.len());
        let mut tick_ranges = Vec::with_capacity(params.items.len());
        for item in &params.items {
            let order_tick = self.base_price_to_closest_tick(&item.price)?.as_i32();
            let (tick_lower, tick_upper) =
                self.get_order_tick_range_checked(current_tick, order_tick, item.side)?;

            // Store tick ranges for later use in result mapping
            tick_ranges.push((tick_lower.as_i32(), tick_upper.as_i32()));

            let (amount0, amount1) =
                self.get_order_amounts(&item.base_amount, &item.price, item.side)?;

            batch_items.push(AddBatchLiquidityItem {
                amount0,
                amount1,
                tick_upper,
                tick_lower,
                specific_opts: AddLiquiditySpecificOptions::Mint(MintSpecificOptions {
                    recipient: params.recipient,
                    create_pool: false,
                }),
            });
        }

        let batch_params =
            AddBatchLiquidityParams { token0_price: currency0_price, items: batch_items };

        let batch_options = AddLiquidityOptions {
            slippage_tolerance: options.slippage_tolerance,
            deadline: params.deadline,
            use_native: None,
            token0_permit: None,
            token1_permit: None,
        };

        // Execute batch add liquidity
        let result = PoolInfuser::add_batch_liquidity(self, batch_params, batch_options).await?;

        let timestamp = chrono::Utc::now().timestamp();

        // Map results to PlaceOrderResultItem
        let orders: Vec<PlaceOrderResultItem> = result
            .results
            .into_iter()
            .zip(params.items.iter())
            .zip(tick_ranges.iter())
            .map(|((add_result, item), (tick_lower, tick_upper))| PlaceOrderResultItem {
                token_id: add_result.token_id,
                price: item.price.clone(),
                base_amount: item.base_amount.clone(),
                side: item.side,
                tick_lower: *tick_lower,
                tick_upper: *tick_upper,
            })
            .collect();

        Ok(PlaceBatchOrdersResult { tx_hash: result.tx_hash, orders, timestamp })
    }

    #[instrument(skip(self, params, options), fields(
        position_manager_address = ?self.position_manager_address(),
        token_id = ?params.order_metadata.token_id,
        order_side = ?params.order_metadata.order_side
    ))]
    async fn fulfill_order(
        &self,
        params: FulfillOrderParams,
        options: FulfillOrderOptions,
    ) -> Result<FulfillOrderResult> {
        let currency0_price = PoolViewer::currency0_price(self, None).await?;

        // Get position data using get_position
        let position = PoolMaker::get_position(self, params.order_metadata.token_id, None).await?;

        debug!(
            token_id = ?params.order_metadata.token_id,
            liquidity = ?position.liquidity,
            tick_lower = ?position.tick_lower,
            tick_upper = ?position.tick_upper,
            "Position data retrieved for fulfill order"
        );

        // Check if the order can be fulfilled (price has crossed through the position's
        // tick range)
        let current_tick = self.price_to_closest_tick(currency0_price.clone())?.as_i32();

        if !self.can_fulfill_order(
            current_tick,
            position.tick_lower,
            position.tick_upper,
            params.order_metadata.order_side,
        )? {
            return Err(anyhow::anyhow!(
                "Order cannot be fulfilled yet. Current tick {} has not crossed through position \
                 range [{}, {}) for {:?} order. Buy orders require price to drop below, sell \
                 orders require price to rise above.",
                current_tick,
                position.tick_lower,
                position.tick_upper,
                params.order_metadata.order_side
            ));
        }

        let tick_lower_i24 = I24::try_from(position.tick_lower)?;
        let tick_upper_i24 = I24::try_from(position.tick_upper)?;

        let remove_params = RemoveLiquidityParams {
            token_id: params.order_metadata.token_id,
            liquidity: U256::from(position.liquidity),
            recipient: params.recipient,
            deadline: params.deadline,
            token0_price: currency0_price.clone(),
            tick_lower: tick_lower_i24,
            tick_upper: tick_upper_i24,
        };

        let remove_options = RemoveLiquidityOptions {
            slippage_tolerance: options.slippage_tolerance,
            burn_token: true,
            permit: None,
            collect_options: Default::default(),
        };

        // Use PoolInfuser::remove_liquidity
        let result = PoolInfuser::remove_liquidity(self, remove_params, remove_options).await?;

        let timestamp = chrono::Utc::now().timestamp();

        // Determine base and quote amounts based on is_token_a_base
        let (base_amount, quote_amount) = if self.is_token_a_base {
            (result.amount0, result.amount1)
        } else {
            (result.amount1, result.amount0)
        };

        let fulfill_price = self.tick_to_base_price(tick_lower_i24)?;

        Ok(FulfillOrderResult {
            token_id: params.order_metadata.token_id,
            tx_hash: result.tx_hash,
            fully_filled: true,
            base_amount,
            quote_amount,
            fill_price: fulfill_price,
            fee: None,
            tick_lower: position.tick_lower,
            tick_upper: position.tick_upper,
            timestamp,
        })
    }

    #[instrument(skip(self, params, options), fields(
        position_manager_address = ?self.position_manager_address(),
        num_orders = params.items.len()
    ))]
    async fn fulfill_batch_orders(
        &self,
        params: crate::traits::pool_maker::FulfillBatchOrdersParams,
        options: FulfillOrderOptions,
    ) -> Result<FulfillBatchOrdersResult> {
        use crate::traits::{
            pool_infuser::{
                RemoveBatchLiquidityItem, RemoveBatchLiquidityParams, RemoveLiquidityOptions,
            },
            pool_maker::FulfillOrderResultItem,
        };

        if params.items.is_empty() {
            return Ok(FulfillBatchOrdersResult {
                tx_hash: TxHash::default(),
                orders: Vec::new(),
                timestamp: chrono::Utc::now().timestamp(),
            });
        }

        // Get current price and tick
        let currency0_price = PoolViewer::currency0_price(self, None).await?;
        let current_tick = self.price_to_closest_tick(currency0_price.clone())?.as_i32();

        // Get all positions using multicall
        let token_ids: Vec<U256> =
            params.items.iter().map(|item| item.order_metadata.token_id).collect();

        let positions = PoolMaker::get_positions(self, &token_ids, None).await?;

        // Validate all orders can be fulfilled and build batch items
        let mut batch_items = Vec::with_capacity(params.items.len());
        for (item, position) in params.items.iter().zip(positions.iter()) {
            // Check if the order can be fulfilled
            if !self.can_fulfill_order(
                current_tick,
                position.tick_lower,
                position.tick_upper,
                item.order_metadata.order_side,
            )? {
                return Err(anyhow::anyhow!(
                    "Order {} cannot be fulfilled yet. Current tick {} has not crossed through \
                     position range [{}, {}) for {:?} order.",
                    item.order_metadata.token_id,
                    current_tick,
                    position.tick_lower,
                    position.tick_upper,
                    item.order_metadata.order_side
                ));
            }

            let tick_lower_i24 = I24::try_from(position.tick_lower)?;
            let tick_upper_i24 = I24::try_from(position.tick_upper)?;

            batch_items.push(RemoveBatchLiquidityItem {
                token_id: item.order_metadata.token_id,
                liquidity: U256::from(position.liquidity),
                tick_lower: tick_lower_i24,
                tick_upper: tick_upper_i24,
                burn_token: true,
            });
        }

        let batch_params = RemoveBatchLiquidityParams {
            recipient: params.recipient,
            deadline: params.deadline,
            token0_price: currency0_price.clone(),
            items: batch_items,
        };

        let batch_options = RemoveLiquidityOptions {
            slippage_tolerance: options.slippage_tolerance,
            burn_token: true,
            permit: None,
            collect_options: Default::default(),
        };

        // Execute batch remove liquidity
        let result = PoolInfuser::remove_batch_liquidity(self, batch_params, batch_options).await?;

        let timestamp = chrono::Utc::now().timestamp();

        // Map results to FulfillOrderResultItem
        let orders: Vec<FulfillOrderResultItem> = result
            .results
            .into_iter()
            .zip(params.items.iter())
            .zip(positions.iter())
            .map(|((remove_result, item), position)| {
                // Determine base and quote amounts based on is_token_a_base
                let (base_amount, quote_amount) = if self.is_token_a_base {
                    (remove_result.amount0, remove_result.amount1)
                } else {
                    (remove_result.amount1, remove_result.amount0)
                };

                let tick_lower_i24 = I24::try_from(position.tick_lower).unwrap_or_default();
                let fill_price =
                    self.tick_to_base_price(tick_lower_i24).unwrap_or(currency0_price.clone());

                FulfillOrderResultItem {
                    token_id: item.order_metadata.token_id,
                    fully_filled: true,
                    base_amount,
                    quote_amount,
                    fill_price,
                    fee: None,
                    tick_lower: position.tick_lower,
                    tick_upper: position.tick_upper,
                }
            })
            .collect();

        Ok(FulfillBatchOrdersResult { tx_hash: result.tx_hash, orders, timestamp })
    }

    #[instrument(skip(self), fields(token_id = ?order_metadata.token_id, order_side = ?order_metadata.order_side))]
    async fn get_order(&self, order_metadata: OrderMetadata) -> Result<Option<OrderInfo>> {
        // TODO: Query position from NonfungiblePositionManager
        // This requires calling positions(tokenId) on the contract
        debug!(token_id = ?order_metadata.token_id, order_side = ?order_metadata.order_side, "get_order not yet fully implemented");
        Ok(None)
    }

    #[instrument(skip(self), fields(token_id = ?token_id))]
    async fn get_position(
        &self,
        token_id: U256,
        block_id: Option<BlockId>,
    ) -> Result<PositionInfo> {
        // Query position data from NonfungiblePositionManager
        let position_manager = uniswap_lens::bindings::iuniswapv3nonfungiblepositionmanager::IUniswapV3NonfungiblePositionManager::IUniswapV3NonfungiblePositionManagerInstance::new(
            self.position_manager_address(),
            self.provider.clone(),
        );
        let position_data = position_manager.positions(token_id).call().await?;

        // Get current sqrt price to calculate amounts
        let sqrt_price_x96 = PoolState::sqrt_price_x96(self, block_id).await?;

        self.calculate_position_info(
            token_id,
            position_data.tickLower.as_i32(),
            position_data.tickUpper.as_i32(),
            position_data.liquidity,
            position_data.tokensOwed0,
            position_data.tokensOwed1,
            sqrt_price_x96,
        )
    }

    #[instrument(skip(self, token_ids), fields(num_positions = token_ids.len()))]
    async fn get_positions(
        &self,
        token_ids: &[U256],
        block_id: Option<BlockId>,
    ) -> Result<Vec<PositionInfo>> {
        if token_ids.is_empty() {
            return Ok(Vec::new());
        }

        // Setup multicall for position data
        let position_manager = uniswap_lens::bindings::iuniswapv3nonfungiblepositionmanager::IUniswapV3NonfungiblePositionManager::IUniswapV3NonfungiblePositionManagerInstance::new(
            self.position_manager_address(),
            self.provider.clone(),
        );

        let mut multicall = alloy::providers::Provider::multicall(&self.provider).dynamic();
        for token_id in token_ids {
            multicall = multicall.add_dynamic(position_manager.positions(*token_id));
        }

        let block_id = block_id.unwrap_or(BlockId::latest());
        let position_data = multicall.block(block_id).aggregate().await?;

        // Get current sqrt price to calculate amounts
        let sqrt_price_x96 = PoolState::sqrt_price_x96(self, Some(block_id)).await?;

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

        for (token_id, pos_data) in token_ids.iter().zip(position_data.iter()) {
            let position_info = self.calculate_position_info(
                *token_id,
                pos_data.tickLower.as_i32(),
                pos_data.tickUpper.as_i32(),
                pos_data.liquidity,
                pos_data.tokensOwed0,
                pos_data.tokensOwed1,
                sqrt_price_x96,
            )?;
            results.push(position_info);
        }

        debug!(num_positions = results.len(), "Fetched positions via multicall");
        Ok(results)
    }

    #[instrument(skip(self, orders), fields(num_orders = orders.len()))]
    async fn get_orders(
        &self,
        orders: &[OrderMetadata],
        _block_id: Option<BlockId>,
    ) -> Result<Vec<OrderInfo>> {
        // TODO: Query positions from NonfungiblePositionManager
        debug!(num_orders = orders.len(), "get_orders not yet fully implemented");
        Ok(Vec::new())
    }

    #[instrument(skip(self, params), fields(token_id = ?params.token_id))]
    async fn cancel_order(
        &self,
        params: crate::traits::pool_maker::CancelOrderParams,
    ) -> Result<CancelOrderResult> {
        // Cancel order = remove all liquidity and burn the NFT
        let currency0_price = PoolViewer::currency0_price(self, None).await?;

        // Get position data using get_position
        let position = PoolMaker::get_position(self, params.token_id, None).await?;

        let tick_lower_i24 = I24::try_from(position.tick_lower)?;
        let tick_upper_i24 = I24::try_from(position.tick_upper)?;

        let remove_params = RemoveLiquidityParams {
            token_id: params.token_id,
            liquidity: U256::from(position.liquidity),
            recipient: params.recipient,
            deadline: params.deadline,
            token0_price: currency0_price,
            tick_lower: tick_lower_i24,
            tick_upper: tick_upper_i24,
        };

        let remove_options = RemoveLiquidityOptions {
            slippage_tolerance: params.slippage_tolerance,
            burn_token: true,
            permit: None,
            collect_options: Default::default(),
        };

        // Use PoolInfuser::remove_liquidity
        let result = PoolInfuser::remove_liquidity(self, remove_params, remove_options).await?;

        let timestamp = chrono::Utc::now().timestamp();

        info!(token_id = ?params.token_id, "Order cancelled successfully");

        Ok(CancelOrderResult {
            token_id: params.token_id,
            tx_hash: result.tx_hash,
            tick_lower: position.tick_lower,
            tick_upper: position.tick_upper,
            timestamp,
        })
    }

    #[instrument(skip(self, params), fields(num_orders = params.token_ids.len()))]
    async fn cancel_batch_orders(
        &self,
        params: crate::traits::pool_maker::CancelBatchOrdersParams,
    ) -> Result<CancelBatchOrdersResult> {
        use crate::traits::pool_infuser::{
            RemoveBatchLiquidityItem, RemoveBatchLiquidityParams, RemoveLiquidityOptions,
        };

        if params.token_ids.is_empty() {
            return Ok(CancelBatchOrdersResult {
                tx_hash: TxHash::default(),
                cancelled_orders: Vec::new(),
                timestamp: chrono::Utc::now().timestamp(),
            });
        }

        // Get current price
        let currency0_price = PoolViewer::currency0_price(self, None).await?;

        // Get all positions using multicall
        let positions = PoolMaker::get_positions(self, &params.token_ids, None).await?;

        // Build batch items
        let mut batch_items = Vec::with_capacity(params.token_ids.len());
        for (token_id, position) in params.token_ids.iter().zip(positions.iter()) {
            let tick_lower_i24 = I24::try_from(position.tick_lower)?;
            let tick_upper_i24 = I24::try_from(position.tick_upper)?;

            batch_items.push(RemoveBatchLiquidityItem {
                token_id: *token_id,
                liquidity: U256::from(position.liquidity),
                tick_lower: tick_lower_i24,
                tick_upper: tick_upper_i24,
                burn_token: true,
            });
        }

        let batch_params = RemoveBatchLiquidityParams {
            recipient: params.recipient,
            deadline: params.deadline,
            token0_price: currency0_price,
            items: batch_items,
        };

        let batch_options = RemoveLiquidityOptions {
            slippage_tolerance: params.slippage_tolerance,
            burn_token: true,
            permit: None,
            collect_options: Default::default(),
        };

        // Execute batch remove liquidity
        let result = PoolInfuser::remove_batch_liquidity(self, batch_params, batch_options).await?;

        let timestamp = chrono::Utc::now().timestamp();

        // Build cancelled orders with tick ranges
        let cancelled_orders: Vec<CancelOrderResultItem> = params
            .token_ids
            .iter()
            .zip(positions.iter())
            .map(|(token_id, position)| CancelOrderResultItem {
                token_id: *token_id,
                tick_lower: position.tick_lower,
                tick_upper: position.tick_upper,
            })
            .collect();

        info!(num_cancelled = params.token_ids.len(), "Batch orders cancelled successfully");

        Ok(CancelBatchOrdersResult { tx_hash: result.tx_hash, cancelled_orders, timestamp })
    }

    #[instrument(skip(self), fields(token_id = ?order_metadata.token_id, order_side = ?order_metadata.order_side))]
    async fn can_fulfill(
        &self,
        order_metadata: OrderMetadata,
        block_id: Option<BlockId>,
    ) -> Result<bool> {
        let currency0_price = PoolViewer::currency0_price(self, block_id).await?;
        // Get position data
        let position = PoolMaker::get_position(self, order_metadata.token_id, block_id).await?;

        // Convert current price to tick
        let current_tick = self.price_to_closest_tick(currency0_price.clone())?.as_i32();

        // Use precise check with order side
        let can_fulfill = self.can_fulfill_order(
            current_tick,
            position.tick_lower,
            position.tick_upper,
            order_metadata.order_side,
        )?;

        debug!(
            token_id = ?order_metadata.token_id,
            current_tick = current_tick,
            position_tick_lower = position.tick_lower,
            position_tick_upper = position.tick_upper,
            order_side = ?order_metadata.order_side,
            can_fulfill = can_fulfill,
            "can_fulfill check"
        );

        Ok(can_fulfill)
    }

    #[instrument(skip(self, current_price), fields(price = ?price_input.price, side = ?price_input.side))]
    fn check_price_fulfillable(
        &self,
        current_price: &Price<Currency, Currency>,
        price_input: PriceCheckInput,
    ) -> Result<PriceCheckResult> {
        // Use batch check for single price
        let prices = vec![price_input];
        let results = PoolMaker::check_prices_fulfillable(self, current_price, prices)?;
        Ok(results[0].clone())
    }

    #[instrument(skip(self, current_price), fields(count = prices.len()))]
    fn check_prices_fulfillable(
        &self,
        current_price: &Price<Currency, Currency>,
        prices: Vec<PriceCheckInput>,
    ) -> Result<Vec<PriceCheckResult>> {
        if prices.is_empty() {
            return Ok(vec![]);
        }

        // Convert current price to tick
        let current_tick = self.base_price_to_closest_tick(current_price)?.as_i32();

        // Get the restricted price range around current tick
        let restricted_range = PoolMaker::get_restricted_price_range(self, current_tick)?;

        // Check each price
        let mut results = Vec::with_capacity(prices.len());
        for price_input in prices {
            // Convert the input price to tick
            let order_tick = self.base_price_to_closest_tick(&price_input.price)?.as_i32();

            // Get the order tick range for this price and side
            let (tick_lower, tick_upper) =
                self.get_order_tick_range(order_tick, price_input.side)?;
            let tick_lower_i32 = tick_lower.as_i32();
            let tick_upper_i32 = tick_upper.as_i32();

            // Use can_fulfill_order_range to check if the order range is fulfillable
            let is_fulfillable = self.can_fulfill_order_range(
                &restricted_range,
                tick_lower_i32,
                tick_upper_i32,
                price_input.side,
            );

            results.push(PriceCheckResult {
                price: price_input.price,
                side: price_input.side,
                is_fulfillable,
            });
        }

        debug!(
            checked_count = results.len(),
            fulfillable_count = results.iter().filter(|r| r.is_fulfillable).count(),
            "check_prices_fulfillable completed"
        );

        Ok(results)
    }

    #[instrument(skip(self, current_price), fields(price = ?price_input.price, side = ?price_input.side))]
    fn check_price_placeable(
        &self,
        current_price: &Price<Currency, Currency>,
        price_input: PriceCheckInput,
    ) -> Result<PricePlaceableResult> {
        // Use batch check for single price
        let prices = vec![price_input];
        let results = PoolMaker::check_prices_placeable(self, current_price, prices)?;
        Ok(results[0].clone())
    }

    #[instrument(skip(self, current_price), fields(count = prices.len()))]
    fn check_prices_placeable(
        &self,
        current_price: &Price<Currency, Currency>,
        prices: Vec<PriceCheckInput>,
    ) -> Result<Vec<PricePlaceableResult>> {
        if prices.is_empty() {
            return Ok(vec![]);
        }

        // Convert current price to tick
        let current_tick = self.base_price_to_closest_tick(current_price)?.as_i32();

        // Get the restricted price range around current tick
        let restricted_range = PoolMaker::get_restricted_price_range(self, current_tick)?;

        // Check each price
        let mut results = Vec::with_capacity(prices.len());
        for price_input in prices {
            // Convert the input price to tick
            let order_tick = self.base_price_to_closest_tick(&price_input.price)?.as_i32();

            // Get the order tick range for this price and side
            let (tick_lower, tick_upper) =
                self.get_order_tick_range(order_tick, price_input.side)?;
            let tick_lower_i32 = tick_lower.as_i32();
            let tick_upper_i32 = tick_upper.as_i32();

            // Use can_place_order_range to check if the order range can be safely placed
            let is_placeable = self.can_place_order_range(
                &restricted_range,
                tick_lower_i32,
                tick_upper_i32,
                price_input.side,
            );

            results.push(PricePlaceableResult {
                price: price_input.price,
                side: price_input.side,
                is_placeable,
            });
        }

        debug!(
            checked_count = results.len(),
            placeable_count = results.iter().filter(|r| r.is_placeable).count(),
            "check_prices_placeable completed"
        );

        Ok(results)
    }

    #[instrument(skip(self))]
    async fn get_market_price(
        &self,
        block_id: Option<BlockId>,
    ) -> Result<Price<Currency, Currency>> {
        if self.is_token_a_base {
            // Base is token_a, return price of token_a in terms of token_b
            PoolViewer::currency0_price(self, block_id).await
        } else {
            // Base is token_b, return price of token_b in terms of token_a
            PoolViewer::currency1_price(self, block_id).await
        }
    }

    #[instrument(skip(self, price), fields(price = ?price, side = ?side))]
    fn get_order_price_range(
        &self,
        price: &Price<Currency, Currency>,
        side: OrderSide,
    ) -> Result<OrderPriceRange> {
        // Convert the price to the closest tick
        let order_tick = self.base_price_to_closest_tick(price)?.as_i32();

        // Get the tick range for this order
        let (tick_lower, tick_upper) = self.get_order_tick_range(order_tick, side)?;
        let tick_lower_i32 = tick_lower.as_i32();
        let tick_upper_i32 = tick_upper.as_i32();

        // Convert ticks back to prices
        let lower_price = self.tick_to_base_price(tick_lower)?;
        let upper_price = self.tick_to_base_price(tick_upper)?;

        Ok(OrderPriceRange {
            lower_price,
            upper_price,
            tick_lower: tick_lower_i32,
            tick_upper: tick_upper_i32,
            side,
        })
    }

    #[instrument(skip(self))]
    fn get_restricted_price_range(&self, current_tick: i32) -> Result<RestrictedPriceRange> {
        // Calculate tick boundaries based on tick spacing
        // The restricted range spans two tick spacings around the current price
        let tick_lower = (current_tick / self.tick_spacing) * self.tick_spacing - self.tick_spacing;
        let tick_upper = tick_lower + 2 * self.tick_spacing;

        // Convert ticks to prices using helper method from impl_position_viewer_helpers
        let tick_lower_i24 = I24::try_from(tick_lower)?;
        let tick_upper_i24 = I24::try_from(tick_upper)?;

        let lower_price = self.tick_to_base_price(tick_lower_i24)?;
        let upper_price = self.tick_to_base_price(tick_upper_i24)?;

        Ok(RestrictedPriceRange { lower_price, upper_price, tick_lower, tick_upper })
    }

    #[instrument(skip(self, _side, _amount), fields(side = ?_side, amount = ?_amount))]
    async fn estimate_execution_price(
        &self,
        _side: OrderSide,
        _amount: CurrencyAmount<Currency>,
        block_id: Option<BlockId>,
    ) -> Result<Price<Currency, Currency>> {
        // For now, return market price
        // TODO: Implement proper price impact estimation using quoter
        self.get_market_price(block_id).await
    }
}