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
use alloy_primitives::keccak256;

use super::*;
use crate::error::VerificationKind;

fn bps(value: u16) -> Bps {
    Bps::new(value).unwrap()
}

fn id(text: &str) -> B256 {
    text.parse().unwrap()
}

/// `contracts/test/TakerFees.t.sol`'s vector: 3 000 units on the payment.
const CHARGED: &str = "0xde65f326692b00000000000000000bb8290decd9548b62a8d60345a988386fc8";

fn swap(tag: &str, fee: &str) -> B256 {
    id(&format!("0x{tag}{fee:0>20}{}", "ab".repeat(16)))
}

#[test]
fn a_swap_id_carries_its_fee_after_the_escrows_tag() {
    let fee = |id: B256| swap_fee(&id);
    assert_eq!(
        fee(id(CHARGED)),
        SwapFee { fee: U256::from(3_000u16), on_delivery: false, wallet: false }
    );
    assert_eq!(
        fee(swap("cc909c08081a", "0258")),
        SwapFee { fee: U256::from(600u16), on_delivery: true, wallet: false }
    );
    assert_eq!(
        fee(id(&format!("0x{}", "aa".repeat(32)))),
        SwapFee { fee: U256::ZERO, on_delivery: false, wallet: false }
    );
    assert_eq!(
        fee(swap("1b4c4374729e", "0bb8")),
        SwapFee { fee: U256::from(3_000u16), on_delivery: false, wallet: true }
    );
    assert_eq!(
        fee(swap("fcb0d9ddb285", "0")),
        SwapFee { fee: U256::ZERO, on_delivery: true, wallet: true }
    );
    // The largest fee ten bytes hold.
    assert_eq!(
        fee(swap("de65f326692b", &"ff".repeat(10))).fee,
        (U256::from(1u8) << 80) - U256::from(1u8)
    );
}

/// `contracts/test/WalletDelivery.t.sol`: the tags are the first six bytes of these hashes.
#[test]
fn the_tags_are_the_escrows() {
    for (text, tag) in [
        ("LaMarge fee on payment", FEE_ON_PAYMENT),
        ("LaMarge fee on delivery", FEE_ON_DELIVERY),
        ("LaMarge wallet, fee on payment", WALLET_FEE_ON_PAYMENT),
        ("LaMarge wallet, fee on delivery", WALLET_FEE_ON_DELIVERY),
    ] {
        assert_eq!(keccak256(text)[..6], tag, "{text}");
    }
}

fn check(
    swap_id: B256,
    taker_fee: u64,
    amounts: (u64, u64),
    on_delivery: bool,
    max: Option<u16>,
) -> Result<(), &'static str> {
    check_fee(
        &swap_id,
        U256::from(taker_fee),
        U256::from(amounts.0),
        U256::from(amounts.1),
        on_delivery,
        max.map(bps),
    )
    .map_err(|error| {
        assert_eq!(error.kind, VerificationKind::Differs);
        error.detail
    })
}

#[test]
fn a_fee_is_the_swap_ids_where_the_payment_says_within_the_takers_consent() {
    let amounts = (10_003_000, 10_000_000);
    assert_eq!(check(id(CHARGED), 3_000, amounts, false, Some(3)), Ok(()));
    assert_eq!(
        check(id(CHARGED), 3_000, amounts, false, Some(2)),
        Err(details::FEE_ABOVE_ACCEPTED)
    );
    assert_eq!(check(id(CHARGED), 3_000, amounts, false, None), Err(details::FEE_ABOVE_ACCEPTED));
    assert_eq!(check(id(CHARGED), 3_000, amounts, true, Some(3)), Err(details::FILLS_SWAP_ID));
    assert_eq!(check(id(CHARGED), 2_999, amounts, false, Some(3)), Err(details::FILLS_TAKER_FEE));
    // A fee larger than the payment it is part of.
    assert_eq!(
        check(id(CHARGED), 3_000, (2_999, 1), false, Some(100)),
        Err(details::FILLS_TAKER_FEE)
    );
    let plain = id(&format!("0x{}", "aa".repeat(32)));
    assert_eq!(check(plain, 0, amounts, false, None), Ok(()));
    assert_eq!(check(plain, 1, amounts, false, Some(3)), Err(details::FILLS_TAKER_FEE));
}

#[test]
fn a_wallet_delivery_fee_on_delivery_is_bounded_by_what_it_delivers() {
    let wallet = swap("fcb0d9ddb285", "0258");
    assert_eq!(check(wallet, 600, (2_001_300, 2_000_000), true, Some(3)), Ok(()));
    assert_eq!(
        check(wallet, 600, (2_001_300, 2_000_000), false, Some(3)),
        Err(details::FILLS_SWAP_ID)
    );
    assert_eq!(
        check(wallet, 600, (2_001_300, 2_000_000), true, Some(2)),
        Err(details::FEE_ABOVE_ACCEPTED)
    );
    // On delivery the bound is on what the offer delivers, fee included: 600 of 1 999 400 +
    // 600 is exactly 3 bps; one unit less delivered is above.
    assert_eq!(check(wallet, 600, (0, 1_999_400), true, Some(3)), Ok(()));
    assert_eq!(check(wallet, 600, (0, 1_999_399), true, Some(3)), Err(details::FEE_ABOVE_ACCEPTED));
}

#[test]
fn a_wallet_deliverys_least_received_is_the_escrows_floor_on_polygon() {
    let least = |venue: &VenueId, amount: u64| minimum_received(venue, U256::from(amount)).unwrap();
    assert_eq!(least(&VenueId::Polymarket, 1_005_000), U256::from(1_004_498u64));
    assert_eq!(least(&VenueId::Polymarket, 10_000), U256::from(9_995u64));
    for amount in 0..3_000u64 {
        let paid = least(&VenueId::Polymarket, amount);
        // The escrow reverts below it: `paid × 10 000 < amount × 9 995`.
        let floor = U256::from(amount) * U256::from(9_995u64);
        assert!(paid * U256::from(10_000u64) >= floor);
        assert!(paid.is_zero() || (paid - U256::from(1u8)) * U256::from(10_000u64) < floor);
    }
    assert_eq!(least(&VenueId::Hyperliquid, 1_005_000), U256::from(1_005_000u64));
    assert_eq!(least(&VenueId::Gmx, 1), U256::from(1u8));
    assert_eq!(
        minimum_received(&VenueId::Polymarket, U256::MAX),
        Some(U256::MAX - U256::MAX / U256::from(2_000u16))
    );
}

#[test]
fn the_price_within_a_budget_leaves_no_unit_its_fee_does_not_take() {
    for value in [0, 1, 3, 100] {
        let rate = bps(value);
        for budget in 0..3_000u64 {
            let budget = U256::from(budget);
            let price = price_within(budget, rate).unwrap();
            let next = price + U256::from(1u8);
            assert!(price + fee_on(price, rate) <= budget);
            assert!(next + fee_on(next, rate) > budget);
        }
    }
    assert_eq!(price_within(U256::from(2_001_900u64), bps(3)), Some(U256::from(2_001_300u64)));
    // No overflow at the top of the range.
    assert_eq!(price_within(U256::MAX, bps(0)), Some(U256::MAX));
    assert!(price_within(U256::MAX, bps(100)).unwrap() < U256::MAX);
}

#[test]
fn fees_round_down_exactly_without_overflow() {
    assert_eq!(fee_on(U256::from(2_001_300u64), bps(3)), U256::from(600u16));
    assert_eq!(fee_on(U256::from(9_999u64), bps(1)), U256::ZERO);
    assert_eq!(fee_on(U256::MAX, bps(10_000)), U256::MAX);
    assert_eq!(fee_on(U256::MAX, bps(100)), U256::MAX / U256::from(100u8));
}

#[test]
fn ratios_widen_then_narrow() {
    let max = U256::MAX;
    assert_eq!(mul_div(max, max, max), Some(max));
    assert_eq!(mul_div_ceil(max, max, max), Some(max));
    assert_eq!(mul_div_ceil(max, U256::from(1u8), U256::from(2u8)), Some(U256::from(1u8) << 255));
    assert_eq!(mul_div(max, U256::from(2u8), U256::from(1u8)), None);
    assert_eq!(mul_div(U256::from(1u8), U256::from(1u8), U256::ZERO), None);
    assert_eq!(mul_div_ceil(U256::from(1u8), U256::from(1u8), U256::ZERO), None);
    assert_eq!(mul_div(U256::from(7u8), U256::from(3u8), U256::from(2u8)), Some(U256::from(10u8)));
    assert_eq!(
        mul_div_ceil(U256::from(7u8), U256::from(3u8), U256::from(2u8)),
        Some(U256::from(11u8))
    );
    assert_eq!(
        mul_div_ceil(U256::from(6u8), U256::from(3u8), U256::from(2u8)),
        Some(U256::from(9u8))
    );
    assert!(product_lt(U256::from(1u8), max, U256::from(2u8), max));
    assert!(!product_lt(max, max, max, max));
}

#[test]
fn a_fee_needs_the_takers_consent_and_is_on_delivery_from_a_venue() {
    assert_eq!(take_fee(&VenueId::Polymarket, bps(3), None), Fee::default());
    assert_eq!(
        take_fee(&VenueId::Polymarket, bps(3), Some(bps(3))),
        Fee { bps: bps(3), on_delivery: false }
    );
    assert_eq!(
        take_fee(&VenueId::Lighter, bps(3), Some(bps(5))),
        Fee { bps: bps(3), on_delivery: true }
    );
}