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
//! Lighter transfers as their API key signs them: Poseidon2 over Goldilocks as Lighter's plonky2
//! variant, the transfer's hash and owner message, and a sent transfer read back from its
//! `tx_info`. Checked against the vectors Lighter's Go libraries generate
//! (`tests/vectors/lighter.json`), which the server's port also passes.

mod constants;

use serde_json::Value;

use super::lighter;

/// Goldilocks: `2^64 - 2^32 + 1`.
const P: u64 = 0xFFFF_FFFF_0000_0001;
/// Lighter's transaction type of a transfer.
const TX_TYPE_TRANSFER: u64 = 12;
/// The largest integer a JSON number carries exactly, as Lighter's `tx_info` writes them.
const SAFE_INTEGER: u64 = (1 << 53) - 1;

/// An internal transfer between Lighter accounts, as its API key signs it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct LighterTransfer {
    /// The sending account's index.
    pub from: u64,
    /// The API key index signing it.
    pub api_key: u8,
    /// The receiving account's index.
    pub to: u64,
    /// The asset moved: 3 for USDC.
    pub asset: u8,
    /// The sending route: 0 for perps collateral.
    pub from_route: u8,
    /// The receiving route.
    pub to_route: u8,
    /// In the asset's base units.
    pub amount: u64,
    /// What Lighter charges the sender on top, in USDC base units.
    pub fee: u64,
    /// Thirty-two bytes the transfer carries; a fill's names it.
    pub memo: [u8; 32],
    /// When Lighter stops accepting it, in Unix milliseconds.
    pub expired_at: u64,
    /// The API key's nonce.
    pub nonce: u64,
}

impl LighterTransfer {
    /// A transfer of `amount` from account `from` to account `to`, both on their collateral
    /// route, signed by API key `api_key` at `nonce`, until `expired_at`.
    #[expect(clippy::too_many_arguments, reason = "Lighter's transfer, field by field")]
    pub fn new(
        from: u64,
        api_key: u8,
        to: u64,
        asset: u8,
        amount: u64,
        fee: u64,
        memo: [u8; 32],
        expired_at: u64,
        nonce: u64,
    ) -> Self {
        Self {
            from,
            api_key,
            to,
            asset,
            from_route: 0,
            to_route: 0,
            amount,
            fee,
            memo,
            expired_at,
            nonce,
        }
    }
}

/// A sent transfer read back from its `tx_info`, and its owner's signature (`L1Sig`).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TransferTxInfo {
    /// The transfer.
    pub transfer: LighterTransfer,
    /// The owner's `personal_sign` signature of its message, as sent.
    pub l1_signature: String,
}

/// A `tx_info` that is not a plain transfer: the field that failed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("Lighter transfer {0} is unreadable")]
pub struct UnreadableTransfer(pub &'static str);

/// Hashes field elements to five, without padding: each block of eight overwrites the rate.
pub fn hash_to_fp5(input: &[u64]) -> [u64; 5] {
    let mut state = [0u64; 12];
    for block in input.chunks(8) {
        state[..block.len()].copy_from_slice(block);
        permute(&mut state);
    }
    [state[0], state[1], state[2], state[3], state[4]]
}

/// The 40-byte hash a transfer's API key signs on chain `chain_id`, also its Lighter transaction
/// hash. Transaction attributes are not part of it: only the owner's message binds the memo.
pub fn transfer_hash(transfer: &LighterTransfer, chain_id: u64) -> [u8; 40] {
    const LOW: u64 = 0xFFFF_FFFF;
    let elements = [
        chain_id,
        TX_TYPE_TRANSFER,
        transfer.nonce,
        transfer.expired_at,
        transfer.from,
        u64::from(transfer.api_key),
        transfer.to,
        u64::from(transfer.asset),
        u64::from(transfer.from_route),
        u64::from(transfer.to_route),
        transfer.amount & LOW,
        transfer.amount >> 32,
        transfer.fee & LOW,
        transfer.fee >> 32,
    ];
    let mut out = [0u8; 40];
    for (bytes, limb) in out.as_chunks_mut::<8>().0.iter_mut().zip(hash_to_fp5(&elements)) {
        *bytes = limb.to_le_bytes();
    }
    out
}

/// The text the owner signs with `personal_sign` for `transfer` to another owner's account on
/// chain `chain_id`.
pub fn transfer_message(transfer: &LighterTransfer, chain_id: u64) -> String {
    lighter::transfer_message(&message_terms(transfer), chain_id)
}

/// What the owner message of `transfer` names.
pub(crate) fn message_terms(transfer: &LighterTransfer) -> lighter::Transfer {
    lighter::Transfer {
        nonce: transfer.nonce,
        from: transfer.from,
        from_route: transfer.from_route,
        api_key: transfer.api_key,
        to: transfer.to,
        to_route: transfer.to_route,
        asset: transfer.asset,
        amount: transfer.amount,
        fee: transfer.fee,
        memo: transfer.memo,
    }
}

/// Reads a sent transfer from its `tx_info` (Lighter's JSON), refusing transaction attributes.
pub fn read_transfer_tx_info(info: &Value) -> Result<TransferTxInfo, UnreadableTransfer> {
    let integer = |name: &'static str| {
        info.get(name)
            .and_then(Value::as_u64)
            .filter(|value| *value <= SAFE_INTEGER)
            .ok_or(UnreadableTransfer(name))
    };
    let small = |name: &'static str| {
        integer(name).and_then(|value| value.try_into().map_err(|_| UnreadableTransfer(name)))
    };
    let attributes = info.get("L2TxAttributes").unwrap_or(&Value::Null);
    let empty = match attributes {
        Value::Null => true,
        Value::Object(fields) => fields.is_empty(),
        Value::Array(items) => items.is_empty(),
        _ => false,
    };
    if !empty {
        return Err(UnreadableTransfer("L2TxAttributes"));
    }
    let memo: [u8; 32] = info
        .get("Memo")
        .and_then(Value::as_array)
        .and_then(|bytes| {
            bytes
                .iter()
                .map(|byte| byte.as_u64().and_then(|byte| u8::try_from(byte).ok()))
                .collect::<Option<Vec<u8>>>()
        })
        .and_then(|bytes| bytes.try_into().ok())
        .ok_or(UnreadableTransfer("Memo"))?;
    let l1_signature =
        info.get("L1Sig").and_then(Value::as_str).ok_or(UnreadableTransfer("L1Sig"))?.to_owned();
    Ok(TransferTxInfo {
        transfer: LighterTransfer {
            from: integer("FromAccountIndex")?,
            api_key: small("ApiKeyIndex")?,
            to: integer("ToAccountIndex")?,
            asset: small("AssetIndex")?,
            from_route: small("FromRouteType")?,
            to_route: small("ToRouteType")?,
            amount: integer("Amount")?,
            fee: integer("USDCFee")?,
            memo,
            expired_at: integer("ExpiredAt")?,
            nonce: integer("Nonce")?,
        },
        l1_signature,
    })
}

fn reduce(value: u128) -> u64 {
    u64::try_from(value % u128::from(P)).unwrap_or_default()
}

fn add(a: u64, b: u64) -> u64 {
    reduce(u128::from(a) + u128::from(b))
}

fn mul(a: u64, b: u64) -> u64 {
    reduce(u128::from(a) * u128::from(b))
}

fn external_layer(state: &mut [u64; 12]) {
    let mut s: [u128; 12] = state.map(u128::from);
    for i in (0..12).step_by(4) {
        let t01 = s[i] + s[i + 1];
        let t23 = s[i + 2] + s[i + 3];
        let t0123 = t01 + t23;
        let (x0, x2) = (s[i], s[i + 2]);
        s[i] = t0123 + t01 + s[i + 1];
        s[i + 1] = t0123 + s[i + 1] + 2 * x2;
        s[i + 2] = t0123 + t23 + s[i + 3];
        s[i + 3] = t0123 + s[i + 3] + 2 * x0;
    }
    let sums: [u128; 4] = std::array::from_fn(|i| s[i] + s[i + 4] + s[i + 8]);
    for (i, x) in state.iter_mut().enumerate() {
        *x = reduce(s[i] + sums[i % 4]);
    }
}

fn sbox(x: u64) -> u64 {
    let x3 = mul(mul(x, x), x);
    mul(mul(x3, x3), x)
}

fn permute(state: &mut [u64; 12]) {
    external_layer(state);
    for (round, full) in constants::EXTERNAL.iter().enumerate() {
        // The partial rounds sit between the two halves of the full rounds.
        if round == 4 {
            for constant in constants::INTERNAL {
                state[0] = sbox(add(state[0], constant));
                let sum = state.iter().fold(0, |acc, &x| add(acc, x));
                for (x, d) in state.iter_mut().zip(constants::DIAG) {
                    *x = add(sum, mul(*x, d));
                }
            }
        }
        for (x, c) in state.iter_mut().zip(full) {
            *x = sbox(add(*x, *c));
        }
        external_layer(state);
    }
}

#[cfg(test)]
mod tests;