lamarge 0.8.0

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
//! Prepared quote line checks: every pool's quote set is rebuilt from the caller's lines before
//! it is signed.

use std::collections::{BTreeMap, HashSet};

use alloy_primitives::{Address, U256};
use chrono::{DateTime, Utc};

use super::{
    details::{self, at, changed, differs, stale},
    differs_unless,
    maker::{self, QuoteTerms},
    signed,
};
use crate::{
    deployments,
    error::VerificationError,
    model::{Order, OrderState, QuoteLine, QuoteLineDraft, QuoteLinesPreparation},
    protocol::{fees, signing::Verified},
    types::{Amount, EscrowEnvironment, Price, QuoteIdentityId, Revision, VenueId},
};

/// The caller's lines a preparation is checked against.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinesRequest<'a> {
    /// The lines to publish.
    pub lines: &'a [QuoteLine],
    /// The last admission time, Unix seconds.
    pub valid_until: u64,
    /// The published lines' revision the publication replaces.
    pub expected_revision: Revision,
}

/// The quote identity publishing, its quote signer, its pools as last read, and the maker's
/// payment recipient on each venue it buys on.
#[derive(Debug, Clone, Copy)]
pub struct LinesAuthority<'a> {
    /// The quote identity publishing.
    pub identity: QuoteIdentityId,
    /// Its quote signer.
    pub quote_signer: Address,
    /// Its pools, as last read.
    pub pools: &'a [Order],
    /// The maker's payment recipient on each venue it buys on.
    pub recipients: &'a BTreeMap<VenueId, Address>,
}

/// What `stock` base units sold on `supply` at `sell` cost on `paying` bought at `buy`, rounded
/// up for the maker; `None` for an unpinned venue or beyond `2^256 - 1`.
pub fn line_receive(
    stock: U256,
    sell: Price,
    buy: Price,
    paying: &VenueId,
    supply: &VenueId,
) -> Option<U256> {
    let scale = |price: Price, venue: &VenueId| {
        let decimals = deployments::chain(venue)?.decimals;
        U256::from(price.units()).checked_mul(U256::from(10u8).pow(U256::from(decimals)))
    };
    fees::mul_div_ceil(stock, scale(sell, paying)?, scale(buy, supply)?)
}

/// Whether a pool on `supply` may quote takers paying on `paying`: another venue, and never
/// between the two venues settled inside themselves.
pub fn direct_pair(paying: &VenueId, supply: &VenueId) -> bool {
    paying != supply
        && !(deployments::is_venue_settled(paying) && deployments::is_venue_settled(supply))
}

/// Checks a lines preparation (`POST /v1/quotes/lines/prepare`) and returns one payload per draft,
/// in draft order. The echoed lines are the caller's, each live pool of the identity with stock
/// signs exactly the set its line builds (receiving where the caller buys, at the caller's
/// prices, to the caller's recipients), and only pools without stock are cancelled. Omitting a
/// receiving venue is allowed; changing a price, stock, minimum or recipient is not. Each payload
/// is signable until a second before `valid_until`, refused once `now` reaches it.
pub fn check_prepared_lines(
    prepared: &QuoteLinesPreparation,
    request: &LinesRequest<'_>,
    authority: &LinesAuthority<'_>,
    environment: EscrowEnvironment,
    now: DateTime<Utc>,
) -> Result<Vec<Verified>, VerificationError> {
    if signed(request.valid_until) <= now.timestamp() {
        return Err(stale(details::VALID_UNTIL));
    }
    let asked = lines(request.lines)?;
    differs_unless([
        (prepared.quote_identity_id == authority.identity, details::QUOTE_IDENTITY_ID),
        (prepared.expected_revision == request.expected_revision, details::EXPECTED_REVISION),
        (prepared.valid_until == request.valid_until, details::VALID_UNTIL),
        (lines(&prepared.lines)? == asked, details::LINES),
    ])?;
    let pools: Vec<&Order> = authority
        .pools
        .iter()
        .filter(|pool| {
            pool.capital_pool
                && pool.quote_identity_id == authority.identity
                && !matches!(pool.state, OrderState::Closed | OrderState::Failed)
        })
        .collect();
    let stocked =
        |pool: &&Order| asked.get(&pool.venue).is_some_and(|line| !line.stock.get().is_zero());
    let (with_stock, idle): (Vec<&Order>, Vec<&Order>) = pools.into_iter().partition(stocked);
    let drafted: HashSet<_> = prepared.drafts.iter().map(|draft| draft.order_id).collect();
    if prepared.drafts.len() != with_stock.len() || drafted.len() != with_stock.len() {
        return Err(differs(details::DRAFTS));
    }
    let verified = prepared
        .drafts
        .iter()
        .enumerate()
        .map(|(index, draft)| {
            check_draft(draft, &with_stock, &asked, request, authority, environment)
                .map_err(|error| at(error, index))
        })
        .collect::<Result<Vec<_>, _>>()?;
    if !prepared.cancels.iter().all(|id| idle.iter().any(|pool| pool.id == *id)) {
        return Err(differs(details::CANCELS));
    }
    Ok(verified)
}

/// One pool's draft: the quote set its line builds for each venue the caller buys on.
fn check_draft(
    draft: &QuoteLineDraft,
    pools: &[&Order],
    asked: &BTreeMap<&VenueId, &QuoteLine>,
    request: &LinesRequest<'_>,
    authority: &LinesAuthority<'_>,
    environment: EscrowEnvironment,
) -> Result<Verified, VerificationError> {
    let pool = pools
        .iter()
        .find(|pool| pool.id == draft.order_id)
        .ok_or(differs(details::DRAFTS_ORDER_ID))?;
    let line = asked.get(&pool.venue).ok_or(differs(details::DRAFTS_ORDER_ID))?;
    let sell = line.sell.ok_or(differs(details::LINES))?;
    let stock = line.stock.get();
    let one_token = deployments::chain(&pool.venue)
        .map(|chain| U256::from(10u8).pow(U256::from(chain.decimals)))
        .ok_or(differs(details::DRAFTS_VENUE))?;
    let min_fill = line.min_fill.map_or(one_token, Amount::get);
    if draft.venue != pool.venue {
        return Err(differs(details::DRAFTS_VENUE));
    }
    if pool.state != OrderState::Live {
        return Err(changed(details::POOL_STATE));
    }
    if pool.quote_signer != authority.quote_signer {
        return Err(changed(details::POOL_QUOTE_SIGNER));
    }
    let venues: HashSet<_> = draft.quotes.iter().map(|quote| &quote.venue).collect();
    if draft.quotes.is_empty() || venues.len() != draft.quotes.len() {
        return Err(differs(details::DRAFTS_QUOTES));
    }
    let quotes = draft
        .quotes
        .iter()
        .map(|quote| {
            let buy = asked
                .get(&quote.venue)
                .and_then(|line| line.buy)
                .filter(|_| direct_pair(&quote.venue, &pool.venue))
                .ok_or(differs(details::DRAFTS_QUOTES_VENUE))?;
            let recipient = *authority
                .recipients
                .get(&quote.venue)
                .ok_or(differs(details::DRAFTS_QUOTES_RECIPIENT))?;
            let receive = line_receive(stock, sell, buy, &quote.venue, &pool.venue)
                .ok_or(differs(details::DRAFTS_QUOTES_RECEIVE))?;
            Ok(QuoteTerms {
                venue: quote.venue.clone(),
                recipient,
                supply: stock,
                receive,
                min_fill,
            })
        })
        .collect::<Result<Vec<_>, VerificationError>>()?;
    check_prepared_quote(draft, pool, &quotes, request.valid_until, line.stock, environment)
}

/// A draft's terms and its one quote set: `quotes` (built from the draft's own quotes, one each)
/// exactly, `size` as its budget, valid until `valid_until` and settling an hour and a second
/// later, at a sequence above the pool's last and at most `2^53 - 1`.
pub fn check_prepared_quote(
    draft: &QuoteLineDraft,
    pool: &Order,
    quotes: &[QuoteTerms],
    valid_until: u64,
    size: Amount,
    environment: EscrowEnvironment,
) -> Result<Verified, VerificationError> {
    let expires_at = valid_until.checked_add(deployments::MAKER_TIMEOUT_SECONDS + 1);
    differs_unless([
        (draft.valid_until == valid_until, details::VALID_UNTIL),
        (draft.quote_size == size, details::QUOTE_SIZE),
        (Some(draft.expires_at) == expires_at, details::EXPIRES_AT),
        (
            pool.last_sequence < draft.sequence && draft.sequence <= maker::MAX_SEQUENCE,
            details::SEQUENCE,
        ),
    ])?;
    let [item] = &draft.to_sign[..] else {
        return Err(differs(details::TO_SIGN));
    };
    for (quote, expected) in draft.quotes.iter().zip(quotes) {
        differs_unless([
            (quote.recipient == expected.recipient, details::DRAFTS_QUOTES_RECIPIENT),
            (quote.supply.get() == expected.supply, details::DRAFTS_QUOTES_SUPPLY),
            (quote.receive.get() == expected.receive, details::DRAFTS_QUOTES_RECEIVE),
            (quote.min_fill.get() == expected.min_fill, details::DRAFTS_QUOTES_MIN_FILL),
        ])?;
    }
    maker::check_signed_quote(
        item,
        pool,
        quotes,
        draft.sequence,
        valid_until,
        draft.expires_at,
        environment,
    )
}

/// Lines by venue: each venue once, a buy price at most its sell price, stock only with a sell
/// price.
fn lines(lines: &[QuoteLine]) -> Result<BTreeMap<&VenueId, &QuoteLine>, VerificationError> {
    let mut by_venue = BTreeMap::new();
    for line in lines {
        let priced = match (line.buy, line.sell) {
            (Some(buy), Some(sell)) => buy <= sell,
            _ => true,
        };
        let stocked = line.stock.get().is_zero() || line.sell.is_some();
        if !priced || !stocked || by_venue.insert(&line.venue, line).is_some() {
            return Err(differs(details::LINES));
        }
    }
    Ok(by_venue)
}

#[cfg(test)]
mod tests;