Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rank by surplus driver V3 #2448

Merged
merged 32 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 110 additions & 1 deletion crates/driver/src/boundary/settlement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use {
infra::Ethereum,
util::conv::u256::U256Ext,
},
anyhow::{anyhow, Context, Result},
anyhow::{anyhow, Context, Ok, Result},
model::{
app_data::AppDataHash,
interaction::InteractionData,
Expand All @@ -34,6 +34,7 @@ use {
DomainSeparator,
},
shared::{
encoded_settlement::EncodedSettlement,
external_prices::ExternalPrices,
http_solver::{
self,
Expand Down Expand Up @@ -175,6 +176,12 @@ impl Settlement {
})
}

pub fn encoded_settlement(&self) -> EncodedSettlement {
self.inner
.clone()
.encode(InternalizationStrategy::EncodeAllInteractions)
}

pub fn tx(
&self,
auction_id: auction::Id,
Expand Down Expand Up @@ -240,6 +247,37 @@ impl Settlement {
Ok(eth::U256::from_big_rational(&quality)?.into())
}

/// Normalized token prices.
pub fn prices(
&self,
eth: &Ethereum,
auction: &competition::Auction,
) -> Result<HashMap<eth::TokenAddress, auction::NormalizedPrice>, boundary::Error> {
let external_prices = ExternalPrices::try_from_auction_prices(
eth.contracts().weth().address(),
auction
.tokens()
.iter()
.filter_map(|token| {
token
.price
.map(|price| (token.address.into(), price.into()))
})
.collect(),
)?;

let prices = auction
.tokens()
.iter()
.fold(HashMap::new(), |mut prices, token| {
if let Some(price) = external_prices.price(&token.address.0 .0) {
prices.insert(token.address, price.clone().into());
}
prices
});
Ok(prices)
}

pub fn merge(self, other: Self) -> Result<Self> {
self.inner.merge(other.inner).map(|inner| Self {
inner,
Expand Down Expand Up @@ -464,6 +502,77 @@ pub fn to_boundary_interaction(
}
}

pub fn to_domain_settlement(
settlement: &EncodedSettlement,
normalized_prices: &HashMap<eth::TokenAddress, auction::NormalizedPrice>,
domain_separator: &eth::DomainSeparator,
policies: &HashMap<competition::order::Uid, Vec<order::FeePolicy>>,
) -> Option<competition::settled::Settlement> {
let order_uids = settlement
.uids(model::DomainSeparator(domain_separator.0))
.ok()?;
let trades = settlement
.trades
.iter()
.zip(order_uids.iter())
.map(|(trade, uid)| {
let uid = uid.0.into();
let side = if trade.8.byte(0) & 0b1 == 0 {
order::Side::Sell
} else {
order::Side::Buy
};
let sell_token_index = trade.0.as_usize();
let buy_token_index = trade.1.as_usize();
let sell_token = settlement.tokens[sell_token_index];
let buy_token = settlement.tokens[buy_token_index];
let uniform_sell_token_index = settlement
.tokens
.iter()
.position(|token| token == &sell_token)
.unwrap();
let uniform_buy_token_index = settlement
.tokens
.iter()
.position(|token| token == &buy_token)
.unwrap();
let sell = eth::Asset {
token: sell_token.into(),
amount: trade.3.into(),
};
let buy = eth::Asset {
token: buy_token.into(),
amount: trade.4.into(),
};
let executed = eth::Asset {
token: match side {
order::Side::Sell => sell.token,
order::Side::Buy => buy.token,
},
amount: trade.9.into(),
};
let prices = competition::settled::Prices {
uniform: competition::settled::ClearingPrices {
sell: settlement.clearing_prices[uniform_sell_token_index],
buy: settlement.clearing_prices[uniform_buy_token_index],
},
custom: competition::settled::ClearingPrices {
sell: settlement.clearing_prices[sell_token_index],
buy: settlement.clearing_prices[buy_token_index],
},
native: competition::settled::NormalizedPrices {
sell: normalized_prices[&sell_token.into()].clone(),
buy: normalized_prices[&buy_token.into()].clone(),
},
};
let policies = policies.get(&uid).cloned().unwrap_or_default();
competition::settled::Trade::new(sell, buy, side, executed, prices, policies)
})
.collect();

Some(competition::settled::Settlement::new(trades))
}

fn to_big_decimal(value: bigdecimal::BigDecimal) -> num::BigRational {
let (x, exp) = value.into_bigint_and_exponent();
let numerator_bytes = x.to_bytes_le();
Expand Down
11 changes: 11 additions & 0 deletions crates/driver/src/domain/competition/auction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use {
},
futures::future::{join_all, BoxFuture, FutureExt, Shared},
itertools::Itertools,
num::BigRational,
std::{
collections::{HashMap, HashSet},
sync::{Arc, Mutex},
Expand Down Expand Up @@ -418,6 +419,16 @@ impl From<eth::U256> for Price {
}
}

/// The price of a token in ETH. Price normalized to native token.
#[derive(Debug, Clone)]
pub struct NormalizedPrice(pub BigRational);

impl From<BigRational> for NormalizedPrice {
fn from(value: BigRational) -> Self {
Self(value)
}
}

#[derive(Debug, Clone, Copy)]
pub struct Id(pub i64);

Expand Down
1 change: 1 addition & 0 deletions crates/driver/src/domain/competition/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use {
pub mod auction;
pub mod order;
pub mod score;
pub mod settled;
pub mod solution;

pub use {
Expand Down
Loading
Loading