lamarge 0.7.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
//! Direct operations its owner sends itself, without quotes or makers: a deposit from the owner's
//! wallet into an escrow venue's account (Polygon's native USDC converted into pUSD by the escrow
//! on its way into Polymarket), or a GMX withdrawal by the owner's own `transferOut`.
//!
//! Journalled under the request's `client_operation_id`: created or found again by it, checked
//! against the request and the pins, its calldata rebuilt from those terms alone, fenced before
//! the host is asked, and never asked again while its outcome is unknown. A deposit the sender
//! did not send is asked again under its same nonce; a GMX withdrawal, which has no nonce, only
//! by its first fenced prompt.

use alloy_primitives::{Address, B256, U256};
use serde::{Deserialize, Serialize};
use tracing::Instrument as _;
use uuid::Uuid;

use super::{
    conversion::{APPROVE, DEADLINE_WINDOW_SECONDS, check_conversion_capability},
    records,
};
use crate::{
    Error, Result, SendError, SendStatus, Session, Transaction, TransactionSender,
    api::DirectRequest,
    deployments,
    model::{BridgeFunding, DirectKind, DirectOperation, DirectState, EscrowChain},
    protocol::{
        checks::{
            deployment,
            details::{self, changed, differs, stale, unsupported},
        },
        gmx,
    },
    types::{Amount, VenueId},
};

mod inspect;

pub use inspect::{DirectInspection, DirectStep, check_direct_amounts, inspect_direct_transaction};

/// The escrow's `directDeposit(address recipient, address token, uint256 amount, uint256 minOut,
/// uint256 nonce, uint256 deadline)`.
const DEPOSIT: [u8; 4] = [0xfc, 0x95, 0x98, 0xe8];
/// How far a funds read may be from the client's clock.
const FUNDS_AHEAD_MS: i64 = 15_000;
const FUNDS_AGE_MS: i64 = 120_000;

/// Where [`Session::direct_transfer`] stopped.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DirectOutcome {
    /// The operation as last read: confirmed, failed and expired are final; prepared or pending,
    /// run the same request again later.
    Operation(Box<DirectOperation>),
    /// Nothing failed: run the same request again later.
    Waiting(DirectWait),
}

/// What a direct operation waits for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DirectWait {
    /// The escrow's allowance does not show the `approve` asked yet, sent or of unknown outcome.
    Approval,
    /// The sender sent nothing (the owner declined, a signature timed out, gas was missing). A
    /// deposit is asked again by the next run, under its same nonce; a GMX withdrawal, which has
    /// no nonce, is never asked again: it is released once it expires.
    NotSent,
    /// The sender's outcome is unknown: nothing is asked again until
    /// [`TransactionSender::status`] says it was not sent.
    Unknown,
}

/// The operation first created for the request.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Identity {
    id: Uuid,
    nonce: Amount,
    deadline: Amount,
    escrow: Address,
}

/// A transaction asked of the sender: journalled before the fence, `fenced` once this store holds
/// it, with its hash once returned, `unsent` once the sender said it sent nothing.
#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)]
struct Asked {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    hash: Option<B256>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    unsent: bool,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    fenced: bool,
}

/// Final: nothing more moves.
fn is_final(state: &DirectState) -> bool {
    matches!(state, DirectState::Confirmed | DirectState::Failed | DirectState::Expired)
}

impl Session {
    /// Runs the direct operation `request` ([`DirectRequest::deposit`],
    /// [`DirectRequest::gmx_withdrawal`]) from the session's own address, its transactions sent
    /// through `sender`: records it (idempotent by `client_operation_id`), checks it against the
    /// request and the pinned deployment, reads the venue's direct capability (and Polygon's
    /// conversion for native USDC) and the owner's funds fresh, then asks an `approve` when the
    /// escrow's allowance is short, and the deposit or `transferOut` itself, rebuilt from the
    /// terms alone.
    ///
    /// Persist the request and run it again to resume: each transaction is journalled before it
    /// is asked, under a stable [`Transaction::id`], and the operation is fenced on LaMarge before
    /// its owner is asked, so a lost answer never asks again, on this device or another.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidRequest`] before any request when the request's owner is not the
    ///   session's address, or the journal holds another request under its id.
    /// - `Verification(..)` when the operation is answered with other terms than the request's,
    ///   another identity than the one first journalled, or off the pins; when the venue's
    ///   direct capability or Polygon's conversion is missing or differs, the deadline is out of
    ///   its window, or the funds read are stale or short.
    pub async fn direct_transfer(
        &self,
        request: &DirectRequest,
        sender: &dyn TransactionSender,
    ) -> Result<DirectOutcome> {
        let span = tracing::info_span!(
            "lamarge.direct",
            client_operation_id = %request.client_operation_id,
        );
        run(self, request, Some(sender)).instrument(span).await
    }
}

/// Runs `request`: see the module. Without a sender, only follows what was already sent.
#[expect(clippy::too_many_lines, reason = "the TypeScript directTransfer(), step by step")]
pub(super) async fn run(
    session: &Session,
    request: &DirectRequest,
    sender: Option<&dyn TransactionSender>,
) -> Result<DirectOutcome> {
    request.validate()?;
    if request.owner != session.address() {
        return Err(Error::InvalidRequest(
            "a direct operation of the session's own address".into(),
        ));
    }
    let journal = session.journal();
    let key = |record: &str| {
        session.record_key(&format!("direct:{}{record}", request.client_operation_id))
    };
    let _turn = journal.lock(&key("")).await;
    match records::load::<DirectRequest>(journal, &key(":request")).await? {
        Some(saved) if saved != *request => {
            let message = format!("direct {} names another operation", request.client_operation_id);
            return Err(Error::InvalidRequest(message.into()));
        }
        Some(_) => {}
        None => records::save(journal, &key(":request"), request, false).await?,
    }
    let directs = session.directs();
    let created = directs.create(request).await?;
    check(session, &created, request)?;
    let identity = Identity {
        id: created.id,
        nonce: created.nonce,
        deadline: created.deadline,
        escrow: created.escrow,
    };
    match records::load::<Identity>(journal, &key(":identity")).await? {
        Some(saved) if saved != identity => return Err(changed(details::DIRECT).into()),
        Some(_) => {}
        None => records::save(journal, &key(":identity"), &identity, false).await?,
    }
    let read = || async {
        let operation = directs.get(identity.id).await?;
        check(session, &operation, request)?;
        let same = (operation.id, operation.nonce, operation.deadline, operation.escrow)
            == (identity.id, identity.nonce, identity.deadline, identity.escrow);
        if same { Ok(operation) } else { Err(Error::from(changed(details::DIRECT))) }
    };

    let sent_key = key(":sent");
    let step = request.kind.as_str();
    let mut sent = records::load::<Asked>(journal, &sent_key).await?;
    if let Some(asked) = &mut sent {
        // Fenced by this store with no answer recorded: only the sender knows whether it went.
        if asked.fenced && asked.hash.is_none() && !asked.unsent {
            match status(sender, &transaction_id(identity.id, step)).await {
                SendStatus::Sent(hash) => asked.hash = Some(hash),
                SendStatus::NotSent => asked.unsent = true,
                _ => {}
            }
            records::save(journal, &sent_key, asked, true).await?;
        }
        if let Some(hash) = asked.hash
            && !created.attempts.iter().any(|seen| seen.parse() == Ok(hash))
        {
            directs.report_transaction(identity.id, hash).await?;
        }
    }
    let operation = read().await?;
    if is_final(&operation.state) {
        return Ok(DirectOutcome::Operation(Box::new(operation)));
    }
    // A deposit the sender did not send may be asked again: its nonce lands it once at most. A
    // GMX withdrawal has none; only its first fenced prompt may send it.
    let retry = request.kind == DirectKind::Deposit
        && sent.is_some_and(|asked| asked.unsent && asked.hash.is_none());
    if !retry && (operation.state != DirectState::Prepared || sent.is_some()) {
        return Ok(DirectOutcome::Operation(Box::new(operation)));
    }

    if !in_window(operation.deadline.get(), session.transport().now().timestamp()) {
        return Err(stale(details::DEADLINE).into());
    }
    let chain = enabled_chain(session, &request.venue).await?;
    if chain.escrow != operation.escrow {
        return Err(differs(details::ESCROW).into());
    }
    let capable = match request.kind {
        DirectKind::Deposit => chain.direct_deposit,
        _ => chain.direct_withdrawal,
    };
    if capable != Some(true) {
        return Err(unsupported(details::VENUE).into());
    }
    if request.token != chain.token {
        check_conversion_capability(&chain)?;
    }
    let sender = sender.ok_or(Error::TransactionSenderRequired)?;
    let read_funds = || async {
        let funds = directs.funding(identity.id).await?;
        check_funds(session, &funds, request, operation.escrow)?;
        Ok::<_, Error>(funds)
    };
    let funds = read_funds().await?;
    if request.kind == DirectKind::Deposit && funds.allowance < request.amount {
        let approval =
            Approval { id: transaction_id(identity.id, "approve"), key: key(":approval") };
        if let Some(wait) = approve(session, sender, &operation, &approval).await? {
            return Ok(DirectOutcome::Waiting(wait));
        }
        if read_funds().await?.allowance < request.amount {
            return Ok(DirectOutcome::Waiting(DirectWait::Approval));
        }
    }

    // Journalled, then fenced, before the prompt: a lost fence answer never prompts again. A
    // deposit asked again was fenced by its first prompt.
    let fenced = Asked { fenced: true, ..Asked::default() };
    if !retry {
        records::save(journal, &sent_key, &Asked::default(), false).await?;
        directs.fence(identity.id).await?;
    }
    records::save(journal, &sent_key, &fenced, true).await?;
    let transaction = Transaction {
        id: transaction_id(identity.id, step),
        chain_id: operation.chain_id,
        to: target(&operation),
        data: calldata(&operation)?,
        value: U256::ZERO,
    };
    match sender.send(transaction).await {
        Ok(hash) => {
            records::save(journal, &sent_key, &Asked { hash: Some(hash), ..fenced }, true).await?;
            directs.report_transaction(identity.id, hash).await?;
        }
        Err(SendError::NotSent(error)) => {
            tracing::info!(%error, step, "direct transaction not sent");
            records::save(journal, &sent_key, &Asked { unsent: true, ..fenced }, true).await?;
            return Ok(DirectOutcome::Waiting(DirectWait::NotSent));
        }
        Err(error) => {
            tracing::warn!(%error, step, "direct transaction outcome unknown");
            return Ok(DirectOutcome::Waiting(DirectWait::Unknown));
        }
    }
    Ok(DirectOutcome::Operation(Box::new(read().await?)))
}

/// The operation is the request's, on the pinned deployment of the session's environment, sent
/// by the session's address; a confirmed one received at least its floor.
fn check(session: &Session, operation: &DirectOperation, request: &DirectRequest) -> Result<()> {
    let chain = deployments::chain(&request.venue).ok_or(unsupported(details::VENUE))?;
    let pinned = deployments::escrow(chain.id, session.escrow_environment());
    let owner = session.address();
    let ok = operation.chain_id == chain.id
        && pinned == Some(operation.escrow)
        && operation.client_operation_id == request.client_operation_id
        && operation.venue == request.venue
        && operation.kind == request.kind
        && operation.owner == owner
        && request.owner == owner
        && operation.recipient == request.recipient
        && operation.token == request.token
        && operation.amount == request.amount
        && operation.min_out == request.min_out;
    if !ok {
        return Err(changed(details::DIRECT).into());
    }
    let deposit = request.kind == DirectKind::Deposit;
    check_direct_amounts(&request.venue, request.token, request.amount, request.min_out, deposit)?;
    calldata(operation)?;
    if operation.state == DirectState::Confirmed
        && (operation.tx_hash.is_none()
            || operation.received.is_none_or(|received| received < request.min_out))
    {
        return Err(differs(details::DIRECT).into());
    }
    Ok(())
}

/// `venue`'s chain as the API lists it enabled, checked against the pins and the session's
/// environment.
async fn enabled_chain(session: &Session, venue: &VenueId) -> Result<EscrowChain> {
    let venues = session.client().market().venues().await?;
    let chain = venues
        .into_iter()
        .find(|row| row.id == *venue && row.enabled)
        .and_then(|row| row.chain)
        .ok_or(unsupported(details::VENUE))?;
    if deployment::check_registry(venue, &chain)? != Some(session.escrow_environment()) {
        return Err(differs(details::ESCROW).into());
    }
    Ok(chain)
}

/// A fresh read of the owner's funds in the request's token toward the escrow, covering it.
fn check_funds(
    session: &Session,
    funds: &BridgeFunding,
    request: &DirectRequest,
    escrow: Address,
) -> Result<()> {
    let age = (session.transport().now() - funds.observed_at).num_milliseconds();
    let fresh = (-FUNDS_AHEAD_MS..FUNDS_AGE_MS).contains(&age);
    if (funds.owner, funds.token, funds.spender) != (session.address(), request.token, escrow)
        || !fresh
        || funds.balance < request.amount
    {
        return Err(changed(details::DIRECT_FUNDING).into());
    }
    Ok(())
}

/// The escrow's allowance asked of the sender: its transaction id and journal key.
struct Approval {
    id: String,
    key: String,
}

/// The escrow's allowance, asked once: an `approve` sent or of unknown outcome is waited for
/// until the allowance shows it; one not sent is asked again. `None` once sent by this run.
async fn approve(
    session: &Session,
    sender: &dyn TransactionSender,
    operation: &DirectOperation,
    approval: &Approval,
) -> Result<Option<DirectWait>> {
    let journal = session.journal();
    if let Some(asked) = records::load::<Asked>(journal, &approval.key).await? {
        if asked.hash.is_some() {
            return Ok(Some(DirectWait::Approval));
        }
        match status(Some(sender), &approval.id).await {
            SendStatus::Sent(hash) => {
                let asked = Asked { hash: Some(hash), ..Asked::default() };
                records::save(journal, &approval.key, &asked, true).await?;
                return Ok(Some(DirectWait::Approval));
            }
            SendStatus::NotSent => {}
            _ => return Ok(Some(DirectWait::Approval)),
        }
    }
    records::save(journal, &approval.key, &Asked::default(), false).await?;
    let transaction = Transaction {
        id: approval.id.clone(),
        chain_id: operation.chain_id,
        to: operation.token,
        data: approve_data(operation.escrow, operation.amount),
        value: U256::ZERO,
    };
    match sender.send(transaction).await {
        Ok(hash) => {
            let asked = Asked { hash: Some(hash), ..Asked::default() };
            records::save(journal, &approval.key, &asked, true).await?;
            Ok(None)
        }
        Err(SendError::NotSent(error)) => {
            tracing::info!(%error, "direct approval not sent");
            records::delete(journal, &approval.key, true).await?;
            Ok(Some(DirectWait::NotSent))
        }
        Err(error) => {
            tracing::warn!(%error, "direct approval outcome unknown");
            Ok(Some(DirectWait::Approval))
        }
    }
}

/// `approve(spender, amount)`.
fn approve_data(spender: Address, amount: Amount) -> Vec<u8> {
    let mut data = APPROVE.to_vec();
    data.extend_from_slice(&address_word(spender));
    data.extend_from_slice(&amount.get().to_be_bytes::<32>());
    data
}

fn address_word(address: Address) -> [u8; 32] {
    let mut word = [0; 32];
    word[12..].copy_from_slice(address.as_slice());
    word
}

/// What the operation's owner calls: the escrow for a deposit, GMX's router for a withdrawal.
fn target(operation: &DirectOperation) -> Address {
    match operation.kind {
        DirectKind::Withdrawal => gmx::TRANSFER_ROUTER,
        _ => operation.escrow,
    }
}

/// The owner-sent call, rebuilt from the operation's terms: no calldata the API supplies is
/// sent. A withdrawal is only GMX's, to its owner's own address.
fn calldata(operation: &DirectOperation) -> Result<Vec<u8>> {
    match operation.kind {
        DirectKind::Withdrawal
            if operation.venue == VenueId::Gmx && operation.owner == operation.recipient =>
        {
            Ok(gmx::transfer_out(operation.amount.get()).to_vec())
        }
        DirectKind::Deposit => {
            let mut data = DEPOSIT.to_vec();
            data.extend_from_slice(&address_word(operation.recipient));
            data.extend_from_slice(&address_word(operation.token));
            for value in [operation.amount, operation.min_out, operation.nonce, operation.deadline]
            {
                data.extend_from_slice(&value.get().to_be_bytes::<32>());
            }
            Ok(data)
        }
        _ => Err(changed(details::DIRECT).into()),
    }
}

/// A direct or conversion deadline, in seconds: after `now`, at most the server's 30 minutes and
/// 15 seconds of skew later.
fn in_window(deadline: U256, now: i64) -> bool {
    let Ok(now) = u64::try_from(now) else { return false };
    let latest = now.saturating_add(DEADLINE_WINDOW_SECONDS.unsigned_abs());
    deadline > U256::from(now) && deadline <= U256::from(latest)
}

/// The stable id of the operation's `step` transaction: `withdrawal`, `deposit` or `approve`.
fn transaction_id(id: Uuid, step: &str) -> String {
    format!("lamarge.direct.{id}.{step}")
}

/// What the sender knows of `id`; without a sender or a lookup, nothing.
async fn status(sender: Option<&dyn TransactionSender>, id: &str) -> SendStatus {
    match sender {
        Some(sender) => sender.status(id).await.unwrap_or(SendStatus::Unknown),
        None => SendStatus::Unknown,
    }
}

#[cfg(test)]
mod tests;