lamarge 0.9.0

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
use alloy_primitives::{B256, address, b256, hex};
use alloy_signer::Signer;
use alloy_signer_local::PrivateKeySigner;
use futures_util::FutureExt as _;
use serde_json::{Value, json};

use super::*;

/// The server's attester test vector (`server/src/attester.rs`): key 0x0a…0a.
fn attester() -> PrivateKeySigner {
    PrivateKeySigner::from_bytes(&B256::repeat_byte(0x0a)).unwrap()
}

const SIGNER: Address = address!("00000000000000000000000000000000000a11ce");
/// 2027-01-15T08:00:00Z, the terms' `payBy`.
const PAY_BY: u64 = 1_800_000_000;

fn now() -> DateTime<Utc> {
    DateTime::from_timestamp(1_799_999_000, 0).unwrap()
}

fn terms_json() -> Value {
    json!({
        "take": "0x0123456789abcdef0123456789abcdef00000000000000000000000000000000",
        "from": "aster", "to": "hyperliquid", "recipient": SIGNER,
        "token": "0xb88339cb7199b77e23db6e890353e22632ba630f", "amountOut": "1000000",
        "payBy": PAY_BY,
    })
}

/// A wallet take's terms name the wallet token and the least received: 0.9995 native USDC to
/// a Polygon address.
fn wallet_terms_json() -> Value {
    let mut terms = terms_json();
    terms["to"] = json!("polymarket");
    terms["recipient"] = json!("0x000000000000000000000000000000000000b7b1");
    terms["token"] = json!("0x3c499c542cef5e3811e1192ce70d8cc03d5c3359");
    terms["amountOut"] = json!("999500");
    terms
}

/// The Aster transfer a taker paid from Aster signs, at chain 1666.
fn request() -> SignRequest {
    SignRequest::TypedData(json!({
        "domain": {
            "name": "AsterSignTransaction", "version": "1", "chainId": 1666,
            "verifyingContract": "0x0000000000000000000000000000000000000000",
        },
        "types": {"Message": [{"name": "msg", "type": "string"}]},
        "primaryType": "Message",
        "message": {"msg": "asset=USDT&amount=1&toAddress=0x…&clientTranId=…&nonce=1&user=0x…"},
    }))
}

fn sol_terms(terms: &Value) -> statements::TakeTerms {
    statements::TakeTerms {
        take: terms["take"].as_str().unwrap().parse().unwrap(),
        from: terms["from"].as_str().unwrap().to_owned(),
        to: terms["to"].as_str().unwrap().to_owned(),
        recipient: terms["recipient"].as_str().unwrap().parse().unwrap(),
        token: terms["token"].as_str().unwrap().parse().unwrap(),
        amountOut: terms["amountOut"].as_str().unwrap().parse().unwrap(),
        payBy: terms["payBy"].as_u64().unwrap(),
    }
}

fn take_hash(digest: B256, terms: &Value) -> B256 {
    statements::TakeAttestation { signer: SIGNER, digest, terms: sol_terms(terms) }
        .eip712_signing_hash(&domain())
}

fn wallet_hash(digest: B256, terms: &Value) -> B256 {
    let t = sol_terms(terms);
    let terms = statements::WalletTakeTerms {
        take: t.take,
        from: t.from,
        to: t.to,
        recipient: t.recipient,
        token: t.token,
        amountOut: t.amountOut,
        payBy: t.payBy,
        destination: "wallet".to_owned(),
    };
    statements::WalletTakeAttestation { signer: SIGNER, digest, terms }
        .eip712_signing_hash(&domain())
}

fn setup_hash(digest: B256) -> B256 {
    statements::SetupAttestation { signer: SIGNER, digest }.eip712_signing_hash(&domain())
}

fn sign(hash: B256) -> String {
    // A local key answers at once.
    let signature = Signer::sign_hash(&attester(), &hash).now_or_never().unwrap();
    format!("0x{}", hex::encode(signature.unwrap().as_bytes()))
}

fn sign_take(digest: B256, terms: &Value) -> String {
    sign(take_hash(digest, terms))
}

fn verify_at(
    attestation: &Value,
    request: &SignRequest,
    now: DateTime<Utc>,
) -> Result<Attested, NotAttested> {
    verify_attestation(request, SIGNER, attestation, &[attester().address()], now)
}

fn verify(attestation: &Value) -> Result<Attested, NotAttested> {
    verify_at(attestation, &request(), now())
}

fn refused(attestation: &Value, reason: &'static str) {
    assert_eq!(verify(attestation), Err(NotAttested(reason)), "{attestation}");
}

fn digest() -> B256 {
    request_digest(&request()).unwrap()
}

fn attested(terms: &Value, destination: Destination) -> Attested {
    let t = sol_terms(terms);
    Attested::Take {
        terms: TakeTerms {
            take: t.take,
            from: t.from.parse().unwrap(),
            to: t.to.parse().unwrap(),
            recipient: t.recipient,
            token: t.token,
            amount_out: Amount::new(t.amountOut),
            pay_by: t.payBy,
        },
        destination,
    }
}

/// "hashes the statements as the server signs them".
#[test]
fn statements_hash_as_the_server_signs_them() {
    let digest = B256::repeat_byte(0x07);
    assert_eq!(
        take_hash(digest, &terms_json()),
        b256!("83b97beb0baa6c8963f9c9585d54258041f1fa77d94ce4f4d9c63e4dc3658535")
    );
    assert_eq!(
        setup_hash(digest),
        b256!("7136d204951a88fa2f5ba4ba302df614766121bb066de565278504db4f99d418")
    );
    assert_eq!(
        wallet_hash(digest, &wallet_terms_json()),
        b256!("68b66081ea11267a03fec4eaab2b005bc11b0207e948a1c6d8f4a67c8ee96c18")
    );
}

/// "returns a take's terms for the request it attests".
#[test]
fn a_takes_terms_are_returned_for_the_request_it_attests() {
    let attestation =
        json!({"signature": sign_take(digest(), &terms_json()), "terms": terms_json()});
    assert_eq!(verify(&attestation), Ok(attested(&terms_json(), Destination::Venue)));
}

/// "returns a wallet take's terms with its destination, never read as a venue take's".
#[test]
fn a_wallet_takes_terms_are_never_read_as_a_venue_takes() {
    let mut terms = wallet_terms_json();
    terms["destination"] = json!("wallet");
    let signature = sign(wallet_hash(digest(), &wallet_terms_json()));
    let wallet = json!({"signature": signature, "terms": terms});
    assert_eq!(verify(&wallet), Ok(attested(&wallet_terms_json(), Destination::Wallet)));
    // The same terms under the other type, either way, are another statement.
    refused(
        &json!({"signature": signature, "terms": wallet_terms_json()}),
        "another key signed it",
    );
    let as_venue = sign_take(digest(), &wallet_terms_json());
    refused(&json!({"signature": as_venue, "terms": terms}), "another key signed it");
    let mut relinked = terms.clone();
    relinked["recipient"] = json!(SIGNER);
    refused(&json!({"signature": signature, "terms": relinked}), "another key signed it");
    // Exactly the seven terms, or those and `destination` "wallet".
    for (field, value) in
        [("destination", json!("venue")), ("destination", json!("Wallet")), ("extra", json!(1))]
    {
        let mut other = terms.clone();
        other[field] = value;
        refused(&json!({"signature": signature, "terms": other}), "unexpected take terms");
    }
    let closed = DateTime::from_timestamp(i64::try_from(PAY_BY).unwrap(), 0).unwrap();
    assert_eq!(
        verify_at(&wallet, &request(), closed),
        Err(NotAttested("its payment window closed"))
    );
}

/// "refuses terms, requests, signers and keys it does not attest".
#[test]
fn terms_requests_signers_and_keys_not_attested_are_refused() {
    let signature = sign_take(digest(), &terms_json());
    // The relink attack: the same payment shown with the signer's own address as the recipient.
    for (field, value) in [
        ("recipient", json!("0x000000000000000000000000000000000000beef")),
        ("amountOut", json!("2000000")),
    ] {
        let mut terms = terms_json();
        terms[field] = value;
        refused(&json!({"signature": signature, "terms": terms}), "another key signed it");
    }
    let attestation = json!({"signature": signature, "terms": terms_json()});
    let SignRequest::TypedData(mut other) = request() else { unreachable!() };
    other["message"] = json!({"msg": "asset=USDT&amount=2"});
    assert_eq!(
        verify_at(&attestation, &SignRequest::TypedData(other), now()),
        Err(NotAttested("another key signed it"))
    );
    let elsewhere = address!("000000000000000000000000000000000000b0b0");
    let attesters = [attester().address()];
    let cases: [(Address, &[Address], &'static str); 4] = [
        (elsewhere, &attesters, "another key signed it"),
        (SIGNER, ATTESTERS.development, "another key signed it"),
        (SIGNER, ATTESTERS.production, "another key signed it"),
        (SIGNER, &[], "no attester pinned"),
    ];
    for (signer, attesters, reason) in cases {
        assert_eq!(
            verify_attestation(&request(), signer, &attestation, attesters, now()),
            Err(NotAttested(reason))
        );
    }
}

/// "never reads a take's request as a setup step, nor a setup step's as a take".
#[test]
fn a_takes_request_is_never_a_setup_steps() {
    refused(&json!({"signature": sign_take(digest(), &terms_json())}), "another key signed it");
    let setup = sign(setup_hash(digest()));
    refused(&json!({"signature": setup, "terms": terms_json()}), "another key signed it");
}

/// "attests a setup step's `personal_sign` text".
#[test]
fn a_setup_steps_text_is_attested() {
    let request = SignRequest::Message("Register Lighter Account\n\npubkey: 0x…\n".to_owned());
    let signature = sign(setup_hash(request_digest(&request).unwrap()));
    assert_eq!(verify_at(&json!({"signature": signature}), &request, now()), Ok(Attested::Setup));
}

/// "refuses a request that is both a message and typed data, or neither".
#[test]
fn a_request_both_or_neither_is_refused() {
    let SignRequest::TypedData(typed) = request() else { unreachable!() };
    let mixed = json!({
        "message": "Register Lighter Account\n\npubkey: 0x…\n",
        "domain": {"name": "Unattested operation", "version": "1", "chainId": 1},
        "types": {"Empty": []}, "primaryType": "Empty",
    });
    let mut text = typed.clone();
    text["message"] = json!("text");
    let mut extra = typed;
    extra["extra"] = json!(1);
    for malformed in [mixed, text, extra] {
        assert_eq!(
            request_digest(&SignRequest::TypedData(malformed)),
            Err(NotAttested("the request is neither typed data nor a message"))
        );
    }
}

/// "refuses malformed and malleated signatures and unknown fields".
#[test]
fn malformed_and_malleated_signatures_and_unknown_fields_are_refused() {
    let signature = sign_take(digest(), &terms_json());
    assert_eq!(verify(&Value::Null), Err(NotAttested("no attestation")));
    refused(&json!({"signature": "0x1234", "terms": terms_json()}), "signature");
    refused(
        &json!({"signature": signature, "terms": terms_json(), "digest": "0x"}),
        "unexpected attestation fields",
    );
    let mut extra = terms_json();
    extra["extra"] = json!(1);
    refused(&json!({"signature": signature, "terms": extra}), "unexpected take terms");
    let bytes: [u8; 65] = hex::decode_to_array(&signature[2..]).unwrap();
    let n = U256::from_be_slice(&hex!(
        "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"
    ));
    let s = U256::from_be_slice(&bytes[32..64]);
    let mut twin = bytes;
    twin[32..64].copy_from_slice(&(n - s).to_be_bytes::<32>());
    twin[64] = if bytes[64] == 27 { 28 } else { 27 };
    refused(
        &json!({"signature": format!("0x{}", hex::encode(twin)), "terms": terms_json()}),
        "a high-s signature",
    );
    // The same signature with `v` 0 or 1 is another encoding of it.
    let mut parity = bytes;
    parity[64] -= 27;
    refused(
        &json!({"signature": format!("0x{}", hex::encode(parity)), "terms": terms_json()}),
        "signature",
    );
    let mut padded = terms_json();
    padded["amountOut"] = json!("0001000000");
    refused(&json!({"signature": signature, "terms": padded}), "amount");
}

/// A wallet hashes the domain under the declared `EIP712Domain`: it must be the one `domain`
/// gives, or the wallet signs a domain LaMarge never attested.
#[test]
fn a_declared_domain_type_must_be_the_domains_own() {
    let SignRequest::TypedData(typed) = request() else { unreachable!() };
    let field = |name: &str, kind: &str| json!({"name": name, "type": kind});
    let canonical = json!([
        field("name", "string"),
        field("version", "string"),
        field("chainId", "uint256"),
        field("verifyingContract", "address"),
    ]);
    let declared = |types: Value| {
        let mut request = typed.clone();
        request["types"]["EIP712Domain"] = types;
        request_digest(&SignRequest::TypedData(request))
    };
    assert_eq!(declared(canonical), request_digest(&request()));
    let trimmed = json!([field("name", "string"), field("version", "string")]);
    let reordered = json!([
        field("version", "string"),
        field("name", "string"),
        field("chainId", "uint256"),
        field("verifyingContract", "address"),
    ]);
    let extra = json!([
        field("name", "string"),
        field("version", "string"),
        field("chainId", "uint256"),
        field("verifyingContract", "address"),
        field("salt", "bytes32"),
    ]);
    for types in [trimmed, reordered, extra] {
        assert_eq!(
            declared(types),
            Err(NotAttested("the request's EIP712Domain differs from its domain"))
        );
    }
}