lamarge 0.5.1

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
//! Taker fee rules: the fee a swap id carries, the fee check, and the exact fee, price and
//! ratio arithmetic the checks and book math share.

use alloy_primitives::{B256, U256, U512, hex, ruint::UintTryFrom};

use super::checks::details::{self, differs};
use crate::{deployments, error::VerificationError, types::Bps, types::VenueId};

/// The escrow's tags: a swap id starting with one carries the fee in its next ten bytes.
const FEE_ON_PAYMENT: [u8; 6] = hex!("de65f326692b");
const FEE_ON_DELIVERY: [u8; 6] = hex!("cc909c08081a");
/// Their wallet twins, which a wallet delivery's swap id always carries, fee zero included.
const WALLET_FEE_ON_PAYMENT: [u8; 6] = hex!("1b4c4374729e");
const WALLET_FEE_ON_DELIVERY: [u8; 6] = hex!("fcb0d9ddb285");

/// The tags under the names `pins.json` gives them.
#[cfg(test)]
pub(crate) const TAGS_FOR_PINS: [(&str, [u8; 6]); 4] = [
    ("fee_on_payment", FEE_ON_PAYMENT),
    ("fee_on_delivery", FEE_ON_DELIVERY),
    ("wallet_fee_on_payment", WALLET_FEE_ON_PAYMENT),
    ("wallet_fee_on_delivery", WALLET_FEE_ON_DELIVERY),
];

/// A take's taker fee: charged on top of the payment, or out of what the maker delivers when
/// the taker pays inside a venue.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct Fee {
    pub(crate) bps: Bps,
    pub(crate) on_delivery: bool,
}

/// The fee a take from `from` pays at its pair's `pair_bps`: none without the taker's consent,
/// `max_fee_bps`.
pub(crate) fn take_fee(from: &VenueId, pair_bps: Bps, max_fee_bps: Option<Bps>) -> Fee {
    match max_fee_bps {
        None => Fee::default(),
        Some(_) => Fee { bps: pair_bps, on_delivery: deployments::is_venue_settled(from) },
    }
}

/// `⌊amount × bps / 10 000⌋`, exactly and without overflow (`bps ≤ 10 000`).
pub(crate) fn fee_on(amount: U256, bps: Bps) -> U256 {
    let scale = U256::from(10_000u16);
    let bps = U256::from(bps.get());
    amount / scale * bps + amount % scale * bps / scale
}

/// The largest price whose fee on top fits `budget`: `P + ⌊P × bps / 10 000⌋ ≤ budget`, as the
/// server plans it.
pub(crate) fn price_within(budget: U256, bps: Bps) -> Option<U256> {
    let scale = U512::from(10_000u16);
    let numerator = (wide(budget) + U512::from(1u8)) * scale - U512::from(1u8);
    narrow(numerator / (scale + U512::from(bps.get())))
}

/// `⌊a × b / c⌋`; `None` for `c = 0` or a result above `2^256 - 1`.
pub(crate) fn mul_div(a: U256, b: U256, c: U256) -> Option<U256> {
    let product: U512 = a.widening_mul(b);
    product.checked_div(wide(c)).and_then(narrow)
}

/// `⌈a × b / c⌉`; `None` for `c = 0` or a result above `2^256 - 1`.
pub(crate) fn mul_div_ceil(a: U256, b: U256, c: U256) -> Option<U256> {
    let product: U512 = a.widening_mul(b);
    let divisor = wide(c);
    let quotient = product.checked_div(divisor)?;
    let rounded = if (product % divisor).is_zero() { quotient } else { quotient + U512::from(1u8) };
    narrow(rounded)
}

/// `a × b < c × d`, exactly.
pub(crate) fn product_lt(a: U256, b: U256, c: U256, d: U256) -> bool {
    a.widening_mul::<256, 4, 512, 8>(b) < c.widening_mul::<256, 4, 512, 8>(d)
}

fn wide(value: U256) -> U512 {
    value.widening_mul(U256::from(1u8))
}

fn narrow(value: U512) -> Option<U256> {
    U256::uint_try_from(value).ok()
}

/// The fee a swap id carries and where the escrow takes it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct SwapFee {
    pub(crate) fee: U256,
    pub(crate) on_delivery: bool,
    /// A wallet delivery's swap id: the escrow pays it by plain transfer, never into a venue.
    pub(crate) wallet: bool,
}

/// The fee `swap_id` carries; zero on the payment, into a venue, without a tag.
pub(crate) fn swap_fee(swap_id: &B256) -> SwapFee {
    let (tag, rest) = swap_id.split_at(6);
    let (on_delivery, wallet) = match <[u8; 6]>::try_from(tag) {
        Ok(FEE_ON_PAYMENT) => (false, false),
        Ok(FEE_ON_DELIVERY) => (true, false),
        Ok(WALLET_FEE_ON_PAYMENT) => (false, true),
        Ok(WALLET_FEE_ON_DELIVERY) => (true, true),
        _ => return SwapFee { fee: U256::ZERO, on_delivery: false, wallet: false },
    };
    SwapFee { fee: U256::from_be_slice(&rest[..10]), on_delivery, wallet }
}

/// That a fill's fee is the one its swap id carries, taken where its payment says, within what
/// the taker accepted: on the maker's price from an escrow payment (`on_delivery` false), on
/// what the offer delivers when the taker pays inside a venue. Without consent, no fee.
pub(crate) fn check_fee(
    swap_id: &B256,
    taker_fee: U256,
    amount_in: U256,
    amount_out: U256,
    on_delivery: bool,
    max_fee_bps: Option<Bps>,
) -> Result<(), VerificationError> {
    let carried = swap_fee(swap_id);
    if carried.fee != taker_fee {
        return Err(differs(details::FILLS_TAKER_FEE));
    }
    if carried.fee.is_zero() {
        return Ok(());
    }
    if carried.on_delivery != on_delivery {
        return Err(differs(details::FILLS_SWAP_ID));
    }
    let charged = if on_delivery {
        amount_out.checked_add(carried.fee)
    } else {
        amount_in.checked_sub(carried.fee)
    }
    .ok_or(differs(details::FILLS_TAKER_FEE))?;
    let accepted = max_fee_bps.is_some_and(|max| {
        !product_lt(U256::from(max.get()), charged, carried.fee, U256::from(10_000u16))
    });
    if accepted { Ok(()) } else { Err(differs(details::FEE_ABOVE_ACCEPTED)) }
}

/// The least a wallet delivery of `amount_out` to `to` pays its recipient, as the escrow checks
/// it: on Polygon `⌈amount_out × 9 995 / 10 000⌉`, elsewhere all of it.
pub(crate) fn minimum_received(to: &VenueId, amount_out: U256) -> Option<U256> {
    match to {
        VenueId::Polymarket => mul_div_ceil(
            amount_out,
            U256::from(deployments::WALLET_SWAP_MIN_BPS),
            U256::from(10_000u16),
        ),
        _ => Some(amount_out),
    }
}

#[cfg(test)]
mod tests;