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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! The protocol's entry points the internal checks do not already provide under the TypeScript
//! SDK's names: its pins as tables, its checks' venue-specific forms, and the payloads it builds.

use alloy_dyn_abi::TypedData;
use alloy_primitives::{Address, B256, U256};
use chrono::{DateTime, Duration, Utc};
use serde_json::{Map, Value};

use super::{
    aster,
    checks::{
        deadline_within,
        details::{self, at, changed, deployment, differs, stale, unsupported},
        escrow,
        take::{self, TakeIntent, TakeReads},
        withdrawal,
    },
    eip712::{self, CloseOrders, FundOffer, Message, PayTake, Permit, QuoteSet},
    relay,
    signing::Verified,
};
use crate::{
    api::{MoveRecipient, MoveRequest},
    deployments::{self, ESCROWS, VENUE_DOMAINS},
    error::VerificationError,
    flows::BridgeTerms,
    model::{Destination, Dex, Fill, TakePreparation, ToSign, ToSignKind, TransferIntent},
    types::{Amount, EscrowEnvironment, MaxParts, VenueId},
};

/// Lighter's L2 chain id, which its transfers and quote sets sign.
pub const LIGHTER_CHAIN_ID: u64 = deployments::LIGHTER.id;
/// Lighter's public API, read directly so account data does not depend on LaMarge.
pub const LIGHTER_API: &str = crate::transport::LIGHTER_API;
/// The index of production's Lighter API key, which sends a taker's transfers.
pub const TAKER_API_KEY: u8 = deployments::slots(EscrowEnvironment::Production).lighter_key_index;
/// The Lighter API key indexes of every environment.
pub const TAKER_API_KEYS: [u8; 2] = [
    deployments::slots(EscrowEnvironment::Production).lighter_key_index,
    deployments::slots(EscrowEnvironment::Development).lighter_key_index,
];

/// Relay's pinned contracts, from Relay's chains and verified sources, never from an answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct RelayPins {
    /// The EVM depository, the same address on every EVM chain.
    pub depository: Address,
    /// `HyperCore`'s depository account, which receives the payer's `SendAsset`.
    pub hyperliquid_depository: Address,
    /// The router that runs destination calls and executes EVM payouts, on every EVM chain.
    pub router: Address,
    /// The solver every order names: it is credited the deposit and owes the fill or the refund.
    pub solver: Address,
    /// The solver's chain.
    pub solver_chain_id: &'static str,
}

/// Relay (relay.link), the external bridge LaMarge plans and tracks: an order is accepted only if
/// its hash, contracts, solver, recipients and amounts match what these pins and the caller's
/// terms rebuild.
pub const RELAY: RelayPins = RelayPins {
    depository: relay::DEPOSITORY,
    hyperliquid_depository: relay::HYPERLIQUID_DEPOSITORY,
    router: relay::ROUTER,
    solver: relay::SOLVER,
    solver_chain_id: relay::SOLVER_CHAIN_ID,
};

/// The contracts the router's calls credit a Polymarket, GMX or Aster account through.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct VenueDeposits {
    /// GMX's `MultichainTransferRouter` on Arbitrum: `bridgeIn` credits what its vault received.
    pub gmx: Address,
    /// GMX's multichain vault on Arbitrum.
    pub gmx_vault: Address,
    /// LaMarge's `RelayCredit`, the same address on Polygon and BSC: it deposits the router's
    /// whole balance into a Polymarket or Aster account.
    pub relay_credit: Address,
}

/// The contracts a bridge credits a venue account through.
pub const VENUE_DEPOSITS: VenueDeposits = VenueDeposits {
    gmx: relay::GMX_ROUTER,
    gmx_vault: relay::GMX_VAULT,
    relay_credit: relay::RELAY_CREDIT,
};

/// The decimals of `venue`'s token; an unpinned venue is refused (`Unsupported`, `venue`).
pub fn decimals_of(venue: &VenueId) -> Result<u8, VerificationError> {
    deployments::chain(venue).map(|chain| chain.decimals).ok_or(unsupported(details::VENUE))
}

/// Whether `venue`'s requests may name `contract` as their escrow: on an escrow venue, any
/// pinned deployment of its chain, whichever environment's; on a venue settled inside itself, its
/// one pinned signing domain.
pub fn is_pinned_escrow(venue: &VenueId, contract: Address) -> bool {
    let Some(chain) = deployments::chain(venue) else {
        return false;
    };
    if deployments::is_venue_settled(venue) {
        VENUE_DOMAINS.iter().any(|domain| domain.venue == *venue && domain.address == contract)
    } else {
        ESCROWS.iter().any(|escrow| escrow.chain_id == chain.id && escrow.address == contract)
    }
}

/// Checks that every escrow request among `items` is signed in a pinned domain, whichever
/// environment's: a `fund` or `pay_take` in a pinned escrow, a `quote_set` in a pinned escrow or a
/// venue's own signing domain. A request of another kind is not looked at. Refused with
/// `Deployment`, `escrow`, at the request's index.
pub fn require_signing_domains(items: &[ToSign]) -> Result<(), VerificationError> {
    for (index, item) in items.iter().enumerate() {
        let quote_set = item.kind == ToSignKind::QuoteSet;
        if !quote_set && item.kind != ToSignKind::Fund && item.kind != ToSignKind::PayTake {
            continue;
        }
        let domain = item.typed_data.get("domain");
        let id = domain.and_then(|domain| domain.get("chainId")).and_then(Value::as_u64);
        let contract = domain
            .and_then(|domain| domain.get("verifyingContract"))
            .and_then(Value::as_str)
            .and_then(eip712::address_text);
        let pinned = id.zip(contract).is_some_and(|(id, contract)| {
            deployments::escrow_environment(id, contract).is_some()
                || (quote_set
                    && VENUE_DOMAINS
                        .iter()
                        .any(|domain| domain.chain_id == id && domain.address == contract))
        });
        if !pinned {
            return Err(at(deployment(details::ESCROW), index));
        }
    }
    Ok(())
}

/// Checks a request to sign on `venue` before any wallet prompt: its exact EIP-712 types and a
/// domain `environment` pins. A `QuoteSet`, `FundOffer`, `PayTake` or `CloseOrders` is signed in
/// the environment's escrow on the venue's chain (a venue settled inside itself signs quote sets
/// only, in its own domain); a `Permit` in the domain of the venue's token, to that escrow. Any
/// other primary type is refused (`Differs`, `primaryType`). Stricter than the TypeScript SDK's
/// `checkEscrowTyped`, which accepts any pinned environment's escrow: the escrow is
/// `environment`'s.
pub fn check_escrow_typed(
    typed: &Value,
    venue: &VenueId,
    environment: EscrowEnvironment,
) -> Result<(), VerificationError> {
    match typed.get("primaryType").and_then(Value::as_str) {
        Some("QuoteSet") => {
            escrow::check_escrow_typed::<QuoteSet>(typed, venue, environment)?;
        }
        Some("FundOffer") => {
            escrow::check_escrow_typed::<FundOffer>(typed, venue, environment)?;
        }
        Some("PayTake") => {
            escrow::check_escrow_typed::<PayTake>(typed, venue, environment)?;
        }
        Some("CloseOrders") => {
            escrow::check_escrow_typed::<CloseOrders>(typed, venue, environment)?;
        }
        Some("Permit") => {
            let chain = deployments::chain(venue).ok_or(unsupported(details::VENUE))?;
            let domain = eip712::permit_domain(chain).ok_or(unsupported(details::VENUE))?;
            let escrow =
                deployments::escrow(chain.id, environment).ok_or(unsupported(details::VENUE))?;
            if eip712::parse_in::<Permit>(typed, &domain)?.message.spender != escrow {
                return Err(differs(details::SPENDER));
            }
        }
        _ => return Err(differs(details::PRIMARY_TYPE)),
    }
    Ok(())
}

/// Checks that `deadline` (Unix seconds) is after `now` and at most `seconds` ahead of it, with a
/// 30-second clock margin (`Stale`, `deadline`).
pub fn check_deadline(
    deadline: U256,
    seconds: i64,
    now: DateTime<Utc>,
) -> Result<(), VerificationError> {
    if deadline_within(deadline, now.timestamp(), seconds) {
        Ok(())
    } else {
        Err(stale(details::DEADLINE))
    }
}

/// The fields of each `LockPayment` a `PayTake`'s typed data names: `LockPayment`'s fields.
const LOCK_PAYMENT_FIELDS: usize = 15;

/// The payments of a `PayTake`'s typed data, as the server wrote them: one to eight, each with
/// exactly `LockPayment`'s fields (`Differs`, `payments`). Their values are checked by
/// [`check_take`](super::check_take).
pub fn take_payments(typed: &Value) -> Result<Vec<&Map<String, Value>>, VerificationError> {
    let error = differs(details::PAYMENTS);
    let payments = typed.pointer("/message/payments").and_then(Value::as_array).ok_or(error)?;
    let payments = payments
        .iter()
        .map(|payment| payment.as_object().filter(|fields| fields.len() == LOCK_PAYMENT_FIELDS))
        .collect::<Option<Vec<_>>>()
        .ok_or(error)?;
    if payments.is_empty() || payments.len() > usize::from(MaxParts::MAX.get()) {
        return Err(error);
    }
    Ok(payments)
}

/// Checks a send (`send`) or a withdrawal of `amount` by `signer` to `destination` on `venue` at
/// `now`: [`check_send`](super::check_send) or [`check_withdrawal`](super::check_withdrawal). A
/// Polymarket operation (`Op`) is only a send. `dex` as either takes it.
#[expect(
    clippy::too_many_arguments,
    reason = "the TypeScript checkTransfer, argument for argument"
)]
pub fn check_transfer(
    typed: &Value,
    venue: &VenueId,
    signer: Address,
    destination: Address,
    amount: Amount,
    send: bool,
    now: DateTime<Utc>,
    dex: Option<&Dex>,
) -> Result<Verified, VerificationError> {
    if send {
        withdrawal::check_send(typed, venue, signer, destination, amount, now, dex)
    } else if typed.get("primaryType").and_then(Value::as_str) == Some("Op") {
        Err(unsupported(details::PRIMARY_TYPE))
    } else {
        withdrawal::check_withdrawal(typed, venue, signer, destination, amount, now, dex)
    }
}

/// Checks an Aster request (`Message{msg}` in Aster's signing domain at `chain_id`: its
/// transfers' chain, or BSC's for agent approvals and withdrawals) and returns its `msg`.
pub fn check_aster_request(typed: &Value, chain_id: u64) -> Result<String, VerificationError> {
    Ok(eip712::parse_in::<Message>(typed, &aster::domain(chain_id))?.message.msg)
}

/// `Message{msg}` in Aster's signing domain at `chain_id`: its transfers' chain, or BSC's for
/// agent approvals and withdrawals.
pub fn aster_request(msg: &str, chain_id: u64) -> TypedData {
    eip712::typed(&Message { msg: msg.to_owned() }, aster::domain(chain_id))
}

/// Reads an Aster transfer between accounts: its request at Aster's transfer chain, whose `msg`
/// is exactly `asset=USDT&amount=…&toAddress=…&clientTranId=…&nonce=…&user=…` (`Differs`,
/// `aster transfer`).
pub fn aster_transfer(typed: &Value) -> Result<aster::Transfer, VerificationError> {
    Ok(take::aster_transfer(typed)?.1)
}

/// Base units of USDT as Aster takes them: a decimal amount of six decimals at most, rounded up
/// so the recipient never gets less. `None` above `2^256 - 1`.
pub fn aster_amount(units: U256) -> Option<String> {
    let decimals = deployments::ASTER.decimals;
    let rounded = deployments::venue_units(units, &VenueId::Aster)?;
    let unit = U256::from(10u8).pow(U256::from(decimals));
    let fraction = (rounded % unit).to_string();
    let fraction = format!("{fraction:0>width$}", width = usize::from(decimals));
    let fraction = fraction.trim_end_matches('0');
    let whole = rounded / unit;
    Some(if fraction.is_empty() { whole.to_string() } else { format!("{whole}.{fraction}") })
}

/// Checks that an Aster `transfer` pays `fill`'s `amount_in`, as Aster carries it in six decimals
/// rounded up, from its payer to its maker's recipient, under the fill's id (`Differs`,
/// `aster transfer`).
pub fn check_aster_transfer(
    transfer: &aster::Transfer,
    fill: &Fill,
) -> Result<(), VerificationError> {
    let owed = fill.amount_in.get();
    let within = owed
        .checked_add(deployments::ASTER.step())
        .is_some_and(|limit| transfer.amount >= owed && transfer.amount < limit);
    let ok = within
        && transfer.to == fill.maker_recipient
        && transfer.user == fill.payer
        && transfer.client_id == aster::client_id(fill.id);
    if ok { Ok(()) } else { Err(differs(details::ASTER_TRANSFER)) }
}

/// [`check_take`](super::check_take) of a take paid from an escrow venue (Hyperliquid,
/// Polymarket, GMX): its one `PayTake`. A take paid from another venue is refused
/// (`Unsupported`, `venue`).
pub fn check_take_intent(
    prepared: &TakePreparation,
    intent: &TakeIntent,
    reads: TakeReads<'_>,
    environment: EscrowEnvironment,
    now: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
    if deployments::is_venue_settled(&intent.from) {
        return Err(unsupported(details::VENUE));
    }
    take::check_take(prepared, intent, reads, environment, now)
}

/// [`check_take`](super::check_take) of a take paid from Lighter: the owner message of the one
/// transfer paying exactly its fill from the payer's linked account. A take paid from another
/// venue is refused (`Unsupported`, `venue`).
pub fn check_lighter_take_intent(
    prepared: &TakePreparation,
    intent: &TakeIntent,
    reads: TakeReads<'_>,
    environment: EscrowEnvironment,
    now: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
    if intent.from != VenueId::Lighter {
        return Err(unsupported(details::VENUE));
    }
    take::check_take(prepared, intent, reads, environment, now)
}

/// [`check_take`](super::check_take) of a take paid from Aster: the payer's transfer of its fill's
/// amount to the maker's account under the fill id, its nonce far enough ahead for LaMarge to
/// relay it and within Aster's window when relayed. A take paid from another venue is refused
/// (`Unsupported`, `venue`).
pub fn check_aster_take_intent(
    prepared: &TakePreparation,
    intent: &TakeIntent,
    reads: TakeReads<'_>,
    environment: EscrowEnvironment,
    now: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
    if intent.from != VenueId::Aster {
        return Err(unsupported(details::VENUE));
    }
    take::check_take(prepared, intent, reads, environment, now)
}

/// Checks a route's second transfer, as LaMarge made it, against the route's first (`first`,
/// whose `then` names the route's end): it continues the first from its destination, paid by the
/// hub `hub` to the route's recipient, spends no more than `delivers` (what the first take
/// delivers on the hub venue) and at least 1% of the plan, at the planned price, and withdraws
/// nothing (`Changed`, `destination` or `amount`).
pub fn check_route_intent(
    first: &TransferIntent,
    second: &TransferIntent,
    hub: Address,
    delivers: U256,
) -> Result<(), VerificationError> {
    let then = first.then.as_ref().ok_or(changed(details::DESTINATION))?;
    let same = second.previous_transfer_id == Some(first.id)
        && second.from == first.to
        && second.to == then.to
        && second.payer == hub
        && second.recipient == then.recipient
        && second.destination == then.destination.clone().unwrap_or(Destination::Venue)
        && second.max_fee_bps == then.max_fee_bps
        && second.withdrawal_preparation.is_none();
    if !same {
        return Err(changed(details::DESTINATION));
    }
    let (pays, planned) = (second.amount_in.get(), then.amount_in.get());
    let share = then.min_out.get().checked_mul(pays).map(|scaled| scaled / planned);
    let ok = !pays.is_zero()
        && pays <= delivers
        && pays.checked_mul(U256::from(100u8)).is_some_and(|hundred| hundred >= planned)
        && share.is_some_and(|share| second.min_out.get() >= share);
    if ok { Ok(()) } else { Err(changed(details::AMOUNT)) }
}

/// What a bridge of `amount_in` (origin base units) must do for the move `request`:
/// [`BridgeTerms::for_move`]. [`BridgeTerms::from_wallet`] starts it from the payer's wallet on
/// the origin chain instead.
pub fn bridge_expectation(
    request: &MoveRequest,
    recipient: MoveRecipient,
    amount_in: Amount,
) -> crate::Result<BridgeTerms> {
    BridgeTerms::for_move(request, recipient, amount_in)
}

/// Checks Relay's `order` (`protocol.v2.orderData`) against `expect` at `now` (Unix seconds) and
/// returns its id: its hash, solver, input, refunds, output, recipient, floor and calls are the
/// ones the pins and `expect` rebuild.
pub fn check_bridge_order(
    order: &Value,
    expect: &BridgeTerms,
    now: i64,
) -> Result<B256, VerificationError> {
    relay::check_bridge_order(order, &expect.expectation(), now).map(|checked| checked.id)
}

/// The `HyperCore` `SendAsset` of `amount` (6 decimals) to Relay's depository, nonce `nonce`, in
/// Hyperliquid's signing domain. It leaves from the bridge's `source_dex`: the payer's perps
/// (`""`) or, for a unified account, `"spot"`; anything else, or none, is refused (`Differs`,
/// `sourceDex`).
pub fn bridge_send_asset(
    amount: U256,
    nonce: u64,
    source_dex: Option<&str>,
) -> Result<TypedData, VerificationError> {
    Ok(relay::bridge_send_asset(amount, nonce, source_dex)?.typed_data())
}

/// Venue names as the account-link challenge writes them.
fn link_name(venue: &VenueId) -> Option<&'static str> {
    match venue {
        VenueId::Hyperliquid => Some("Hyperliquid"),
        VenueId::Polymarket => Some("Polymarket Perps"),
        VenueId::Lighter => Some("Lighter"),
        VenueId::Aster => Some("Aster"),
        VenueId::Gmx => Some("GMX"),
        VenueId::Unknown(_) => None,
    }
}

/// Checks the message `address` signs to be linked on `venue` under `master`: its six lines,
/// naming all three, `nonce` and `expires_at`, valid ten minutes at most from `now`. Returns the
/// text to sign with `personal_sign`, signable until it expires.
pub fn check_link_challenge(
    message: &str,
    nonce: &str,
    expires_at: &str,
    address: Address,
    master: Address,
    venue: &VenueId,
    now: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
    let name = link_name(venue).ok_or(unsupported(details::VENUE))?;
    let lines: Vec<&str> = message.split('\n').collect();
    let expected = [
        format!("LaMarge: link a {name} account"),
        String::new(),
        format!("Account: {address:#x}"),
        format!("Master account: {master:#x}"),
        format!("Nonce: {nonce}"),
        format!("Expires: {expires_at}"),
    ];
    let exact = lines.len() == expected.len()
        && lines.iter().zip(&expected).enumerate().all(|(index, (line, wanted))| {
            // Addresses compare in any case.
            if index == 2 || index == 3 {
                line.eq_ignore_ascii_case(wanted)
            } else {
                *line == wanted.as_str()
            }
        });
    if !exact {
        return Err(differs(details::CHALLENGE));
    }
    let expires = DateTime::parse_from_rfc3339(expires_at)
        .map_err(|_| differs(details::CHALLENGE))?
        .with_timezone(&Utc);
    if expires <= now || expires > now + Duration::minutes(10) {
        return Err(stale(details::CHALLENGE_WINDOW));
    }
    Ok(Verified::text(message.to_owned(), address, Some(expires.timestamp())))
}

#[cfg(test)]
mod tests;