Skip to main content

Crate lamarge

Crate lamarge 

Source
Expand description

§lamarge

Rust client for the LaMarge API: market data, the event feed, sign-in, venue setup, takes, transfers, withdrawals, external bridges of a move and passive market making on escrow venues.

Before a signer sees anything, the crate:

  • checks every item to sign against your request and the deployment values this release pins;
  • saves the signatures of takes, transfers, withdrawals, maker capital and wallet permits in your store::Journal before submitting them, and reuses them when the same request runs again; venue setup steps (setup permits included), closes and quote publications are not journalled and may sign again after an interruption;
  • keeps your client IDs stable across retries.

§Install

cargo add lamarge chrono serde_json
cargo add tokio --features macros,rt-multi-thread
cargo add alloy-signer-local

The crate runs on Tokio. Any alloy_signer::Signer signs: a local key, a KMS key or a Ledger. TLS is rustls with the platform verifier: slim and distroless images need system CA roots (ca-certificates). HTTP requests honour HTTPS_PROXY; the event feed’s WebSocket connects directly and, without a direct route, falls back to HTTP replay. Lighter’s public API is read directly to check account owners; ClientBuilder::lighter_reads sends those reads through your own client, from your address and within your rate budget. Amounts are base units of each venue’s token (types::Amount::parse_venue).

§Examples

§Market data

use lamarge::{Client, Environment, book::SweepTerms, types::VenueId};

#[tokio::main]
async fn main() -> lamarge::Result<()> {
    let client = Client::new(Environment::Production)?;
    client.check_deployment().await?;

    let book = client.market().book(&VenueId::Hyperliquid, &VenueId::Polymarket).await?;
    let terms = SweepTerms::new(Some(book.taker_fee_bps));
    if let Some(limits) = book.limits(None, &terms, chrono::Utc::now())? {
        println!("pay {} to {} base units", limits.minimum.pay, limits.maximum.pay);
    }
    Ok(())
}

§Take

From Hyperliquid margin into the session’s Polymarket account, priced from the book with 10 bps slippage. The whole request resumes the take: it is saved before the first call and reused on every run.

use alloy_signer_local::PrivateKeySigner;
use lamarge::{
    Client, Environment,
    book::{SweepTerms, slippage_minimum},
    flows::{Recipient, TakeRequest, TradeTerms},
    store::FileStore,
    types::{Amount, Bps, ClientId, VenueId},
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let signer: PrivateKeySigner = std::env::var("LAMARGE_PRIVATE_KEY")?.parse()?;
    let me = signer.address();
    let client = Client::new(Environment::Production)?;
    let session = client.sign_in(signer, FileStore::open("lamarge-state")?).await?;

    let (from, to) = (VenueId::Hyperliquid, VenueId::Polymarket);
    for venue in [&from, &to] {
        session.link_account(venue).await?;
    }
    let saved = "take-1.json";
    let request: TakeRequest = match std::fs::read(saved) {
        Ok(json) => serde_json::from_slice(&json)?,
        Err(_) => {
            let amount_in = Amount::parse_venue(&from, "100")?;
            let book = client.market().book(&from, &to).await?;
            let fee = book.taker_fee_bps;
            let swept = book.sweep(amount_in, &SweepTerms::new(Some(fee)), chrono::Utc::now())?;
            let min_out = slippage_minimum(swept.out, Bps::new(10).ok_or("slippage")?);
            let terms = TradeTerms::new(from, to, amount_in, min_out, Recipient::Account(me))
                .max_fee_bps(fee);
            let request = TakeRequest::new(ClientId::new("take-1")?, terms);
            std::fs::write(saved, serde_json::to_vec(&request)?)?;
            request
        }
    };
    let fills = session.take(&request).await?;
    println!("{} fills", fills.len());
    session.sign_out().await?;
    Ok(())
}

Runnable programs in examples/:

ExampleKeyDoes
market_datanonevenue prices, book limits, the public event feed
taker_transferfinanciala resumable transfer from Hyperliquid margin into Polymarket
maker_provisionfinancialHyperliquid setup, a maker credential, pool capital
maker_quotequotelease, quote lines, fills on the private feed

§Features

FeatureDefaultEnables
aws-lc-rsyesrustls with the aws-lc-rs provider (needs cmake on some platforms)
ringnorustls with the ring provider

One provider is required; with both, aws-lc-rs is used. The crate never installs a process-wide rustls provider.

§MSRV

Rust 1.94.1. It is raised only in a minor release, noted in the changelog.

§Documentation

The crate is developed in LaMarge’s repository, next to the server and the API contract. snowbl-capital/lamarge-sdk-rs mirrors each release; issues are welcome there. The TypeScript client is @lamarge/sdk (snowbl-capital/lamarge-sdk-ts).

§Licence

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Re-exports§

pub use error::Error;
pub use error::Result;
pub use host::BlockTag;
pub use host::ChainCall;
pub use host::ChainCallFuture;
pub use host::ChainReader;
pub use host::HostError;
pub use host::HostStream;
pub use host::HttpAnswer;
pub use host::HttpExchange;
pub use host::HttpExchangeFuture;
pub use host::HttpRequest;
pub use host::SendError;
pub use host::SendFuture;
pub use host::SendStatus;
pub use host::StatusFuture;
pub use host::StreamConnector;
pub use host::StreamFuture;
pub use host::Transaction;
pub use host::TransactionSender;
pub use alloy_dyn_abi;
pub use alloy_primitives;
pub use alloy_signer;
pub use alloy_sol_types;

Modules§

api
Resource handles: cheap borrows of a Client, Session or Quoter, one per API area. A handle is reachable only from the credentials allowed to call it, so an unauthorised call does not compile.
aster
Aster: the maker’s AsterDeliverer, which delivers a fill into a taker’s Aster account by the account’s own transfer, its Spot topped up from the margin by a trading agent first.
attestation
LaMarge’s attestations, checked by a signer that holds a taker’s key apart from the app that asks it: the request it is about to sign is the one LaMarge asks, and a take’s terms are the ones LaMarge committed to.
book
Book math: sweeps, minimum takes, limits and slippage floors, as the server matches a take.
delivery
Maker deliveries inside a venue: a fill delivered to a taker’s account on Lighter or Aster is the maker’s own transfer there, sent and reported by a VenueDeliverer.
error
Errors: one Error for every operation, with the server’s refusal in ApiError.
events
The event feed as a Stream, and state tracking over it.
flows
Multi-step operations run by a Session: takes, transfers, withdrawals, venue setup and maker capital, with their request types. Each checks every server payload before signing. A signature whose second copy could move funds or an allowance twice (takes, transfers, withdrawals, maker capital, wallet permits) is journalled before it is submitted and reused for a matching request. Venue setup steps (setup permits included), closes and quote publications are not journalled and may sign again after an interruption: a second copy has no further effect.
funds
What a linked account’s balance row (GET /v1/balances) allows: what a take pays without moving margin, what the relayer sweeps, what a withdrawal keeps back.
host
What a host supplies in place of the client’s own: every request to the API through HttpExchange, the event WebSocket’s connection through StreamConnector, and the transactions a flow sends through TransactionSender.
lighter
Lighter: the maker’s LighterDeliverer, which delivers a fill into a taker’s Lighter account by the pool account’s own transfer. The transfer’s hash and owner message are protocol::transfer_hash and protocol::transfer_message.
model
Response models of the API operations the SDK maps.
protocol
The protocol: pure, I/O-free checks of every server payload against the caller’s terms and the pinned deployments, the pins themselves, and the payloads they rebuild, under the names the TypeScript SDK’s @lamarge/sdk/protocol gives them, in snake case.
store
Persistence for in-flight operations: signatures saved before submission, transfer pointers and results, so an interrupted flow resumes instead of signing twice.
types
Value types shared by requests, responses and flows: amounts, prices, venues and ids.

Structs§

Address
An Ethereum address, 20 bytes in length.
Client
A LaMarge API client. Cheap to clone; clones share connections and configuration.
ClientBuilder
Configures a Client.
CredentialToken
A maker credential’s bearer secret (mk_…); parse a saved one with str::parse.
MakerCredential
What a quoting host needs besides its quote key: the credential’s identity and token. Persistable; Debug redacts the token.
QuoteIdentity
A delegated quote identity: the credential’s identity and the address that signs its quotes.
Quoter
A maker credential with its quote key: quotes, leases and cancels for one delegated identity, and reads its orders, fills and private events. It never moves capital.
RetryPolicy
How transient failures of retryable requests are retried: up to max_attempts attempts, waiting the server’s Retry-After or a jittered exponential backoff.
SavedSession
A session’s credentials, to persist and resume later with Client::resume_session. Debug redacts the token.
Session
A signed-in user: its signer, credentials and journal.
SessionToken
A session’s bearer secret; wrap a saved one with From<String>.

Enums§

Environment
A LaMarge deployment: where the API is and which app origin sign-in challenges name.

Traits§

LighterReads
Performs the client’s reads of Lighter’s public API in place of its own HTTP client, so they leave from the caller’s address and count in the caller’s rate budget there.
Signer
Asynchronous Ethereum signer.

Type Aliases§

B256
32-byte fixed byte-array type.
LighterRead
The future LighterReads::get returns: the status and body of the answer.
U256
256-bit unsigned integer type, consisting of 4, 64-bit limbs.