tycho_simulation/rfq/protocols/liquorice/
all_pairs_decoder.rs1use std::collections::HashMap;
2
3use tycho_client::feed::synchronizer::ComponentWithState;
4use tycho_common::{models::token::Token, Bytes};
5
6use super::{all_pairs_state::LiquoriceAllPairsState, client_builder::LiquoriceClientBuilder};
7use crate::{
8 protocol::{
9 errors::InvalidSnapshotError,
10 models::{DecoderContext, TryFromWithBlock},
11 },
12 rfq::{
13 constants::get_liquorice_auth,
14 models::{ComponentLayout, TimestampHeader},
15 protocols::{
16 component::{decode_all_pairs_component, DecodedAllPairs},
17 maker_price_levels::MakerPriceLevels,
18 },
19 },
20};
21
22impl TryFromWithBlock<ComponentWithState, TimestampHeader> for LiquoriceAllPairsState {
23 type Error = InvalidSnapshotError;
24
25 async fn try_from_with_header(
26 snapshot: ComponentWithState,
27 _timestamp_header: TimestampHeader,
28 _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
29 all_tokens: &HashMap<Bytes, Token>,
30 _decoder_context: &DecoderContext,
31 ) -> Result<Self, Self::Error> {
32 let DecodedAllPairs { books: price_levels, tokens, quote_rule } =
33 decode_all_pairs_component::<MakerPriceLevels>(&snapshot, all_tokens)?;
34
35 let auth = get_liquorice_auth().map_err(|e| {
36 InvalidSnapshotError::ValueError(format!("Failed to get Liquorice authentication: {e}"))
37 })?;
38 let mut builder =
39 LiquoriceClientBuilder::new(snapshot.component.chain, auth.solver, auth.key)
40 .tokens(tokens.keys().cloned().collect())
41 .component_layout(ComponentLayout::AllPairs);
42 if let Some(quote_rule) = quote_rule {
43 builder = builder.quote_rule(quote_rule);
44 }
45 let client = builder.build().map_err(|e| {
46 InvalidSnapshotError::ValueError(format!("Couldn't create LiquoriceClient: {e}"))
47 })?;
48
49 Ok(LiquoriceAllPairsState::new(price_levels, tokens, client))
50 }
51}
52
53#[cfg(test)]
54mod tests {
55 use std::env;
56
57 use num_bigint::BigUint;
58 use tycho_common::simulation::{errors::SimulationError, protocol_sim::ProtocolSim};
59
60 use super::*;
61 use crate::rfq::{
62 models::QuoteRule,
63 protocols::test_utils::{all_pairs_snapshot, decode, usdc, wbtc, weth},
64 };
65
66 #[tokio::test]
67 async fn test_decodes_price_levels() {
68 env::set_var("LIQUORICE_USER", "test_solver");
70 env::set_var("LIQUORICE_KEY", "test_key");
71 let price_levels = serde_json::json!([
72 {
73 "mm": "test_market_maker",
74 "base_token": wbtc().address, "quote_token": usdc().address,
75 "levels": [{ "q": "1.5", "p": "65000.0" }, { "q": "2.0", "p": "64950.0" }]
76 },
77 {
78 "mm": "mm_b",
79 "base_token": wbtc().address, "quote_token": usdc().address,
80 "levels": [{ "q": "0.5", "p": "65100.0" }]
81 },
82 {
83 "mm": "test_market_maker",
84 "base_token": weth().address, "quote_token": usdc().address,
85 "levels": [{ "q": "10", "p": "3000.0" }]
86 }
87 ]);
88 let (snapshot, tokens) =
89 all_pairs_snapshot("rfq:liquorice", &[wbtc(), usdc(), weth()], &price_levels);
90 let state = decode::<LiquoriceAllPairsState>(snapshot, &tokens)
91 .await
92 .unwrap();
93
94 let wbtc_price_levels = state
95 .price_levels
96 .pair_price_levels(&wbtc().address, &usdc().address);
97 assert_eq!(wbtc_price_levels.len(), 2);
98 assert_eq!(wbtc_price_levels[0].market_maker, "mm_b");
99 assert_eq!(wbtc_price_levels[1].levels[0].quantity, 1.5);
100 assert_eq!(wbtc_price_levels[1].levels[0].price, 65000.0);
101 }
102
103 #[tokio::test]
106 async fn test_decodes_once_per_venue_attribute() {
107 env::set_var("LIQUORICE_USER", "test_solver");
108 env::set_var("LIQUORICE_KEY", "test_key");
109 let price_levels = serde_json::json!([
110 {
111 "mm": "mm_b",
112 "base_token": wbtc().address, "quote_token": usdc().address,
113 "levels": [{ "q": "0.5", "p": "65100.0" }]
114 },
115 {
116 "mm": "test_market_maker",
117 "base_token": weth().address, "quote_token": usdc().address,
118 "levels": [{ "q": "10", "p": "3000.0" }]
119 }
120 ]);
121 let (mut snapshot, tokens) =
122 all_pairs_snapshot("rfq:liquorice", &[wbtc(), usdc(), weth()], &price_levels);
123 snapshot
124 .component
125 .static_attributes
126 .insert(
127 QuoteRule::ATTRIBUTE.to_string(),
128 QuoteRule::OncePerVenue
129 .as_str()
130 .as_bytes()
131 .into(),
132 );
133
134 let state = decode::<LiquoriceAllPairsState>(snapshot, &tokens)
135 .await
136 .unwrap();
137 let after_swap = state
138 .get_amount_out(BigUint::from(50_000_000u64), &wbtc(), &usdc())
139 .unwrap()
140 .new_state;
141
142 let result = after_swap.get_amount_out(
143 BigUint::from(1_000_000_000_000_000_000u64),
144 &weth(),
145 &usdc(),
146 );
147 assert!(
148 matches!(result, Err(SimulationError::RecoverableError(message)) if message.contains("already quoted in this route"))
149 );
150 }
151}