lamarge 0.7.0

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
use serde_json::{Value, json};

use super::*;
use crate::{
    error::VerificationKind,
    testing::{
        MAKER, NOW, OTHER, OWNER, at,
        fixtures::{ESCROW_HL, chain_with, fill, model, now},
        time,
    },
};

const ORDER_ID: &str = "0x31bf807825710f2bd3fcde1fe005b28a77bd3355a90275391ff6d44d731c5cfe";
const NONCE: &str = "18446744073709551615";

fn domain_types() -> Value {
    json!([
        {"name": "name", "type": "string"}, {"name": "version", "type": "string"},
        {"name": "chainId", "type": "uint256"}, {"name": "verifyingContract", "type": "address"},
    ])
}

fn order() -> EscrowOrder {
    let mut order = crate::testing::json::fixture("escrow_order");
    order["order_id"] = json!(ORDER_ID);
    order["owner"] = json!(OWNER);
    model(&order)
}

fn chain() -> EscrowChain {
    chain_with("hyperliquid", &json!({}))
}

/// Two USDC of `order()` back to Hyperliquid's spot, good for an hour.
fn withdrawal() -> Value {
    let deadline = NOW + 3_600;
    json!({
        "venue": "hyperliquid", "order_id": ORDER_ID, "amount": "2000000", "to_margin": true,
        "dex": 4_294_967_295_u32, "nonce": NONCE, "deadline": deadline,
        "to_sign": [{
            "kind": "escrow_withdrawal", "signer": OWNER,
            "typed_data": {
                "types": {
                    "EIP712Domain": domain_types(),
                    "Withdrawal": [
                        {"name": "owner", "type": "address"}, {"name": "offerId", "type": "bytes32"},
                        {"name": "amount", "type": "uint256"}, {"name": "toMargin", "type": "bool"},
                        {"name": "dex", "type": "uint32"}, {"name": "nonce", "type": "uint256"},
                        {"name": "deadline", "type": "uint256"},
                    ],
                },
                "primaryType": "Withdrawal",
                "domain": {"name": "LaMarge", "version": "1", "chainId": 999, "verifyingContract": ESCROW_HL},
                "message": {
                    "owner": OWNER, "offerId": ORDER_ID, "amount": "2000000", "toMargin": true,
                    "dex": 4_294_967_295_u32, "nonce": NONCE, "deadline": deadline.to_string(),
                },
            },
        }],
    })
}

fn check(prepared: &Value, amount: u128, to_margin: bool) -> Result<(), VerificationError> {
    let prepared: EscrowWithdrawalPreparation = model(prepared);
    check_escrow_withdrawal(&prepared, &order(), &chain(), Amount::from(amount), now(), to_margin)
}

/// "the withdrawal asked passes".
#[test]
fn the_withdrawal_asked_passes() {
    assert_eq!(check(&withdrawal(), 2_000_000, true), Ok(()));
    let prepared: EscrowWithdrawalPreparation = model(&withdrawal());
    let verified = verified_escrow_withdrawal(
        &prepared,
        &order(),
        &chain(),
        Amount::from(2_000_000_u128),
        now(),
        true,
    )
    .unwrap();
    assert_eq!(verified.not_after(), Some(NOW + 3_600));
}

/// "a withdrawal with … is refused".
#[test]
fn a_tampered_withdrawal_is_refused() {
    let item = "/to_sign/0";
    let message = "/to_sign/0/typed_data/message";
    let tamperings: [(&str, &str, Value); 17] = [
        ("an extra message field", message, json!({"extra": "unexpected"})),
        ("another kind", item, json!({"kind": "close_orders"})),
        ("another signer", item, json!({"signer": OTHER})),
        ("another primary type", "/to_sign/0/typed_data", json!({"primaryType": "FundOffer"})),
        ("another chain", "/to_sign/0/typed_data/domain", json!({"chainId": 137})),
        ("another contract", "/to_sign/0/typed_data/domain", json!({"verifyingContract": OTHER})),
        ("another owner", message, json!({"owner": OTHER})),
        ("another order", message, json!({"offerId": format!("0x{}", "1".repeat(64))})),
        ("to an address", message, json!({"toMargin": false})),
        ("a dex unlike the body's", message, json!({"dex": 0})),
        ("a dex no venue takes, in both", "", json!({"dex": 123})),
        ("a nonce unlike the body's", "", json!({"nonce": "1"})),
        ("a deadline past the hour", "", json!({"deadline": NOW + 7_200})),
        ("an expired deadline", "", json!({"deadline": NOW - 1})),
        ("another amount signed", message, json!({"amount": "3000000"})),
        ("another amount in the body", "", json!({"amount": "3000000"})),
        ("another venue", "", json!({"venue": "polymarket"})),
    ];
    for (name, pointer, patch) in tamperings {
        let mut prepared = withdrawal();
        let target = prepared.pointer_mut(pointer).unwrap().as_object_mut().unwrap();
        target.extend(patch.as_object().unwrap().clone());
        // A term both the body and the signature carry changes in both.
        if pointer.is_empty() && ["dex", "deadline"].iter().any(|key| patch.get(*key).is_some()) {
            let (key, value) = patch.as_object().unwrap().iter().next().unwrap();
            let signed = if key == "deadline" { json!(value.to_string()) } else { value.clone() };
            prepared.pointer_mut(message).unwrap()[key] = signed;
        }
        assert!(check(&prepared, 2_000_000, true).is_err(), "{name}");
    }
    let mut twice = withdrawal();
    let first = twice["to_sign"][0].clone();
    twice["to_sign"].as_array_mut().unwrap().push(first);
    assert_eq!(check(&twice, 2_000_000, true), Err(differs(details::TO_SIGN)));
}

/// "a withdrawal of nothing is refused".
#[test]
fn a_withdrawal_of_nothing_is_refused() {
    let mut prepared = withdrawal();
    prepared["amount"] = json!("0");
    prepared["to_sign"][0]["typed_data"]["message"]["amount"] = json!("0");
    assert_eq!(check(&prepared, 0, true), Err(differs(details::AMOUNT)));
}

/// "wallet release requires an explicit matching choice in the request and signature".
#[test]
fn a_wallet_release_needs_the_same_choice_asked_and_signed() {
    let mut prepared = withdrawal();
    prepared["to_margin"] = json!(false);
    prepared["dex"] = json!(0);
    prepared["to_sign"][0]["typed_data"]["message"]["toMargin"] = json!(false);
    prepared["to_sign"][0]["typed_data"]["message"]["dex"] = json!(0);
    assert_eq!(check(&prepared, 2_000_000, true), Err(differs(details::TO_MARGIN)));
    assert_eq!(check(&prepared, 2_000_000, false), Ok(()));
    prepared["to_sign"][0]["typed_data"]["message"]["toMargin"] = json!(true);
    assert_eq!(check(&prepared, 2_000_000, false), Err(differs(details::TO_MARGIN)));
}

/// "a substituted registry cannot authorize another escrow".
#[test]
fn a_substituted_registry_authorizes_no_other_escrow() {
    let mut prepared = withdrawal();
    let token = chain().token;
    prepared["to_sign"][0]["typed_data"]["domain"]["verifyingContract"] = json!(token);
    let prepared: EscrowWithdrawalPreparation = model(&prepared);
    let substituted = chain_with("hyperliquid", &json!({"escrow": token}));
    let refused = check_escrow_withdrawal(
        &prepared,
        &order(),
        &substituted,
        Amount::from(2_000_000_u128),
        now(),
        true,
    );
    assert_eq!(refused.unwrap_err().kind, VerificationKind::Deployment);
}

/// A maker's fill whose delivery inside Lighter was abandoned while the taker's payment stays
/// locked, and its refund consent, good for ten minutes.
fn refund_fixture() -> (Fill, Value) {
    let deadline = NOW + 600;
    let mut payment = fill("hyperliquid", "lighter", "10000000", "10000000");
    let patch = json!({
        "role": "maker", "maker_leg": "ABANDONED", "payment_leg": "LOCKED", "maker_recipient": MAKER,
        "payer": OTHER, "t2": time(1_200), "deliver_by": time(0), "delivery_hash": null,
    });
    payment.as_object_mut().unwrap().extend(patch.as_object().unwrap().clone());
    let payment: Fill = model(&payment);
    let prepared = json!({
        "deadline": deadline,
        "to_sign": [{
            "kind": "refund_payment", "fill_id": payment.id.as_uuid(), "signer": MAKER,
            "typed_data": {
                "types": {
                    "EIP712Domain": domain_types(),
                    "RefundPayment": [
                        {"name": "payer", "type": "address"}, {"name": "swapId", "type": "bytes32"},
                        {"name": "deadline", "type": "uint256"},
                    ],
                },
                "primaryType": "RefundPayment",
                "domain": {"name": "LaMarge", "version": "1", "chainId": 999, "verifyingContract": ESCROW_HL},
                "message": {"payer": OTHER, "swapId": payment.swap_id, "deadline": deadline.to_string()},
            },
        }],
    });
    (payment, prepared)
}

fn refund(fill: &Fill, prepared: &Value) -> Result<(), VerificationError> {
    check_payment_refund(fill, &model(prepared), now())
}

/// "only a maker payment abandoned inside its venue can be reviewed for an early refund".
#[test]
fn only_an_abandoned_makers_payment_is_refunded_early() {
    let (payment, prepared) = refund_fixture();
    assert!(can_refund_payment(&payment, now()));
    assert_eq!(refund(&payment, &prepared), Ok(()));
    let changes = [
        json!({"role": "taker"}),
        json!({"maker_leg": "LOCKED"}),
        json!({"to_venue": "polymarket", "deliver_by": null}),
        json!({"maker_leg": "CLAIMED"}),
        json!({"payment_leg": "REFUNDED"}),
        json!({"t2": "2000-01-01T00:00:00Z"}),
    ];
    for change in changes {
        let mut changed_fill = serde_json::to_value(&payment).unwrap();
        changed_fill.as_object_mut().unwrap().extend(change.as_object().unwrap().clone());
        let changed_fill: Fill = model(&changed_fill);
        assert_eq!(refund(&changed_fill, &prepared), Err(changed(details::REFUNDABLE)), "{change}");
    }
}

/// "refund consent binds the payment, recipient, chain, contract, fields and expiry".
#[test]
fn a_refund_consent_binds_its_terms() {
    let item = "/to_sign/0";
    let message = "/to_sign/0/typed_data/message";
    let domain = "/to_sign/0/typed_data/domain";
    let mutations: [(&str, Value, VerificationError); 10] = [
        (item, json!({"kind": "escrow_withdrawal"}), differs(details::KIND)),
        (
            item,
            json!({"fill_id": "0192f0a1-b2c3-7d4e-8f90-00000000beef"}),
            differs(details::FILL_ID),
        ),
        (item, json!({"signer": OTHER}), differs(details::SIGNER)),
        (message, json!({"payer": MAKER}), differs(details::PAYER)),
        (message, json!({"swapId": format!("0x{}", "34".repeat(32))}), differs(details::SWAP_ID)),
        (message, json!({"deadline": "0"}), differs(details::DEADLINE)),
        (message, json!({"recipient": MAKER}), differs(details::MESSAGE)),
        (domain, json!({"chainId": 137}), differs(details::DOMAIN)),
        (domain, json!({"verifyingContract": OTHER}), deployment(details::ESCROW)),
        (domain, json!({"version": "2"}), differs(details::DOMAIN)),
    ];
    for (pointer, patch, expected) in mutations {
        let (payment, mut prepared) = refund_fixture();
        let target = prepared.pointer_mut(pointer).unwrap().as_object_mut().unwrap();
        target.extend(patch.as_object().unwrap().clone());
        assert_eq!(
            refund(&payment, &prepared).map_err(|error| error.detail),
            Err(expected.detail),
            "{patch}"
        );
    }
    let (payment, prepared) = refund_fixture();
    let mut types = prepared.clone();
    types["to_sign"][0]["typed_data"]["types"]["RefundPayment"][0]["type"] = json!("bytes32");
    assert!(refund(&payment, &types).is_err());
    for delta in [-1, 3_601 + 30] {
        let (payment, mut prepared) = refund_fixture();
        let mut later = serde_json::to_value(&payment).unwrap();
        later["t2"] = json!("2099-01-01T00:00:00Z");
        let deadline = NOW + delta;
        prepared["deadline"] = json!(deadline);
        prepared["to_sign"][0]["typed_data"]["message"]["deadline"] = json!(deadline.to_string());
        assert_eq!(
            refund(&model(&later), &prepared),
            Err(details::stale(details::DEADLINE)),
            "{delta}"
        );
    }
    let mut none = prepared.clone();
    none["to_sign"] = json!([]);
    assert_eq!(refund(&payment, &none), Err(differs(details::TO_SIGN)));
    let mut twice = prepared.clone();
    let first = twice["to_sign"][0].clone();
    twice["to_sign"].as_array_mut().unwrap().push(first);
    assert_eq!(refund(&payment, &twice), Err(differs(details::TO_SIGN)));
    let mut early = serde_json::to_value(&payment).unwrap();
    early["t2"] = json!(time(599));
    assert_eq!(refund(&model(&early), &prepared), Err(differs(details::DEADLINE)));
}

/// "an early refund needs the payment locked and no venue delivery".
#[test]
fn an_early_refund_needs_the_payment_locked_and_undelivered() {
    let (payment, _) = refund_fixture();
    let lock = |state: u8| {
        let refund_at = u64::try_from(at(1_200).timestamp()).unwrap();
        EscrowLock::new(
            payment.amount_in.get(),
            payment.hashlock,
            payment.maker_recipient,
            refund_at,
            state,
            0,
        )
    };
    assert_eq!(check_refund_locks(&payment, &lock(1)), Ok(()));
    let mut escrowed = payment.clone();
    escrowed.deliver_by = None;
    assert_eq!(check_refund_locks(&escrowed, &lock(1)), Err(unsupported(details::DELIVER_BY)));
    let mut delivered = payment.clone();
    delivered.delivery_hash = Some("ab".to_owned());
    assert_eq!(check_refund_locks(&delivered, &lock(1)), Err(changed(details::DELIVERY_HASH)));
    assert_eq!(check_refund_locks(&payment, &lock(2)), Err(changed(details::PAYMENT_LOCK)));
}