penumbra_dex/component/
rpc.rs

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
use std::{pin::Pin, sync::Arc};

use anyhow::Result;
use async_stream::try_stream;
use futures::{StreamExt, TryStreamExt};
use tokio::sync::mpsc;
use tonic::Status;
use tracing::instrument;

use cnidarium::{StateDelta, Storage};
use penumbra_asset::{asset, Value};
use penumbra_proto::{
    core::component::dex::v1::{
        query_service_server::QueryService,
        simulate_trade_request::{
            routing::{self, Setting},
            Routing,
        },
        simulation_service_server::SimulationService,
        ArbExecutionRequest, ArbExecutionResponse, ArbExecutionsRequest, ArbExecutionsResponse,
        BatchSwapOutputDataRequest, BatchSwapOutputDataResponse, CandlestickDataRequest,
        CandlestickDataResponse, CandlestickDataStreamRequest, CandlestickDataStreamResponse,
        LiquidityPositionByIdRequest, LiquidityPositionByIdResponse, LiquidityPositionsByIdRequest,
        LiquidityPositionsByIdResponse, LiquidityPositionsByPriceRequest,
        LiquidityPositionsByPriceResponse, LiquidityPositionsRequest, LiquidityPositionsResponse,
        SimulateTradeRequest, SimulateTradeResponse, SpreadRequest, SpreadResponse,
        SwapExecutionRequest, SwapExecutionResponse, SwapExecutionsRequest, SwapExecutionsResponse,
    },
    DomainType, StateReadProto,
};

use super::ExecutionCircuitBreaker;
use crate::{
    component::metrics,
    lp::position::{self, Position},
    state_key, CandlestickData, DirectedTradingPair, SwapExecution, TradingPair,
};

use super::{chandelier::CandlestickRead, router::RouteAndFill, PositionRead, StateReadExt};

pub mod stub;

// TODO: Hide this and only expose a Router?
pub struct Server {
    storage: Storage,
}

impl Server {
    pub fn new(storage: Storage) -> Self {
        Self { storage }
    }
}

#[tonic::async_trait]
impl QueryService for Server {
    type LiquidityPositionsStream = Pin<
        Box<dyn futures::Stream<Item = Result<LiquidityPositionsResponse, tonic::Status>> + Send>,
    >;
    type LiquidityPositionsByPriceStream = Pin<
        Box<
            dyn futures::Stream<Item = Result<LiquidityPositionsByPriceResponse, tonic::Status>>
                + Send,
        >,
    >;
    type LiquidityPositionsByIdStream = Pin<
        Box<
            dyn futures::Stream<Item = Result<LiquidityPositionsByIdResponse, tonic::Status>>
                + Send,
        >,
    >;
    type ArbExecutionsStream =
        Pin<Box<dyn futures::Stream<Item = Result<ArbExecutionsResponse, tonic::Status>> + Send>>;
    type SwapExecutionsStream =
        Pin<Box<dyn futures::Stream<Item = Result<SwapExecutionsResponse, tonic::Status>> + Send>>;
    type CandlestickDataStreamStream = Pin<
        Box<
            dyn futures::Stream<Item = Result<CandlestickDataStreamResponse, tonic::Status>> + Send,
        >,
    >;

    #[instrument(skip(self, request))]
    async fn arb_execution(
        &self,
        request: tonic::Request<ArbExecutionRequest>,
    ) -> Result<tonic::Response<ArbExecutionResponse>, Status> {
        let state = self.storage.latest_snapshot();
        let request_inner = request.into_inner();
        let height = request_inner.height;

        let arb_execution = state
            .arb_execution(height)
            .await
            .map_err(|e| tonic::Status::internal(e.to_string()))?;

        match arb_execution {
            Some(arb_execution) => Ok(tonic::Response::new(ArbExecutionResponse {
                swap_execution: Some(arb_execution.into()),
                height,
            })),
            None => Err(Status::not_found("arb execution data not found")),
        }
    }

    #[instrument(skip(self, request))]
    async fn arb_executions(
        &self,
        request: tonic::Request<ArbExecutionsRequest>,
    ) -> Result<tonic::Response<Self::ArbExecutionsStream>, Status> {
        let state = self.storage.latest_snapshot();
        let request_inner = request.into_inner();
        let start_height = request_inner.start_height;
        let end_height = request_inner.end_height;

        let s = state.prefix(state_key::arb_executions());
        Ok(tonic::Response::new(
            s.filter_map(
                move |i: anyhow::Result<(String, SwapExecution)>| async move {
                    if i.is_err() {
                        return Some(Err(tonic::Status::unavailable(format!(
                            "error getting prefix value from storage: {}",
                            i.expect_err("i is_err")
                        ))));
                    }

                    let (key, arb_execution) = i.expect("i is Ok");
                    let height = key
                        .split('/')
                        .last()
                        .expect("arb execution key has height as last part")
                        .parse()
                        .expect("height is a number");

                    // TODO: would be great to start iteration at start_height
                    // and stop at end_height rather than touching _every_
                    // key, but the current storage implementation doesn't make this
                    // easy.
                    if height < start_height || height > end_height {
                        None
                    } else {
                        Some(Ok(ArbExecutionsResponse {
                            swap_execution: Some(arb_execution.into()),
                            height,
                        }))
                    }
                },
            )
            // TODO: how do we instrument a Stream
            //.instrument(Span::current())
            .boxed(),
        ))
    }

    #[instrument(skip(self, request))]
    /// Get the batch swap data associated with a given trading pair and height.
    async fn batch_swap_output_data(
        &self,
        request: tonic::Request<BatchSwapOutputDataRequest>,
    ) -> Result<tonic::Response<BatchSwapOutputDataResponse>, Status> {
        let state = self.storage.latest_snapshot();

        let request_inner = request.into_inner();
        let height = request_inner.height;
        let trading_pair = request_inner
            .trading_pair
            .ok_or_else(|| Status::invalid_argument("missing trading_pair"))?
            .try_into()
            .map_err(|_| Status::invalid_argument("invalid trading_pair"))?;

        let output_data = state
            .output_data(height, trading_pair)
            .await
            .map_err(|e| tonic::Status::internal(e.to_string()))?;

        match output_data {
            Some(data) => Ok(tonic::Response::new(BatchSwapOutputDataResponse {
                data: Some(data.into()),
            })),
            None => Err(Status::not_found("batch swap output data not found")),
        }
    }

    #[instrument(skip(self, request))]
    /// Get the batch swap data associated with a given trading pair and height.
    async fn swap_execution(
        &self,
        request: tonic::Request<SwapExecutionRequest>,
    ) -> Result<tonic::Response<SwapExecutionResponse>, Status> {
        let state = self.storage.latest_snapshot();
        let request_inner = request.into_inner();
        let height = request_inner.height;
        let trading_pair = request_inner
            .trading_pair
            .ok_or_else(|| Status::invalid_argument("missing trading_pair"))?
            .try_into()
            .map_err(|_| Status::invalid_argument("invalid trading_pair"))?;

        let swap_execution = state
            .swap_execution(height, trading_pair)
            .await
            .map_err(|e| tonic::Status::internal(e.to_string()))?;

        match swap_execution {
            Some(swap_execution) => Ok(tonic::Response::new(SwapExecutionResponse {
                swap_execution: Some(swap_execution.into()),
            })),
            None => Err(Status::not_found("batch swap output data not found")),
        }
    }

    #[instrument(skip(self, request))]
    async fn candlestick_data(
        &self,
        request: tonic::Request<CandlestickDataRequest>,
    ) -> Result<tonic::Response<CandlestickDataResponse>, Status> {
        let state = self.storage.latest_snapshot();
        // Limit the number of candlesticks returned to 20,000 (approximately 1 day)
        // to prevent the server from being overwhelmed by a single request.
        let limit = std::cmp::min(request.get_ref().limit, 20_000u64);
        let start_height = match request.get_ref().start_height {
            0 => {
                // If no start height is provided, go `limit` blocks back from now.
                let current_height = state.version();
                current_height.saturating_sub(limit)
            }
            start_height => start_height,
        };

        let pair: DirectedTradingPair = request
            .get_ref()
            .pair
            .clone()
            .ok_or_else(|| Status::invalid_argument("missing trading_pair"))?
            .try_into()
            .map_err(|_| Status::invalid_argument("invalid trading_pair"))?;

        let candlesticks = state
            .candlesticks(&pair, start_height, limit as usize)
            .await
            .map_err(|e| tonic::Status::internal(e.to_string()))?;

        Ok(tonic::Response::new(CandlestickDataResponse {
            data: candlesticks.into_iter().map(Into::into).collect(),
        }))
    }

    async fn candlestick_data_stream(
        &self,
        request: tonic::Request<CandlestickDataStreamRequest>,
    ) -> Result<tonic::Response<Self::CandlestickDataStreamStream>, Status> {
        let pair: DirectedTradingPair = request
            .get_ref()
            .pair
            .clone()
            .ok_or_else(|| Status::invalid_argument("missing trading_pair"))?
            .try_into()
            .map_err(|_| Status::invalid_argument("invalid trading_pair"))?;

        let (tx_candle, rx_candle) = mpsc::channel::<CandlestickData>(1);
        let storage = self.storage.clone();
        tokio::spawn(async move {
            // could add metrics here
            // let _guard = CandlestickDataStreamConnectionCounter::new();
            let mut rx_state_snapshot = storage.subscribe();
            loop {
                rx_state_snapshot
                    .changed()
                    .await
                    .expect("channel should be open");
                let snapshot = rx_state_snapshot.borrow().clone();
                let height = snapshot.version();
                match snapshot.get_candlestick(&pair, height).await? {
                    Some(candle) => tx_candle.send(candle).await?,
                    None => {
                        // If there's no candlestick data, might as well check that
                        // tx_candle is still open in case the client has disconnected.
                        if tx_candle.is_closed() {
                            break;
                        }
                    }
                }
            }
            Ok::<_, anyhow::Error>(())
        });

        Ok(tonic::Response::new(
            tokio_stream::wrappers::ReceiverStream::new(rx_candle)
                .map(|candle| {
                    Ok(CandlestickDataStreamResponse {
                        data: Some(candle.into()),
                    })
                })
                .boxed(),
        ))
    }

    #[instrument(skip(self, request))]
    async fn swap_executions(
        &self,
        request: tonic::Request<SwapExecutionsRequest>,
    ) -> Result<tonic::Response<Self::SwapExecutionsStream>, Status> {
        let state = self.storage.latest_snapshot();

        let request_inner = request.into_inner();
        let start_height = request_inner.start_height;
        let end_height = request_inner.end_height;
        let trading_pair = request_inner.trading_pair;

        // Convert to domain type ahead of time if necessary
        let trading_pair: Option<DirectedTradingPair> =
            trading_pair.map(|trading_pair| trading_pair.try_into().expect("invalid trading pair"));

        let s = state.nonverifiable_prefix(&state_key::swap_executions().as_bytes());
        Ok(tonic::Response::new(
            s.filter_map(move |i: anyhow::Result<(Vec<u8>, SwapExecution)>| {
                async move {
                    if i.is_err() {
                        return Some(Err(tonic::Status::unavailable(format!(
                            "error getting prefix value from storage: {}",
                            i.expect_err("i is_err")
                        ))));
                    }

                    let (key, swap_execution) = i.expect("i is Ok");

                    let key = std::str::from_utf8(&key)
                        .expect("state key for swap executions should be valid utf-8 string");

                    let parts = key.split('/').collect::<Vec<_>>();
                    let height = parts[2].parse().expect("height is not a number");
                    let asset_1: asset::Id =
                        parts[3].parse().expect("asset id formatted improperly");
                    let asset_2: asset::Id =
                        parts[4].parse().expect("asset id formatted improperly");

                    let swap_trading_pair = DirectedTradingPair::new(asset_1, asset_2);

                    if let Some(trading_pair) = trading_pair {
                        // filter by trading pair
                        if swap_trading_pair != trading_pair {
                            return None;
                        }
                    }

                    // TODO: would be great to start iteration at start_height
                    // and stop at end_height rather than touching _every_
                    // key, but the current storage implementation doesn't make this
                    // easy.
                    if height < start_height || height > end_height {
                        None
                    } else {
                        Some(Ok(SwapExecutionsResponse {
                            swap_execution: Some(swap_execution.into()),
                            height,
                            trading_pair: Some(swap_trading_pair.into()),
                        }))
                    }
                }
            })
            // TODO: how do we instrument a Stream
            //.instrument(Span::current())
            .boxed(),
        ))
    }

    async fn spread(
        &self,
        request: tonic::Request<SpreadRequest>,
    ) -> Result<tonic::Response<SpreadResponse>, Status> {
        let state = self.storage.latest_snapshot();
        let request = request.into_inner();

        let pair: TradingPair = request
            .trading_pair
            .ok_or_else(|| tonic::Status::invalid_argument("missing trading pair"))?
            .try_into()
            .map_err(|e| {
                tonic::Status::invalid_argument(format!("error parsing trading pair: {:#}", e))
            })?;

        let pair12 = DirectedTradingPair {
            start: pair.asset_1(),
            end: pair.asset_2(),
        };
        let pair21 = DirectedTradingPair {
            start: pair.asset_2(),
            end: pair.asset_1(),
        };
        let best_1_to_2_position = state
            .best_position(&pair12)
            .await
            .map_err(|e| {
                tonic::Status::internal(format!(
                    "error finding best position for {:?}: {:#}",
                    pair12, e
                ))
            })?
            .map(|(_, p)| p);
        let best_2_to_1_position = state
            .best_position(&pair12)
            .await
            .map_err(|e| {
                tonic::Status::internal(format!(
                    "error finding best position for {:?}: {:#}",
                    pair21, e
                ))
            })?
            .map(|(_, p)| p);

        let approx_effective_price_1_to_2 = best_1_to_2_position
            .as_ref()
            .map(|p| {
                p.phi
                    .orient_start(pair.asset_1())
                    .expect("position has one end = asset 1")
                    .effective_price()
                    .into()
            })
            .unwrap_or_default();

        let approx_effective_price_2_to_1 = best_2_to_1_position
            .as_ref()
            .map(|p| {
                p.phi
                    .orient_start(pair.asset_2())
                    .expect("position has one end = asset 2")
                    .effective_price()
                    .into()
            })
            .unwrap_or_default();

        Ok(tonic::Response::new(SpreadResponse {
            best_1_to_2_position: best_1_to_2_position.map(Into::into),
            best_2_to_1_position: best_2_to_1_position.map(Into::into),
            approx_effective_price_1_to_2,
            approx_effective_price_2_to_1,
        }))
    }

    #[instrument(skip(self, request))]
    async fn liquidity_positions_by_price(
        &self,
        request: tonic::Request<LiquidityPositionsByPriceRequest>,
    ) -> Result<tonic::Response<Self::LiquidityPositionsByPriceStream>, Status> {
        let state = self.storage.latest_snapshot();
        let request = request.into_inner();

        let pair: DirectedTradingPair = request
            .trading_pair
            .ok_or_else(|| tonic::Status::invalid_argument("missing directed trading pair"))?
            .try_into()
            .map_err(|e| {
                tonic::Status::invalid_argument(format!(
                    "error parsing directed trading pair: {:#}",
                    e
                ))
            })?;

        let limit = if request.limit != 0 {
            request.limit as usize
        } else {
            usize::MAX
        };

        let s = state
            .positions_by_price(&pair)
            .take(limit)
            .map_ok(|(id, position)| LiquidityPositionsByPriceResponse {
                data: Some(position.into()),
                id: Some(id.into()),
            })
            .map_err(|e: anyhow::Error| {
                tonic::Status::internal(format!("error retrieving positions: {:#}", e))
            });
        // TODO: how do we instrument a Stream
        Ok(tonic::Response::new(s.boxed()))
    }

    #[instrument(skip(self, request))]
    async fn liquidity_positions(
        &self,
        request: tonic::Request<LiquidityPositionsRequest>,
    ) -> Result<tonic::Response<Self::LiquidityPositionsStream>, Status> {
        let state = self.storage.latest_snapshot();

        let include_closed = request.get_ref().include_closed;
        let s = state.all_positions();
        Ok(tonic::Response::new(
            s.filter(move |item| {
                use crate::lp::position::State;
                let keep = match item {
                    Ok(position) => {
                        if position.state == State::Opened {
                            true
                        } else {
                            include_closed
                        }
                    }
                    Err(_) => false,
                };
                futures::future::ready(keep)
            })
            .map_ok(|i: Position| LiquidityPositionsResponse {
                data: Some(i.into()),
            })
            .map_err(|e: anyhow::Error| {
                tonic::Status::unavailable(format!("error getting prefix value from storage: {e}"))
            })
            // TODO: how do we instrument a Stream
            //.instrument(Span::current())
            .boxed(),
        ))
    }

    #[instrument(skip(self, request))]
    async fn liquidity_position_by_id(
        &self,
        request: tonic::Request<LiquidityPositionByIdRequest>,
    ) -> Result<tonic::Response<LiquidityPositionByIdResponse>, Status> {
        let state = self.storage.latest_snapshot();

        let position_id: position::Id = request
            .into_inner()
            .position_id
            .ok_or_else(|| Status::invalid_argument("empty message"))?
            .try_into()
            .map_err(|e: anyhow::Error| {
                tonic::Status::invalid_argument(format!("error converting position_id: {e}"))
            })?;

        let position = state
            .position_by_id(&position_id)
            .await
            .map_err(|e: anyhow::Error| {
                tonic::Status::unavailable(format!("error fetching position from storage: {e}"))
            })?
            .ok_or_else(|| Status::not_found("position not found"))?;

        Ok(tonic::Response::new(LiquidityPositionByIdResponse {
            data: Some(position.into()),
        }))
    }

    #[instrument(skip(self, request))]
    async fn liquidity_positions_by_id(
        &self,
        request: tonic::Request<LiquidityPositionsByIdRequest>,
    ) -> Result<tonic::Response<Self::LiquidityPositionsByIdStream>, Status> {
        let state = self.storage.latest_snapshot();

        let position_ids: Vec<position::Id> = request
            .into_inner()
            .position_id
            .into_iter()
            .map(TryInto::try_into)
            .collect::<anyhow::Result<Vec<_>>>()
            .map_err(|e: anyhow::Error| {
                tonic::Status::invalid_argument(format!("error converting position_id: {e}"))
            })?;

        let s = try_stream! {
            for position_id in position_ids {
                let position = state
                    .position_by_id(&position_id)
                    .await
                    .map_err(|e: anyhow::Error| {
                        tonic::Status::unavailable(format!("error fetching position from storage: {e}"))
                    })?
                    .ok_or_else(|| Status::not_found("position not found"))?;

                yield position.to_proto();
            }
        };
        Ok(tonic::Response::new(
            s.map_ok(|p: penumbra_proto::core::component::dex::v1::Position| {
                LiquidityPositionsByIdResponse { data: Some(p) }
            })
            .map_err(|e: anyhow::Error| {
                tonic::Status::unavailable(format!(
                    "error getting position value from storage: {e}"
                ))
            })
            // TODO: how do we instrument a Stream
            //.instrument(Span::current())
            .boxed(),
        ))
    }
}

#[tonic::async_trait]
impl SimulationService for Server {
    async fn simulate_trade(
        &self,
        request: tonic::Request<SimulateTradeRequest>,
    ) -> Result<tonic::Response<SimulateTradeResponse>, Status> {
        let request = request.into_inner();
        let routing_stategy = match request.routing {
            None => Routing {
                setting: Some(Setting::Default(routing::Default {})),
            },
            Some(routing) => routing,
        };

        let routing_strategy = match routing_stategy.setting {
            None => Setting::Default(routing::Default {}),
            Some(setting) => setting,
        };

        let input: Value = request
            .input
            .ok_or_else(|| tonic::Status::invalid_argument("missing input parameter"))?
            .try_into()
            .map_err(|e| {
                tonic::Status::invalid_argument(format!("error parsing input: {:#}", e))
            })?;

        let output_id = request
            .output
            .ok_or_else(|| tonic::Status::invalid_argument("missing output id parameter"))?
            .try_into()
            .map_err(|e| {
                tonic::Status::invalid_argument(format!("error parsing output id: {:#}", e))
            })?;

        let start_time = std::time::Instant::now();
        let state = self.storage.latest_snapshot();

        let mut routing_params = state
            .routing_params()
            .await
            .expect("dex routing params are set");
        match routing_strategy {
            Setting::SingleHop(_) => {
                routing_params.max_hops = 1;
            }
            Setting::Default(_) => {
                // no-op, use the default
            }
        }

        let execution_budget = state
            .get_dex_params()
            .await
            .expect("dex parameters are set")
            .max_execution_budget;

        let mut state_tx = Arc::new(StateDelta::new(state));
        let execution_circuit_breaker = ExecutionCircuitBreaker::new(execution_budget);

        let swap_execution = match state_tx
            .route_and_fill(
                input.asset_id,
                output_id,
                input.amount,
                routing_params,
                execution_circuit_breaker,
            )
            .await
            .map_err(|e| tonic::Status::internal(format!("error simulating trade: {:#}", e)))?
        {
            Some(swap_execution) => swap_execution,
            None => SwapExecution {
                traces: vec![],
                input: Value {
                    amount: 0u64.into(),
                    asset_id: input.asset_id,
                },
                output: Value {
                    amount: 0u64.into(),
                    asset_id: output_id,
                },
            },
        };

        let unfilled = Value {
            amount: input
                .amount
                .checked_sub(&swap_execution.input.amount)
                .ok_or_else(|| {
                    tonic::Status::failed_precondition(
                        "swap execution input amount is larger than request input amount"
                            .to_string(),
                    )
                })?,
            asset_id: input.asset_id,
        };

        let rsp = tonic::Response::new(SimulateTradeResponse {
            unfilled: Some(unfilled.into()),
            output: Some(swap_execution.into()),
        });

        let duration = start_time.elapsed();

        metrics::histogram!(metrics::DEX_RPC_SIMULATE_TRADE_DURATION).record(duration);

        Ok(rsp)
    }
}