use std::{
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
fmt::Debug,
sync::Arc,
};
use chrono::{DateTime, Utc};
use num_bigint::BigUint;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use tycho_common::{
models::{token::Token, Chain},
simulation::{
errors::SimulationError,
protocol_sim::{GetAmountOutResult, ProtocolSim},
},
Bytes,
};
use crate::{
book::{
component::{encode_swap_directions, pair_book, PairState, SWAP_DIRECTIONS_ATTRIBUTE},
Book, Books,
},
protocol::models::ProtocolComponent,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ComponentLayout<R> {
PerPair,
AllPairs(R),
}
impl<R> From<Option<R>> for ComponentLayout<R> {
fn from(rule: Option<R>) -> Self {
rule.map_or(ComponentLayout::PerPair, ComponentLayout::AllPairs)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum QuoteRule {
OncePerMaker,
OncePerVenue,
}
impl QuoteRule {
pub const ATTRIBUTE: &'static str = "quote_rule";
const ALL: [QuoteRule; 2] = [QuoteRule::OncePerMaker, QuoteRule::OncePerVenue];
pub fn from_attributes(
attributes: &HashMap<String, Bytes>,
) -> Result<Option<QuoteRule>, String> {
let Some(value) = attributes.get(Self::ATTRIBUTE) else {
return Ok(None);
};
Self::ALL
.into_iter()
.find(|rule| rule.as_str().as_bytes() == value.as_ref())
.map(Some)
.ok_or_else(|| {
format!("Unknown quote_rule attribute: {}", String::from_utf8_lossy(value))
})
}
pub fn as_str(self) -> &'static str {
match self {
QuoteRule::OncePerMaker => "once_per_maker",
QuoteRule::OncePerVenue => "once_per_venue",
}
}
}
pub(crate) trait Turns:
Clone + Debug + PartialEq + Serialize + DeserializeOwned + 'static
{
type Signer: Clone + Debug + PartialEq + Serialize + DeserializeOwned;
type Rule: Copy + Debug;
fn untaken(rule: Self::Rule) -> Self;
fn quote_rule(&self) -> QuoteRule;
fn allows(&self, signer: &Self::Signer) -> bool;
fn spend(&mut self, signer: &Self::Signer);
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(crate) struct MarketMaker(pub String);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Venue;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum SignedByMakers {
PerMaker(HashSet<MarketMaker>),
PerVenue(bool),
}
impl Turns for SignedByMakers {
type Signer = MarketMaker;
type Rule = QuoteRule;
fn untaken(rule: QuoteRule) -> Self {
match rule {
QuoteRule::OncePerMaker => SignedByMakers::PerMaker(HashSet::new()),
QuoteRule::OncePerVenue => SignedByMakers::PerVenue(false),
}
}
fn quote_rule(&self) -> QuoteRule {
match self {
SignedByMakers::PerMaker(_) => QuoteRule::OncePerMaker,
SignedByMakers::PerVenue(_) => QuoteRule::OncePerVenue,
}
}
fn allows(&self, signer: &MarketMaker) -> bool {
match self {
SignedByMakers::PerMaker(makers) => !makers.contains(signer),
SignedByMakers::PerVenue(signed) => !signed,
}
}
fn spend(&mut self, signer: &MarketMaker) {
match self {
SignedByMakers::PerMaker(makers) => {
makers.insert(signer.clone());
}
SignedByMakers::PerVenue(signed) => *signed = true,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct SignedByVenue(bool);
impl Turns for SignedByVenue {
type Signer = Venue;
type Rule = ();
fn untaken((): ()) -> Self {
SignedByVenue(false)
}
fn quote_rule(&self) -> QuoteRule {
QuoteRule::OncePerVenue
}
fn allows(&self, _signer: &Venue) -> bool {
!self.0
}
fn spend(&mut self, _signer: &Venue) {
self.0 = true;
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub(crate) struct VenueBook<P, S> {
pub signer: S,
pub updated_at: Option<DateTime<Utc>>,
pub state: P,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(bound = "P: Serialize + DeserializeOwned + PairState, T: Turns")]
pub(crate) struct AllPairs<P, T: Turns> {
books: Arc<VenueBooks<P, T::Signer>>,
spent: T,
}
#[derive(Debug, Deserialize)]
#[serde(
from = "Vec<VenueBook<P, S>>",
bound = "P: DeserializeOwned + PairState, S: DeserializeOwned"
)]
struct VenueBooks<P, S> {
books: Vec<VenueBook<P, S>>,
by_direction: HashMap<Bytes, HashMap<Bytes, Vec<usize>>>,
}
impl<P: Serialize, S: Serialize> Serialize for VenueBooks<P, S> {
fn serialize<W: serde::Serializer>(&self, serializer: W) -> Result<W::Ok, W::Error> {
self.books.serialize(serializer)
}
}
impl<P: PairState, S> From<Vec<VenueBook<P, S>>> for VenueBooks<P, S> {
fn from(books: Vec<VenueBook<P, S>>) -> Self {
let mut by_direction: HashMap<Bytes, HashMap<Bytes, Vec<usize>>> = HashMap::new();
let mut kept = Vec::new();
for book in books {
let directions = book.state.directions();
if directions.is_empty() {
continue;
}
let index = kept.len();
for (sold, bought) in directions {
by_direction
.entry(sold)
.or_default()
.entry(bought)
.or_default()
.push(index);
}
kept.push(book);
}
VenueBooks { books: kept, by_direction }
}
}
type Answered<'a, P, S> = (&'a VenueBook<P, S>, Result<GetAmountOutResult, SimulationError>);
impl<P: PairState, T: Turns> AllPairs<P, T> {
pub fn new(books: Vec<VenueBook<P, T::Signer>>, rule: T::Rule) -> Self {
AllPairs { books: Arc::new(books.into()), spent: T::untaken(rule) }
}
pub fn rule(&self) -> QuoteRule {
self.spent.quote_rule()
}
pub fn directions(&self) -> BTreeSet<(Bytes, Bytes)> {
self.books
.by_direction
.iter()
.flat_map(|(sold, bought)| {
bought
.keys()
.map(|bought| (sold.clone(), bought.clone()))
})
.collect()
}
pub fn books(&self) -> &[VenueBook<P, T::Signer>] {
&self.books.books
}
fn updated_at(&self) -> Option<DateTime<Utc>> {
self.books()
.iter()
.map(|book| book.updated_at)
.collect::<Option<Vec<_>>>()?
.into_iter()
.min()
}
pub fn books_pricing(
&self,
token_in: &Bytes,
token_out: &Bytes,
) -> impl Iterator<Item = &VenueBook<P, T::Signer>> {
self.books
.by_direction
.get(token_in)
.and_then(|bought| bought.get(token_out))
.into_iter()
.flatten()
.map(|index| &self.books.books[*index])
}
fn candidates(
&self,
token_in: &Bytes,
token_out: &Bytes,
) -> Result<impl Iterator<Item = &VenueBook<P, T::Signer>>, SimulationError> {
let mut pricing = self
.books_pricing(token_in, token_out)
.peekable();
if pricing.peek().is_none() {
return Err(SimulationError::InvalidInput(
format!("Venue prices no book from {token_in} into {token_out}"),
None,
));
}
let mut quotable = pricing
.filter(|book| self.spent.allows(&book.signer))
.peekable();
if quotable.peek().is_none() {
return Err(SimulationError::RecoverableError(
"Every book pricing this swap already quoted in this route".to_string(),
));
}
Ok(quotable)
}
fn spending(&self, signer: &T::Signer) -> Self {
let mut spent = self.spent.clone();
spent.spend(signer);
AllPairs { books: Arc::clone(&self.books), spent }
}
fn best(
&self,
amount_in: &BigUint,
token_in: &Bytes,
token_out: &Bytes,
) -> Result<Answered<'_, P, T::Signer>, SimulationError> {
let mut best: Option<Answered<'_, P, T::Signer>> = None;
for book in self.candidates(token_in, token_out)? {
let (sold, bought) = book.tokens(token_in);
let answer = book
.state
.get_amount_out(amount_in.clone(), sold, bought);
if best
.as_ref()
.is_none_or(|(_, taken)| rank(taken) < rank(&answer))
{
best = Some((book, answer));
}
}
best.ok_or_else(|| no_book_ranked("answer this swap"))
}
pub fn spot_price(&self, base: &Bytes, quote: &Bytes) -> Result<f64, SimulationError> {
let mut best: Option<Result<f64, SimulationError>> = None;
for book in self.candidates(base, quote)? {
let (base, quote) = book.tokens(base);
let price = book.state.spot_price(base, quote);
if best
.as_ref()
.is_none_or(|taken| taken.as_ref().ok() < price.as_ref().ok())
{
best = Some(price);
}
}
best.unwrap_or_else(|| Err(no_book_ranked("price this pair")))
}
pub fn get_limits(
&self,
sell_token: Bytes,
buy_token: Bytes,
) -> Result<(BigUint, BigUint), SimulationError> {
let mut best: Option<Result<(BigUint, BigUint), SimulationError>> = None;
for book in self.candidates(&sell_token, &buy_token)? {
let limits = book
.state
.get_limits(sell_token.clone(), buy_token.clone());
let bought = |limits: &Result<(BigUint, BigUint), SimulationError>| {
limits
.as_ref()
.ok()
.map(|(_, bought)| bought.clone())
};
if best
.as_ref()
.is_none_or(|taken| bought(taken) < bought(&limits))
{
best = Some(limits);
}
}
best.unwrap_or_else(|| Err(no_book_ranked("report its limits")))
}
pub fn same_books(&self, other: &Self) -> bool {
self.spent == other.spent &&
self.books().len() == other.books().len() &&
self.books()
.iter()
.zip(other.books().iter())
.all(|(ours, theirs)| {
ours.signer == theirs.signer && ours.state.eq(&theirs.state)
})
}
pub fn amount_out<W>(
&self,
amount_in: &BigUint,
token_in: &Bytes,
token_out: &Bytes,
) -> Result<GetAmountOutResult, SimulationError>
where
W: From<Self> + ProtocolSim + 'static,
{
let (book, answer) = self.best(amount_in, token_in, token_out)?;
let quoted = || -> Box<dyn ProtocolSim> { Box::new(W::from(self.spending(&book.signer))) };
match answer {
Ok(mut result) => {
result.new_state = quoted();
Ok(result)
}
Err(SimulationError::InvalidInput(message, Some(mut partial))) => {
partial.new_state = quoted();
Err(SimulationError::InvalidInput(message, Some(partial)))
}
Err(refused) => Err(refused),
}
}
pub fn quoting_book(
&self,
amount_in: &BigUint,
token_in: &Bytes,
token_out: &Bytes,
) -> Result<&P, SimulationError> {
let (book, _) = self.best(amount_in, token_in, token_out)?;
Ok(&book.state)
}
}
impl<P: PairState, S> VenueBook<P, S> {
fn tokens(&self, token_in: &Bytes) -> (&Token, &Token) {
let (base, quote) = (self.state.base_token(), self.state.quote_token());
if token_in == &base.address {
(base, quote)
} else {
(quote, base)
}
}
}
fn no_book_ranked(what: &str) -> SimulationError {
SimulationError::FatalError(format!(
"Books were reported for this direction, and none of them was ranked to {what}"
))
}
fn rank(answer: &Result<GetAmountOutResult, SimulationError>) -> (u8, Option<&BigUint>) {
match answer {
Ok(result) => (2, Some(&result.amount)),
Err(SimulationError::InvalidInput(_, Some(partial))) => (1, Some(&partial.amount)),
Err(_) => (0, None),
}
}
pub(crate) trait RefusesQuote {
fn check_amount(
&self,
_amount_in: &BigUint,
_token_in: &Bytes,
_token_out: &Bytes,
) -> Result<(), SimulationError> {
Ok(())
}
}
macro_rules! all_pairs_state {
(
$(#[$doc:meta])*
$wrapper:ident($pair:ty, $turns:ty);
) => {
$(#[$doc])*
#[derive(Clone, Debug, Serialize, Deserialize, ::derive_more::From)]
pub struct $wrapper($crate::book::all_pairs::AllPairs<$pair, $turns>);
#[typetag::serde]
impl ::tycho_common::simulation::protocol_sim::ProtocolSim for $wrapper {
fn fee(&self) -> f64 {
0.0
}
fn spot_price(
&self,
base: &::tycho_common::models::token::Token,
quote: &::tycho_common::models::token::Token,
) -> ::std::result::Result<f64, ::tycho_common::simulation::errors::SimulationError>
{
self.0
.spot_price(&base.address, "e.address)
}
fn get_amount_out(
&self,
amount_in: ::num_bigint::BigUint,
token_in: &::tycho_common::models::token::Token,
token_out: &::tycho_common::models::token::Token,
) -> ::std::result::Result<
::tycho_common::simulation::protocol_sim::GetAmountOutResult,
::tycho_common::simulation::errors::SimulationError,
> {
$crate::book::all_pairs::RefusesQuote::check_amount(
self,
&amount_in,
&token_in.address,
&token_out.address,
)?;
self.0
.amount_out::<$wrapper>(&amount_in, &token_in.address, &token_out.address)
}
fn get_limits(
&self,
sell_token: ::tycho_common::Bytes,
buy_token: ::tycho_common::Bytes,
) -> ::std::result::Result<
(::num_bigint::BigUint, ::num_bigint::BigUint),
::tycho_common::simulation::errors::SimulationError,
> {
self.0.get_limits(sell_token, buy_token)
}
fn as_indicatively_priced(
&self,
) -> ::std::result::Result<
&dyn ::tycho_common::simulation::indicatively_priced::IndicativelyPriced,
::tycho_common::simulation::errors::SimulationError,
> {
::std::result::Result::Ok(self)
}
fn delta_transition(
&mut self,
_delta: ::tycho_common::dto::ProtocolStateDelta,
_tokens: &::std::collections::HashMap<
::tycho_common::Bytes,
::tycho_common::models::token::Token,
>,
_balances: &::tycho_common::simulation::protocol_sim::Balances,
) -> ::std::result::Result<(), ::tycho_common::simulation::errors::TransitionError>
{
::std::result::Result::Err(
::tycho_common::simulation::errors::TransitionError::DecodeError(
"Not implemented".into(),
),
)
}
fn clone_box(
&self,
) -> ::std::boxed::Box<dyn ::tycho_common::simulation::protocol_sim::ProtocolSim> {
::std::boxed::Box::new(self.clone())
}
fn as_any(&self) -> &dyn ::std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn ::std::any::Any {
self
}
fn eq(
&self,
other: &dyn ::tycho_common::simulation::protocol_sim::ProtocolSim,
) -> bool {
other
.as_any()
.downcast_ref::<$wrapper>()
.is_some_and(|other| self.0.same_books(&other.0))
}
}
#[::async_trait::async_trait]
impl ::tycho_common::simulation::indicatively_priced::IndicativelyPriced for $wrapper {
async fn request_signed_quote(
&self,
params: ::tycho_common::models::protocol::GetAmountOutParams,
) -> ::std::result::Result<
::tycho_common::simulation::indicatively_priced::SignedQuote,
::tycho_common::simulation::errors::SimulationError,
> {
::tycho_common::simulation::indicatively_priced::IndicativelyPriced::request_signed_quote(
self.0.quoting_book(
¶ms.amount_in,
¶ms.token_in,
¶ms.token_out,
)?,
params,
)
.await
}
}
};
}
pub(crate) use all_pairs_state;
pub(crate) fn all_pairs_component_id(protocol_system: &str) -> Bytes {
Bytes::from(protocol_system.as_bytes())
}
pub(crate) fn all_pairs_book<P: PairState, T: Turns, W>(
protocol_system: &str,
protocol_type: &str,
chain: Chain,
books: Vec<VenueBook<P, T::Signer>>,
rule: T::Rule,
) -> Option<Book>
where
W: From<AllPairs<P, T>> + ProtocolSim + 'static,
{
let pairs = AllPairs::new(books, rule);
if pairs.books().is_empty() {
return None;
}
let tokens: BTreeMap<Bytes, Token> = pairs
.books()
.iter()
.flat_map(|book| [book.state.base_token(), book.state.quote_token()])
.map(|token| (token.address.clone(), token.clone()))
.collect();
let directions = pairs.directions();
let updated_at = pairs.updated_at();
let component = ProtocolComponent::new(
all_pairs_component_id(protocol_system),
protocol_system.to_string(),
protocol_type.to_string(),
chain,
tokens.into_values().collect(),
vec![],
HashMap::from([
(SWAP_DIRECTIONS_ATTRIBUTE.to_string(), encode_swap_directions(&directions)),
(QuoteRule::ATTRIBUTE.to_string(), pairs.rule().as_str().as_bytes().into()),
]),
Default::default(),
Default::default(),
);
Some(Book { component, state: Arc::new(W::from(pairs)), updated_at })
}
pub(crate) struct BookCollector<P, T: Turns> {
protocol_system: &'static str,
protocol_type: &'static str,
chain: Chain,
layout: ComponentLayout<T::Rule>,
books: Books,
venue_books: Vec<VenueBook<P, T::Signer>>,
}
impl<P: PairState, T: Turns> BookCollector<P, T> {
pub fn new(
protocol_system: &'static str,
protocol_type: &'static str,
chain: Chain,
layout: impl Into<ComponentLayout<T::Rule>>,
) -> Self {
BookCollector {
protocol_system,
protocol_type,
chain,
layout: layout.into(),
books: Books::new(),
venue_books: Vec::new(),
}
}
pub fn push(&mut self, component_id: Bytes, book: VenueBook<P, T::Signer>) {
match self.layout {
ComponentLayout::PerPair => self.books.insert(pair_book(
self.protocol_system,
self.protocol_type,
self.chain,
component_id,
book.state,
book.updated_at,
)),
ComponentLayout::AllPairs(_) => self.venue_books.push(book),
}
}
pub fn finish<W>(mut self) -> Books
where
W: From<AllPairs<P, T>> + ProtocolSim + 'static,
{
if let ComponentLayout::AllPairs(rule) = self.layout {
self.books
.extend(all_pairs_book::<P, T, W>(
self.protocol_system,
self.protocol_type,
self.chain,
self.venue_books,
rule,
));
}
self.books
}
}
#[cfg(test)]
mod tests {
use std::any::Any;
use rstest::rstest;
use tycho_common::{
dto::ProtocolStateDelta,
simulation::{errors::TransitionError, protocol_sim::Balances},
};
use super::*;
use crate::book::{decode_swap_directions, sim, test_token_map};
#[derive(Clone, Debug, Serialize, Deserialize)]
struct TestBook {
base: Token,
quote: Token,
out_per_in: u64,
depth: u64,
}
impl PairState for TestBook {
fn base_token(&self) -> &Token {
&self.base
}
fn quote_token(&self) -> &Token {
&self.quote
}
fn directions(&self) -> Vec<(Bytes, Bytes)> {
sim::directions(&self.base, &self.quote, self.out_per_in > 0, false)
}
}
#[typetag::serde]
impl ProtocolSim for TestBook {
fn fee(&self) -> f64 {
0.0
}
fn spot_price(&self, _base: &Token, _quote: &Token) -> Result<f64, SimulationError> {
Ok(self.out_per_in as f64)
}
fn get_amount_out(
&self,
amount_in: BigUint,
token_in: &Token,
_token_out: &Token,
) -> Result<GetAmountOutResult, SimulationError> {
assert_eq!(token_in.address, self.base.address, "a book is given its own tokens");
let filled = amount_in.clone().min(whole(self.depth));
let result = GetAmountOutResult {
amount: &filled * BigUint::from(self.out_per_in),
gas: BigUint::from(100u64),
new_state: self.clone_box(),
};
if filled == amount_in {
Ok(result)
} else {
Err(SimulationError::InvalidInput("Out of depth".to_string(), Some(result)))
}
}
fn get_limits(
&self,
_sell_token: Bytes,
_buy_token: Bytes,
) -> Result<(BigUint, BigUint), SimulationError> {
Ok((whole(self.depth), whole(self.depth * self.out_per_in)))
}
fn delta_transition(
&mut self,
_delta: ProtocolStateDelta,
_tokens: &HashMap<Bytes, Token>,
_balances: &Balances,
) -> Result<(), TransitionError> {
unimplemented!("a test book never transitions")
}
fn clone_box(&self) -> Box<dyn ProtocolSim> {
Box::new(self.clone())
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn eq(&self, other: &dyn ProtocolSim) -> bool {
other
.as_any()
.downcast_ref::<TestBook>()
.is_some_and(|other| {
self.out_per_in == other.out_per_in && self.depth == other.depth
})
}
}
#[derive(Clone, Debug, Serialize, Deserialize, derive_more::From)]
struct TestVenue(AllPairs<TestBook, SignedByMakers>);
impl RefusesQuote for TestVenue {}
impl TestVenue {
fn amount_out(
&self,
amount_in: &BigUint,
token_in: &Bytes,
token_out: &Bytes,
) -> Result<GetAmountOutResult, SimulationError> {
self.0
.amount_out::<TestVenue>(amount_in, token_in, token_out)
}
}
#[typetag::serde]
impl ProtocolSim for TestVenue {
fn fee(&self) -> f64 {
0.0
}
fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
self.0
.spot_price(&base.address, "e.address)
}
fn get_amount_out(
&self,
amount_in: BigUint,
token_in: &Token,
token_out: &Token,
) -> Result<GetAmountOutResult, SimulationError> {
self.check_amount(&amount_in, &token_in.address, &token_out.address)?;
self.0
.amount_out::<TestVenue>(&amount_in, &token_in.address, &token_out.address)
}
fn get_limits(
&self,
sell_token: Bytes,
buy_token: Bytes,
) -> Result<(BigUint, BigUint), SimulationError> {
self.0.get_limits(sell_token, buy_token)
}
fn delta_transition(
&mut self,
_delta: ProtocolStateDelta,
_tokens: &HashMap<Bytes, Token>,
_balances: &Balances,
) -> Result<(), TransitionError> {
unimplemented!("a test venue never transitions")
}
fn clone_box(&self) -> Box<dyn ProtocolSim> {
Box::new(self.clone())
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn eq(&self, other: &dyn ProtocolSim) -> bool {
other
.as_any()
.downcast_ref::<TestVenue>()
.is_some_and(|other| self.0.same_books(&other.0))
}
}
fn whole(count: u64) -> BigUint {
BigUint::from(count) * BigUint::from(10u64).pow(18)
}
fn addr(byte: u8) -> Bytes {
Bytes::from(vec![byte; 20])
}
fn tokens() -> HashMap<Bytes, Token> {
test_token_map(&[(&addr(0xaa), "A", 18), (&addr(0xbb), "B", 18), (&addr(0xcc), "C", 18)])
}
fn book(maker: &str, out_per_in: u64, depth: u64) -> VenueBook<TestBook, MarketMaker> {
let tokens = tokens();
VenueBook {
signer: MarketMaker(maker.to_string()),
updated_at: None,
state: TestBook {
base: tokens[&addr(0xaa)].clone(),
quote: tokens[&addr(0xbb)].clone(),
out_per_in,
depth,
},
}
}
fn venue(books: Vec<VenueBook<TestBook, MarketMaker>>, rule: QuoteRule) -> TestVenue {
TestVenue(AllPairs::new(books, rule))
}
#[test]
fn the_best_paying_book_takes_the_swap() {
let venue = venue(
vec![book("cheap", 2, 10), book("generous", 3, 10), book("shallow", 9, 0)],
QuoteRule::OncePerMaker,
);
let swap = venue
.amount_out(&whole(1), &addr(0xaa), &addr(0xbb))
.unwrap();
assert_eq!(swap.amount, whole(3));
}
#[test]
fn a_partial_fill_beats_a_refusal() {
let venue =
venue(vec![book("shallow", 2, 1), book("empty", 5, 0)], QuoteRule::OncePerMaker);
match venue.amount_out(&whole(4), &addr(0xaa), &addr(0xbb)) {
Err(SimulationError::InvalidInput(_, Some(partial))) => {
assert_eq!(partial.amount, whole(2));
}
other => panic!("expected the partially filled result, got {other:?}"),
}
}
#[rstest]
#[case::once_per_maker(QuoteRule::OncePerMaker, Some(2))]
#[case::once_per_venue(QuoteRule::OncePerVenue, None)]
fn the_second_swap_is_held_to_the_rule(
#[case] rule: QuoteRule,
#[case] second_pays: Option<u64>,
) {
let venue = venue(vec![book("generous", 3, 10), book("cheap", 2, 10)], rule);
let first = venue
.amount_out(&whole(1), &addr(0xaa), &addr(0xbb))
.unwrap();
assert_eq!(first.amount, whole(3));
let second = first.new_state.get_amount_out(
whole(1),
&tokens()[&addr(0xaa)],
&tokens()[&addr(0xbb)],
);
match (second, second_pays) {
(Ok(second), Some(pays)) => assert_eq!(second.amount, whole(pays)),
(Err(SimulationError::RecoverableError(message)), None) => {
assert_eq!(message, "Every book pricing this swap already quoted in this route")
}
(second, _) => panic!("expected a second swap paying {second_pays:?}, got {second:?}"),
}
}
#[test]
fn a_partial_fill_carries_the_venue_on() {
let venue = venue(vec![book("shallow", 2, 1)], QuoteRule::OncePerVenue);
let Err(SimulationError::InvalidInput(_, Some(partial))) =
venue.amount_out(&whole(4), &addr(0xaa), &addr(0xbb))
else {
panic!("expected a partial fill");
};
let after = partial.new_state.get_amount_out(
whole(1),
&tokens()[&addr(0xaa)],
&tokens()[&addr(0xbb)],
);
assert!(matches!(after, Err(SimulationError::RecoverableError(_))), "got {after:?}");
}
#[test]
fn a_direction_the_venue_does_not_price_is_invalid_input() {
let venue = venue(vec![book("generous", 3, 10)], QuoteRule::OncePerMaker);
let reverse = venue.amount_out(&whole(1), &addr(0xbb), &addr(0xaa));
let unknown = venue.amount_out(&whole(1), &addr(0xaa), &addr(0xcc));
assert!(matches!(reverse, Err(SimulationError::InvalidInput(_, None))), "got {reverse:?}");
assert!(matches!(unknown, Err(SimulationError::InvalidInput(_, None))), "got {unknown:?}");
}
#[test]
fn the_price_and_the_limits_are_the_best_books() {
let venue =
venue(vec![book("cheap", 2, 10), book("generous", 3, 8)], QuoteRule::OncePerVenue);
assert_eq!(
venue
.0
.spot_price(&addr(0xaa), &addr(0xbb))
.unwrap(),
3.0
);
assert_eq!(
venue
.0
.get_limits(addr(0xaa), addr(0xbb))
.unwrap(),
(whole(8), whole(24)),
"the limits of the book that buys most, not the sum of both"
);
let spent = venue
.amount_out(&whole(1), &addr(0xaa), &addr(0xbb))
.unwrap()
.new_state;
assert!(matches!(
spent.get_limits(addr(0xaa), addr(0xbb)),
Err(SimulationError::RecoverableError(_))
));
}
#[test]
fn a_venue_that_prices_nothing_publishes_no_component() {
let book = all_pairs_book::<TestBook, SignedByMakers, TestVenue>(
"rfq:venue",
"venue_pool",
Chain::Ethereum,
vec![book("empty", 0, 0)],
QuoteRule::OncePerMaker,
);
assert!(book.is_none(), "{book:?}");
}
#[test]
fn the_component_advertises_the_directions_and_the_rule() {
let tokens = tokens();
let b_to_c = VenueBook {
signer: MarketMaker("mm".to_string()),
updated_at: None,
state: TestBook {
base: tokens[&addr(0xbb)].clone(),
quote: tokens[&addr(0xcc)].clone(),
out_per_in: 1,
depth: 1,
},
};
let book = all_pairs_book::<TestBook, SignedByMakers, TestVenue>(
"rfq:venue",
"venue_pool",
Chain::Ethereum,
vec![book("generous", 3, 10), b_to_c],
QuoteRule::OncePerMaker,
)
.expect("a venue pricing two pairs has a component");
assert_eq!(book.component.id.to_string(), "0x7266713a76656e7565");
assert_eq!(
book.component
.tokens
.iter()
.map(|token| token.symbol.as_str())
.collect::<Vec<_>>(),
vec!["A", "B", "C"]
);
let directions = &book.component.static_attributes[SWAP_DIRECTIONS_ATTRIBUTE];
assert_eq!(
decode_swap_directions(directions).unwrap(),
vec![(addr(0xaa), addr(0xbb)), (addr(0xbb), addr(0xcc))]
);
assert_eq!(
book.component.static_attributes[QuoteRule::ATTRIBUTE],
Bytes::from("once_per_maker".as_bytes())
);
}
#[test]
fn a_book_that_prices_nothing_is_left_out() {
let tokens = tokens();
let silent = VenueBook {
signer: MarketMaker("mm".to_string()),
updated_at: None,
state: TestBook {
base: tokens[&addr(0xbb)].clone(),
quote: tokens[&addr(0xcc)].clone(),
out_per_in: 0,
depth: 10,
},
};
let book = all_pairs_book::<TestBook, SignedByMakers, TestVenue>(
"rfq:venue",
"venue_pool",
Chain::Ethereum,
vec![book("generous", 3, 10), silent],
QuoteRule::OncePerMaker,
)
.expect("one book prices a pair");
let directions =
decode_swap_directions(&book.component.static_attributes[SWAP_DIRECTIONS_ATTRIBUTE])
.unwrap();
assert_eq!(directions, vec![(addr(0xaa), addr(0xbb))]);
assert_eq!(
book.component
.tokens
.iter()
.map(|token| token.symbol.as_str())
.collect::<Vec<_>>(),
vec!["A", "B"]
);
assert_eq!(
directions
.iter()
.flat_map(|(sold, bought)| [sold.clone(), bought.clone()])
.collect::<BTreeSet<_>>(),
book.component
.tokens
.iter()
.map(|token| token.address.clone())
.collect::<BTreeSet<_>>(),
"the component carries the tokens its directions name, and no others"
);
}
#[test]
fn a_serialized_venue_still_prices_its_directions() {
let venue = venue(vec![book("generous", 3, 10)], QuoteRule::OncePerMaker);
let replayed: TestVenue =
serde_json::from_str(&serde_json::to_string(&venue).unwrap()).unwrap();
assert_eq!(
replayed
.amount_out(&whole(1), &addr(0xaa), &addr(0xbb))
.unwrap()
.amount,
whole(3)
);
}
#[test]
fn the_rule_travels_as_its_attribute() {
let attribute = |value: &str| {
HashMap::from([(QuoteRule::ATTRIBUTE.to_string(), Bytes::from(value.as_bytes()))])
};
assert_eq!(
QuoteRule::from_attributes(&attribute("once_per_venue")),
Ok(Some(QuoteRule::OncePerVenue))
);
assert_eq!(
QuoteRule::from_attributes(&attribute("once_per_maker")),
Ok(Some(QuoteRule::OncePerMaker))
);
assert_eq!(QuoteRule::from_attributes(&HashMap::new()), Ok(None));
assert_eq!(
QuoteRule::from_attributes(&attribute("once_per_hour")),
Err("Unknown quote_rule attribute: once_per_hour".to_string())
);
}
#[test]
fn swap_directions_are_forty_bytes_each() {
let directions = BTreeSet::from([(addr(0x11), addr(0x22))]);
let encoded = encode_swap_directions(&directions);
assert_eq!(
encoded.to_string(),
"0x1111111111111111111111111111111111111111\
2222222222222222222222222222222222222222"
);
assert!(decode_swap_directions(&[0u8; 41]).is_err());
}
#[rstest]
#[case::per_pair(ComponentLayout::PerPair, vec!["0x01", "0x02"])]
#[case::all_pairs(ComponentLayout::AllPairs(QuoteRule::OncePerVenue), vec!["0x7266713a76656e7565"])]
fn the_layout_decides_which_components_a_venues_books_become(
#[case] layout: ComponentLayout<QuoteRule>,
#[case] expected: Vec<&str>,
) {
let mut collector = BookCollector::new("rfq:venue", "venue_pool", Chain::Ethereum, layout);
collector.push(Bytes::from([0x01]), book("mm1", 2, 10));
collector.push(Bytes::from([0x02]), book("mm2", 3, 10));
let books = collector.finish::<TestVenue>();
let mut ids: Vec<&str> = books
.keys()
.map(String::as_str)
.collect();
ids.sort();
assert_eq!(ids, expected);
}
}