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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! Take checks: escrow payments, Lighter and Aster payments, destinations and minimums.
//!
//! [`check_take`] is the one entry: it binds every fill and the one payment request to the
//! caller's terms, and whenever the take delivers into Lighter, to the owner Lighter itself
//! reports for the delivering account.

use std::collections::{BTreeSet, HashSet};

use alloy_primitives::{Address, B256, U256, hex};
use chrono::{DateTime, Utc};
use serde_json::Value;

use super::{
    LighterOwners,
    details::{self, at, changed, differs, stale, unsupported},
    differs_unless, escrow, funding, signed, sum,
};
use crate::{
    deployments,
    error::VerificationError,
    model::{
        AsterTransferItem, Destination, Fill, FillRole, Funding, LighterTransferItem, Take,
        TakePreparation, TakeSignRequest, ToSignKind, WalletFunding,
    },
    protocol::{
        aster,
        eip712::{self, Message, PayTake},
        fees, lighter,
        signing::Verified,
    },
    types::{Amount, Bps, EscrowEnvironment, MaxParts, VenueId},
};

/// The most seconds to a take's `pay_by`.
const PAY_WINDOW_SECONDS: i64 = 90;

/// Where a take delivers on its receiving venue, as the caller states it: never taken from the
/// API.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Delivery {
    /// Into this account, linked on the receiving venue (for Lighter, the owner of the
    /// delivering account index).
    Account(Address),
    /// By plain transfer to this address on the receiving venue's escrow chain.
    Wallet(Address),
}

impl Delivery {
    fn recipient(self) -> Address {
        match self {
            Self::Account(address) | Self::Wallet(address) => address,
        }
    }

    fn wallet(self) -> bool {
        matches!(self, Self::Wallet(_))
    }
}

/// The caller's terms a take is checked against.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TakeIntent {
    /// The venue paying.
    pub from: VenueId,
    /// The venue receiving.
    pub to: VenueId,
    /// The most paid, in `from` base units.
    pub amount_in: Amount,
    /// The least received, in `to` base units.
    pub min_out: Amount,
    /// The most fills.
    pub max_parts: MaxParts,
    /// `None`: no fee accepted.
    pub max_fee_bps: Option<Bps>,
    /// Paid from the escrow-chain wallet rather than the venue account.
    pub wallet_funding: bool,
    /// Where the take delivers.
    pub delivery: Delivery,
    /// The session address: the payer and signer.
    pub payer: Address,
    /// The payer's linked Lighter account index, for a take paid from Lighter.
    pub payer_account: Option<u64>,
    /// Signed at once with a transfer's withdrawal: a route's pay window, and signable only
    /// until the at-once cutoff leaves time to sign.
    pub at_once: bool,
    /// A grouped route's second take, signed before the first delivers: a route's pay window.
    pub route: bool,
}

/// What the flow read for the check: Lighter's owners of the accounts [`lighter_accounts`]
/// names, and for a take from wallet funds, a fresh read of them (excluding this take).
#[derive(Debug, Clone, Copy)]
pub struct TakeReads<'a> {
    /// Lighter's owners of the accounts [`lighter_accounts`] names.
    pub lighter_owners: &'a LighterOwners,
    /// For a take from wallet funds, a fresh read of them (`GET /v1/wallets/{venue}`).
    pub wallet_funds: Option<&'a WalletFunding>,
}

/// Checks a prepared take (`POST /v1/takes`) against `intent` at `now` and returns its one
/// payment to sign: a `PayTake` from an escrow venue, the Lighter owner message of a take paid
/// from Lighter, or the Aster transfer request of a take paid from Aster.
pub fn check_take(
    prepared: &TakePreparation,
    intent: &TakeIntent,
    reads: TakeReads<'_>,
    environment: EscrowEnvironment,
    now: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
    let take = &prepared.take;
    if intent.delivery.wallet() && wallet_token(&intent.to).is_none() {
        return Err(unsupported(details::DESTINATION));
    }
    let funding = if intent.wallet_funding { Funding::Wallet } else { Funding::Venue };
    let funded = |value: &Option<Funding>| value.as_ref().unwrap_or(&Funding::Venue) == &funding;
    if !funded(&take.funding) || !take.fills.iter().all(|fill| funded(&fill.funding)) {
        return Err(differs(details::FUNDING));
    }
    let kind = payment_kind(&intent.from)?;
    if !prepared.to_sign.iter().all(|item| *item.kind() == kind) {
        return Err(differs(details::TO_SIGN_KIND));
    }
    check_minimum_received(take, intent)?;
    if intent.to == VenueId::Lighter {
        check_lighter_destination(&take.fills, intent.delivery.recipient(), reads.lighter_owners)?;
    }
    if intent.wallet_funding {
        let funds = reads.wallet_funds.ok_or(changed(details::WALLET_FUNDS))?;
        let spendable =
            funding::check_wallet_funding(funds, &intent.from, intent.payer, environment, now)?;
        if spendable < intent.amount_in.get() {
            return Err(changed(details::WALLET_FUNDS));
        }
    }
    let now = now.timestamp();
    match &intent.from {
        VenueId::Lighter => {
            check_lighter_take(prepared, intent, reads.lighter_owners, environment, now)
        }
        VenueId::Aster => check_aster_take(prepared, intent, now),
        _ => check_escrow_take(prepared, intent, environment, now),
    }
}

/// The Lighter account indexes whose owners [`check_take`] needs: a delivery into Lighter's
/// account, and a Lighter payment's two accounts.
pub fn lighter_accounts(prepared: &TakePreparation, intent: &TakeIntent) -> BTreeSet<u64> {
    let mut indexes = BTreeSet::new();
    if intent.to == VenueId::Lighter {
        let delivered = prepared.take.fills.iter().filter_map(|fill| fill.delivery_to.as_deref());
        indexes.extend(delivered.filter_map(account_index));
    }
    for item in &prepared.to_sign {
        if let TakeSignRequest::Lighter(item) = item {
            indexes.extend([item.typed_data.from_account_index, item.typed_data.to_account_index]);
        }
    }
    indexes
}

/// The nonce, in microseconds, of a take's Aster transfer request, as it must be named to have
/// LaMarge issue the request again.
pub(crate) fn aster_nonce(item: &AsterTransferItem) -> Result<u64, VerificationError> {
    Ok(aster_transfer(&item.typed_data)?.1.nonce)
}

/// Until when, in Unix seconds, a reserved take can still be signed: its earliest `pay_by`,
/// sooner for an Aster transfer whose nonce must stay ahead, unless LaMarge issues that request
/// again right before it is signed (`aster_reissue`).
pub fn signable_until(prepared: &TakePreparation) -> Result<i64, VerificationError> {
    let mut until = prepared.take.fills.iter().map(|fill| fill.pay_by.timestamp()).min();
    if !prepared.aster_reissue {
        for item in &prepared.to_sign {
            if let TakeSignRequest::Aster(item) = item {
                let ahead = nonce_seconds(aster_nonce(item)?) - aster::NONCE_AHEAD_SECONDS;
                until = Some(until.map_or(ahead, |until| until.min(ahead)));
            }
        }
    }
    until.ok_or(differs(details::FILLS))
}

/// The server's submission cutoff, in Unix seconds, for a take signed at once with its
/// withdrawal.
pub(crate) fn at_once_cutoff(prepared: &TakePreparation) -> Result<i64, VerificationError> {
    Ok(signable_until(prepared)? - signed(deployments::AT_ONCE_SEND_MARGIN_SECONDS))
}

/// The last second a take may be signed: before its [`signable_until`], or signed at once, while
/// the at-once cutoff leaves its signing seconds.
fn signing_bound(
    prepared: &TakePreparation,
    intent: &TakeIntent,
) -> Result<i64, VerificationError> {
    let bound = if intent.at_once {
        at_once_cutoff(prepared)? - signed(deployments::AT_ONCE_SIGNING_SECONDS)
    } else {
        signable_until(prepared)?
    };
    Ok(bound - 1)
}

fn nonce_seconds(nonce: u64) -> i64 {
    signed(nonce / 1_000_000)
}

/// The request kind paying a take from `from`.
pub fn payment_kind(from: &VenueId) -> Result<ToSignKind, VerificationError> {
    match from {
        VenueId::Lighter => Ok(ToSignKind::LighterTransfer),
        VenueId::Aster => Ok(ToSignKind::AsterTransfer),
        VenueId::Hyperliquid | VenueId::Polymarket | VenueId::Gmx => Ok(ToSignKind::PayTake),
        VenueId::Unknown(_) => Err(unsupported(details::VENUE)),
    }
}

fn wallet_token(venue: &VenueId) -> Option<Address> {
    deployments::chain(venue)?.wallet_token
}

fn account_index(text: &str) -> Option<u64> {
    if !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit()) {
        text.parse().ok()
    } else {
        None
    }
}

/// A wallet take's `minimum_received` is the least its recipient gets of the wallet token for
/// all it delivers, as the escrow bounds it; a venue take's is none.
pub fn check_minimum_received(take: &Take, intent: &TakeIntent) -> Result<(), VerificationError> {
    let error = differs(details::MINIMUM_RECEIVED);
    let expected = if intent.delivery.wallet() {
        let total = sum(take.fills.iter().map(|fill| fill.amount_out.get()), error)?;
        let least = fees::minimum_received(&intent.to, total).ok_or(error)?;
        Some((wallet_token(&intent.to).ok_or(error)?, least))
    } else {
        None
    };
    let served = take.minimum_received.as_ref().map(|least| (least.token, least.amount.get()));
    if served == expected { Ok(()) } else { Err(error) }
}

/// Every fill delivering into Lighter names one account index, and Lighter says its owner is the
/// recipient.
fn check_lighter_destination(
    fills: &[Fill],
    recipient: Address,
    owners: &LighterOwners,
) -> Result<(), VerificationError> {
    let indexes: HashSet<Option<u64>> =
        fills.iter().map(|fill| fill.delivery_to.as_deref().and_then(account_index)).collect();
    let mut indexes = indexes.into_iter();
    let (Some(Some(index)), None) = (indexes.next(), indexes.next()) else {
        return Err(differs(details::FILLS_DELIVERY_TO));
    };
    if owners.get(&index) == Some(&recipient) {
        Ok(())
    } else {
        Err(differs(details::DESTINATION_OWNER))
    }
}

/// What every fill of a take must say: the taker's, on the asked venues, paid by the payer,
/// delivered to the recipient as asked, under a swap id of that kind, for a positive amount.
fn check_fill(fill: &Fill, intent: &TakeIntent) -> Result<(), VerificationError> {
    let wallet = intent.delivery.wallet();
    let destination = if wallet { Destination::Wallet } else { Destination::Venue };
    differs_unless([
        (fill.role == FillRole::Taker, details::FILLS_ROLE),
        (fill.from_venue == intent.from, details::FILLS_FROM_VENUE),
        (fill.to_venue == intent.to, details::FILLS_TO_VENUE),
        (fill.payer == intent.payer, details::FILLS_PAYER),
        (fill.taker_recipient == intent.delivery.recipient(), details::FILLS_TAKER_RECIPIENT),
        (fill.destination == destination, details::FILLS_DESTINATION),
        (fees::swap_fee(&fill.swap_id).wallet == wallet, details::FILLS_SWAP_ID),
        (!fill.amount_in.get().is_zero(), details::FILLS_AMOUNT_IN),
    ])
}

/// Delivered inside a venue, a fill goes to the taker's own account there: its Aster address,
/// or a Lighter index (whose owner only Lighter confirms); through an escrow, to none.
fn check_delivery(fill: &Fill, recipient: Address) -> Result<(), VerificationError> {
    let to = fill.delivery_to.as_deref();
    let ok = match fill.to_venue {
        VenueId::Aster => to.and_then(eip712::address_text) == Some(recipient),
        VenueId::Lighter => to.and_then(account_index).is_some(),
        _ => to.is_none(),
    };
    if ok { Ok(()) } else { Err(differs(details::FILLS_DELIVERY_TO)) }
}

/// `pay_by` within the pay window, `t1` after it within the maker's timeout.
fn check_windows(fill: &Fill, now: i64, pay_window: i64) -> Result<(), VerificationError> {
    let (pay_by, t1) = (fill.pay_by.timestamp(), fill.t1.timestamp());
    if pay_by <= now || pay_by > now + pay_window {
        return Err(stale(details::FILLS_PAY_BY));
    }
    if t1 <= pay_by || t1 > now + signed(deployments::MAKER_TIMEOUT_SECONDS) + 30 {
        return Err(differs(details::FILLS_T1));
    }
    Ok(())
}

/// A take paid from an escrow venue: one `PayTake` in `environment`'s escrow on `from`, paying
/// every fill exactly, all within the caller's amounts, parts, fee, recipient and windows.
fn check_escrow_take(
    prepared: &TakePreparation,
    intent: &TakeIntent,
    environment: EscrowEnvironment,
    now: i64,
) -> Result<Verified, VerificationError> {
    let fills = &prepared.take.fills;
    if fills.is_empty() || fills.len() > usize::from(intent.max_parts.get()) {
        return Err(differs(details::FILLS));
    }
    if fills.iter().map(|fill| fill.id).collect::<HashSet<_>>().len() != fills.len() {
        return Err(differs(details::FILLS_ID));
    }
    if fills.iter().map(|fill| fill.swap_id).collect::<HashSet<_>>().len() != fills.len() {
        return Err(differs(details::FILLS_SWAP_ID));
    }
    let total_in = sum(fills.iter().map(|fill| fill.amount_in.get()), differs(details::AMOUNT_IN))?;
    let total_out =
        sum(fills.iter().map(|fill| fill.amount_out.get()), differs(details::AMOUNT_OUT))?;
    if total_in.is_zero() || total_in > intent.amount_in.get() {
        return Err(differs(details::AMOUNT_IN));
    }
    if total_out < intent.min_out.get() {
        return Err(differs(details::AMOUNT_OUT));
    }
    let [TakeSignRequest::Typed(item)] = &prepared.to_sign[..] else {
        return Err(differs(details::TO_SIGN));
    };
    let (parsed, domain) =
        escrow::check_escrow_typed::<PayTake>(&item.typed_data, &intent.from, environment)?;
    let pay = &parsed.message;
    if item.signer != intent.payer || pay.payer != intent.payer {
        return Err(differs(details::PAYER));
    }
    if !item.fill_id.is_some_and(|id| fills.iter().any(|fill| *fill.id.as_uuid() == id)) {
        return Err(differs(details::FILL_ID));
    }
    if pay.payments.len() != fills.len() {
        return Err(differs(details::PAYMENTS));
    }
    let receive = Receive::of(&intent.to, intent.delivery.wallet(), environment)?;
    let pay_window = if intent.at_once || intent.route {
        signed(deployments::ROUTE_PAY_WINDOW_SECONDS)
    } else {
        PAY_WINDOW_SECONDS
    };
    for (index, fill) in fills.iter().enumerate() {
        check_paid_fill(fill, pay, intent, &receive, now, pay_window)
            .map_err(|error| at(error, index))?;
    }
    if pay.deposit > total_in {
        return Err(differs(details::DEPOSIT));
    }
    let not_after = signing_bound(prepared, intent)?;
    Verified::typed(eip712::typed(pay, domain), parsed.digest, intent.payer, Some(not_after))
}

/// Where a payment's delivery must be received: the receiving chain, its token (the wallet token
/// for a wallet delivery) and escrow.
struct Receive {
    chain_id: U256,
    token: Address,
    escrow: Address,
}

impl Receive {
    fn of(
        to: &VenueId,
        wallet: bool,
        environment: EscrowEnvironment,
    ) -> Result<Self, VerificationError> {
        let chain = deployments::chain(to).ok_or(unsupported(details::VENUE))?;
        let token = if wallet { chain.wallet_token } else { Some(chain.token) };
        Ok(Self {
            chain_id: U256::from(chain.id),
            token: token.ok_or(unsupported(details::DESTINATION))?,
            escrow: deployments::contract(to, environment).ok_or(unsupported(details::VENUE))?,
        })
    }
}

/// One fill of an escrow take and its one payment in `pay`.
fn check_paid_fill(
    fill: &Fill,
    pay: &PayTake,
    intent: &TakeIntent,
    receive: &Receive,
    now: i64,
    pay_window: i64,
) -> Result<(), VerificationError> {
    check_fill(fill, intent)?;
    if fill.amount_out.get().is_zero() {
        return Err(differs(details::FILLS_AMOUNT_OUT));
    }
    check_delivery(fill, intent.delivery.recipient())?;
    check_windows(fill, now, pay_window)?;
    let (t1, t2) = (fill.t1.timestamp(), fill.t2.timestamp());
    if t2 <= t1 || t2 > now + signed(deployments::TAKER_TIMEOUT_SECONDS) + 30 {
        return Err(differs(details::FILLS_T2));
    }
    let mut matching = pay.payments.iter().filter(|payment| payment.swapId == fill.swap_id);
    let (Some(payment), None) = (matching.next(), matching.next()) else {
        return Err(differs(details::PAYMENTS_SWAP_ID));
    };
    let (amount_in, amount_out) = (fill.amount_in.get(), fill.amount_out.get());
    let dex = payment.dex == 0 || intent.from == VenueId::Hyperliquid && payment.dex == u32::MAX;
    differs_unless([
        (payment.payer == intent.payer, details::PAYMENTS_PAYER),
        (payment.recipient == fill.maker_recipient, details::PAYMENTS_RECIPIENT),
        (payment.hashlock == fill.hashlock, details::PAYMENTS_HASHLOCK),
        (payment.amount == amount_in, details::PAYMENTS_AMOUNT),
    ])?;
    // The fee rides on the payment, which the claim splits: the maker's price is the rest.
    fees::check_fee(
        &fill.swap_id,
        fill.taker_fee.get(),
        amount_in,
        amount_out,
        false,
        intent.max_fee_bps,
    )?;
    differs_unless([
        (i64::try_from(payment.refundAt).ok() == Some(t2), details::PAYMENTS_REFUND_AT),
        (
            payment.deadline == U256::try_from(fill.pay_by.timestamp()).unwrap_or(U256::MAX),
            details::PAYMENTS_DEADLINE,
        ),
        (dex, details::PAYMENTS_DEX),
        (payment.orderId == *fill.order_id.as_b256(), details::PAYMENTS_ORDER_ID),
        (payment.sequence == fill.sequence, details::PAYMENTS_SEQUENCE),
        (payment.amountOut == amount_out, details::PAYMENTS_AMOUNT_OUT),
        (
            payment.receiveRecipient == intent.delivery.recipient(),
            details::PAYMENTS_RECEIVE_RECIPIENT,
        ),
        (
            payment.receiveChainId == receive.chain_id
                && payment.receiveToken == receive.token
                && payment.receiveEscrow == receive.escrow,
            details::PAYMENTS_RECEIVE,
        ),
    ])
}

/// A take paid inside its venue: exactly one fill, paid by one request of the payer, within the
/// caller's amounts and fee (taken on delivery), delivered as asked, in the pay window.
fn check_venue_fill<'a>(
    prepared: &'a TakePreparation,
    intent: &TakeIntent,
    signer: Address,
    fill_id: &uuid::Uuid,
    now: i64,
) -> Result<&'a Fill, VerificationError> {
    let ([fill], [_]) = (&prepared.take.fills[..], &prepared.to_sign[..]) else {
        return Err(differs(details::TO_SIGN));
    };
    if signer != intent.payer {
        return Err(differs(details::TO_SIGN_SIGNER));
    }
    check_fill(fill, intent)?;
    if fill.id.as_uuid() != fill_id {
        return Err(differs(details::FILL_ID));
    }
    if fill.amount_in > intent.amount_in {
        return Err(differs(details::FILLS_AMOUNT_IN));
    }
    if fill.amount_out < intent.min_out {
        return Err(differs(details::FILLS_AMOUNT_OUT));
    }
    fees::check_fee(
        &fill.swap_id,
        fill.taker_fee.get(),
        fill.amount_in.get(),
        fill.amount_out.get(),
        true,
        intent.max_fee_bps,
    )?;
    check_delivery(fill, intent.delivery.recipient())?;
    check_windows(fill, now, PAY_WINDOW_SECONDS)?;
    Ok(fill)
}

/// A take paid from Lighter: the owner message of one internal transfer of exactly the fill's
/// amount from the payer's linked account (Lighter says the payer owns it) to the maker's (Lighter
/// says the maker's recipient owns it), named by the fill's memo, by `environment`'s LaMarge key,
/// with Lighter's fee at most 1 USDC.
fn check_lighter_take(
    prepared: &TakePreparation,
    intent: &TakeIntent,
    owners: &LighterOwners,
    environment: EscrowEnvironment,
    now: i64,
) -> Result<Verified, VerificationError> {
    let Some(TakeSignRequest::Lighter(LighterTransferItem {
        signer,
        fill_id,
        typed_data: terms,
        ..
    })) = prepared.to_sign.first()
    else {
        return Err(differs(details::TO_SIGN));
    };
    let fill = check_venue_fill(prepared, intent, *signer, fill_id.as_uuid(), now)?;
    let memo = lighter::fill_memo(fill.id);
    if Some(terms.from_account_index) != intent.payer_account
        || terms.amount != fill.amount_in
        || terms.memo != hex::encode(memo)
    {
        return Err(differs(details::LIGHTER_TRANSFER));
    }
    // Pinned to the environment: another environment's key is another registration.
    if terms.api_key_index != deployments::slots(environment).lighter_key_index {
        return Err(differs(details::LIGHTER_KEY));
    }
    if terms.usdc_fee.get() > deployments::LIGHTER_MAX_TAKER_FEE {
        return Err(differs(details::LIGHTER_FEE));
    }
    if owners.get(&terms.to_account_index) != Some(&fill.maker_recipient) {
        return Err(differs(details::LIGHTER_MAKER_ACCOUNT));
    }
    if owners.get(&terms.from_account_index) != Some(&intent.payer) {
        return Err(differs(details::LIGHTER_PAYER_ACCOUNT));
    }
    let units = |amount: Amount| {
        u64::try_from(amount.get()).map_err(|_| differs(details::LIGHTER_TRANSFER))
    };
    let transfer = lighter::Transfer {
        nonce: terms.nonce,
        from: terms.from_account_index,
        from_route: lighter::COLLATERAL_ROUTE,
        api_key: terms.api_key_index,
        to: terms.to_account_index,
        to_route: lighter::COLLATERAL_ROUTE,
        asset: lighter::USDC_ASSET,
        amount: units(terms.amount)?,
        fee: units(terms.usdc_fee)?,
        memo,
    };
    let not_after = signing_bound(prepared, intent)?;
    let message = lighter::transfer_message(&transfer, deployments::LIGHTER.id);
    Ok(Verified::text(message, intent.payer, Some(not_after)))
}

/// A take paid from Aster: the payer's transfer request (`Message` at chain 1666) of the fill's
/// amount, as Aster carries it in six decimals rounded up, to the maker's recipient under the
/// fill's id, its nonce far enough ahead for LaMarge to relay it and within Aster's window when
/// relayed by `pay_by`, signable only while that nonce stays ahead.
fn check_aster_take(
    prepared: &TakePreparation,
    intent: &TakeIntent,
    now: i64,
) -> Result<Verified, VerificationError> {
    let Some(TakeSignRequest::Aster(item)) = prepared.to_sign.first() else {
        return Err(differs(details::TO_SIGN));
    };
    let fill = check_venue_fill(prepared, intent, item.signer, item.fill_id.as_uuid(), now)?;
    let (msg, transfer, digest) = aster_transfer(&item.typed_data)?;
    let owed = fill.amount_in.get();
    let amount = transfer.amount >= owed && transfer.amount - owed < deployments::ASTER.step();
    if !amount
        || transfer.to != fill.maker_recipient
        || transfer.user != intent.payer
        || transfer.client_id != aster::client_id(fill.id)
    {
        return Err(differs(details::ASTER_TRANSFER));
    }
    let window = aster::transfer_nonce_window(now, fill.pay_by.timestamp());
    if !window.contains(&i128::from(transfer.nonce)) {
        return Err(stale(details::ASTER_NONCE));
    }
    // Whether or not LaMarge may issue the request again, this one is signed only while its
    // nonce stays ahead.
    let ahead = nonce_seconds(transfer.nonce) - aster::NONCE_AHEAD_SECONDS;
    let not_after = signing_bound(prepared, intent)?.min(ahead - 1);
    let domain = aster::domain(aster::TRANSFER_CHAIN_ID);
    let message = Message { msg };
    Verified::typed(eip712::typed(&message, domain), digest, intent.payer, Some(not_after))
}

/// An Aster transfer request between accounts (`Message` at chain 1666): its `msg`, the transfer
/// it reads as, and its digest.
pub(crate) fn aster_transfer(
    raw: &Value,
) -> Result<(String, aster::Transfer, B256), VerificationError> {
    let parsed = eip712::parse_in::<Message>(raw, &aster::domain(aster::TRANSFER_CHAIN_ID))?;
    let msg = parsed.message.msg;
    let transfer = aster::parse_transfer(&msg).ok_or(differs(details::ASTER_TRANSFER))?;
    Ok((msg, transfer, parsed.digest))
}

#[cfg(test)]
mod tests;