1use std::cmp::Ordering;
2use std::fmt::{Display, Formatter};
3use std::hash::{Hash, Hasher};
4
5use serde::{Deserialize, Serialize};
6
7use alloy_primitives::Address;
8use kabu_types_entities::{PoolId, PoolProtocol, SwapPath};
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct SwapLineDTO {
12 pub pool_types: Vec<PoolProtocol>,
13 pub token_symbols: Vec<String>,
14 pub pools: Vec<PoolId>,
15 pub tokens: Vec<Address>,
16}
17
18impl Ord for SwapLineDTO {
20 fn cmp(&self, other: &Self) -> Ordering {
21 let len_cmp = self.pools.len().cmp(&other.pools.len());
22 if len_cmp != Ordering::Equal {
23 return len_cmp;
24 }
25
26 for (a, b) in self.pool_types.iter().zip(other.pool_types.iter()) {
28 let adr_cmp = a.to_string().cmp(&b.to_string());
29 if adr_cmp != Ordering::Equal {
30 return adr_cmp;
31 }
32 }
33
34 Ordering::Equal
35 }
36}
37
38impl PartialOrd for SwapLineDTO {
39 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
40 Some(self.cmp(other))
41 }
42}
43
44impl PartialEq for SwapLineDTO {
46 fn eq(&self, other: &Self) -> bool {
47 self.pools == other.pools
48 }
49}
50
51impl Eq for SwapLineDTO {}
52
53impl Display for SwapLineDTO {
54 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
55 let symbols = self.token_symbols.join("->");
56 write!(f, "{:?} [{}]", self.pool_types, symbols)
57 }
58}
59
60impl From<&SwapPath> for SwapLineDTO {
61 fn from(value: &SwapPath) -> Self {
62 Self {
63 pool_types: value.pools.iter().map(|x| x.get_protocol()).collect(),
64 token_symbols: value.tokens.iter().map(|x| x.get_symbol()).collect(),
65 pools: value.pools.iter().map(|x| x.get_address()).collect(),
66 tokens: value.tokens.iter().map(|x| x.get_address()).collect(),
67 }
68 }
69}
70
71impl From<SwapPath> for SwapLineDTO {
72 fn from(value: SwapPath) -> Self {
73 Self {
74 pool_types: value.pools.iter().map(|x| x.get_protocol()).collect(),
75 token_symbols: value.tokens.iter().map(|x| x.get_symbol()).collect(),
76 pools: value.pools.iter().map(|x| x.get_address()).collect(),
77 tokens: value.tokens.iter().map(|x| x.get_address()).collect(),
78 }
79 }
80}
81
82impl Hash for SwapLineDTO {
83 fn hash<H: Hasher>(&self, state: &mut H) {
84 self.tokens.hash(state);
85 self.pools.hash(state);
86 }
87}