lamarge 0.8.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
//! The withdrawal flow: withdrawals out of Hyperliquid, Polymarket and Aster, sends to another
//! account on Hyperliquid, Polymarket and Aster.

use alloy_primitives::Address;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tracing::Instrument as _;

use super::{linked, records};
use crate::{
    Error, Result, Session,
    error::ErrorCode,
    model::{Dex, Withdrawal, WithdrawalState},
    protocol::{
        aster,
        checks::{
            details::{self, changed, unsupported},
            withdrawal::{
                check_aster_margin_withdrawal, check_margin_withdrawal, check_send, signed_at,
            },
        },
        deliveries::aster_withdrawal_envelope,
        signing::Verified,
    },
    transport::{Call, ops},
    types::{Amount, ClientId, EscrowEnvironment, MoveId, SignatureBytes, VenueId},
};

/// Where a withdrawal goes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum WithdrawTo {
    /// Out of the venue to the session address (Hyperliquid: on HyperEVM; Polymarket: on
    /// Polygon; Aster: on BSC, or the chain [`WithdrawalRequest::chain`] names).
    Signer,
    /// Out of Polymarket to this wallet (Deposit Wallet or Safe), which must be the account's
    /// linked venue wallet: the SDK never takes the destination from the API.
    VenueWallet(Address),
    /// A send to another account on the same venue; on Polymarket, its Perps owner (signer)
    /// address.
    Account(Address),
}

/// Exactly `amount` out of the session's account on `venue`: a withdrawal (Hyperliquid,
/// Polymarket, Aster) or a send to another account (Hyperliquid, Polymarket, Aster).
///
/// Persist the whole request (it is serializable) before the first call, then run that same
/// request again to resume.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WithdrawalRequest {
    id: ClientId,
    venue: VenueId,
    amount: Amount,
    to: WithdrawTo,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    move_id: Option<MoveId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    dex: Option<Dex>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    chain_id: Option<u64>,
}

impl WithdrawalRequest {
    /// A withdrawal named `id` of `amount` (in `venue`'s base units) to `to`. The same id
    /// finds this withdrawal again, never a second one.
    pub fn new(id: ClientId, venue: VenueId, amount: Amount, to: WithdrawTo) -> Self {
        Self { id, venue, amount, to, move_id: None, dex: None, chain_id: None }
    }

    /// Sends an Aster withdrawal to the signer on `chain_id` instead of BSC: 42161 Arbitrum or
    /// 1 Ethereum (56 is BSC). Aster limits each chain on its own; `Withdrawals::chains` lists
    /// each one's withdrawable amount and fee. Refused on any other withdrawal.
    #[must_use]
    pub fn chain(mut self, chain_id: u64) -> Self {
        self.chain_id = Some(chain_id);
        self
    }

    /// Attaches a withdrawal to the signer to move `id`, from the move's origin account by its
    /// payer: what it moves feeds the move's bridge. An exact retry keeps the first move.
    #[must_use]
    pub fn move_id(mut self, id: MoveId) -> Self {
        self.move_id = Some(id);
        self
    }

    /// Pays a Hyperliquid withdrawal or send from `dex` instead of the perps: [`Dex::Xyz`], a
    /// standard account's trade.xyz balance. Refused on any other venue.
    #[must_use]
    pub fn dex(mut self, dex: Dex) -> Self {
        self.dex = Some(dex);
        self
    }
}

/// What a stored withdrawal was for: a stored record answers only the same request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Context {
    environment: EscrowEnvironment,
    venue: VenueId,
    amount: Amount,
    to: WithdrawTo,
    signer: Address,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    move_id: Option<MoveId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    dex: Option<Dex>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    chain_id: Option<u64>,
}

/// A withdrawal's signature, saved before it is first submitted (`{ns}withdrawal:{id}`), then its
/// outcome.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct WithdrawalRecord {
    context: Context,
    /// As prepared, submitted exactly so.
    typed_data: Value,
    signature: SignatureBytes,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    result: Option<Withdrawal>,
    /// The venue refused it: the id is spent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    refused: Option<ErrorCode>,
}

#[derive(Serialize)]
struct PrepareBody<'a> {
    venue: &'a VenueId,
    amount: Amount,
    to: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    recipient: Option<Address>,
    #[serde(skip_serializing_if = "Option::is_none")]
    dex: Option<&'a Dex>,
    #[serde(skip_serializing_if = "Option::is_none")]
    chain_id: Option<u64>,
}

#[derive(Deserialize)]
struct Prepared {
    typed_data: Value,
}

#[derive(Serialize)]
struct SubmitBody<'a> {
    venue: &'a VenueId,
    typed_data: &'a Value,
    signature: SignatureBytes,
    #[serde(skip_serializing_if = "Option::is_none")]
    envelope: Option<Envelope>,
    #[serde(skip_serializing_if = "Option::is_none")]
    move_id: Option<MoveId>,
}

/// The account's own envelope around an Aster withdrawal.
#[derive(Serialize)]
struct Envelope {
    signer: Address,
    /// Microseconds.
    nonce: String,
    signature: SignatureBytes,
}

impl Session {
    /// Withdraws or sends exactly `amount` from the session's account on the request's venue:
    /// prepared, checked (to the destination asked for, without fee, its time within a minute),
    /// signed, saved to the journal, then relayed.
    ///
    /// The journal keeps the signature and the outcome under the request's id: running the same
    /// request again returns a final outcome (`relayed`) without any request, or submits the
    /// same signature again (checked again at its own signing time), never a second withdrawal.
    ///
    /// Supported: withdrawals out of Hyperliquid and Aster ([`WithdrawTo::Signer`]) and
    /// Polymarket ([`WithdrawTo::Signer`], [`WithdrawTo::VenueWallet`], the linked wallet), sends
    /// on Hyperliquid, Polymarket and Aster ([`WithdrawTo::Account`], another address than the
    /// session's). An Aster withdrawal adds Aster's fee to `amount` (2 USDT at most), goes to BSC
    /// or the chain [`WithdrawalRequest::chain`] names, and is relayed in an envelope the session
    /// signs too, fresh at each submission.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidRequest`] before any request for a zero amount, a send to the session's
    ///   own address or a destination the venue does not offer, or the same id with other terms;
    ///   `Verification(Unsupported)` for anything else this release does not support.
    /// - `Verification(..)` when the prepared withdrawal fails a check: nothing is signed.
    /// - `VENUE_REJECTED` or `WITHDRAWAL_EXPIRED` when the venue refused it, then
    ///   [`Error::WithdrawalRefused`] on every later run: use a new id.
    ///
    /// # Cancellation
    ///
    /// Dropping the future is safe: a saved signature is submitted by running the same request
    /// again, and an unsaved one is discarded.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn run(session: &lamarge::Session) -> Result<(), Box<dyn std::error::Error>> {
    /// use lamarge::flows::{WithdrawTo, WithdrawalRequest};
    /// use lamarge::types::{Amount, ClientId, VenueId};
    ///
    /// let amount = Amount::parse_venue(&VenueId::Hyperliquid, "25")?;
    /// let id = ClientId::new("out-1")?;
    /// let request = WithdrawalRequest::new(id, VenueId::Hyperliquid, amount, WithdrawTo::Signer);
    /// let withdrawal = session.withdraw(&request).await?;
    /// # Ok(()) }
    /// ```
    pub async fn withdraw(&self, request: &WithdrawalRequest) -> Result<Withdrawal> {
        let span =
            tracing::info_span!("lamarge.withdraw", id = %request.id, venue = %request.venue);
        run(self, request).instrument(span).await
    }
}

/// The API's name of `to`, and the send's recipient.
fn target(to: WithdrawTo) -> (&'static str, Option<Address>) {
    match to {
        WithdrawTo::Signer => ("signer", None),
        WithdrawTo::VenueWallet(_) => ("wallet", None),
        WithdrawTo::Account(recipient) => ("account", Some(recipient)),
    }
}

/// Refuses, before any request, what this release does not support or the API would refuse.
fn validate(session: &Session, request: &WithdrawalRequest) -> Result<()> {
    match (&request.venue, request.to) {
        (
            VenueId::Hyperliquid | VenueId::Polymarket | VenueId::Aster,
            WithdrawTo::Signer | WithdrawTo::Account(_),
        )
        | (VenueId::Polymarket, WithdrawTo::VenueWallet(_)) => {}
        (VenueId::Hyperliquid, WithdrawTo::VenueWallet(_)) => {
            return Err(Error::InvalidRequest("Hyperliquid withdraws to the signer only".into()));
        }
        _ => return Err(unsupported(details::VENUE).into()),
    }
    if request.to == WithdrawTo::Account(session.address()) {
        return Err(Error::InvalidRequest("a send goes to another account".into()));
    }
    if request.move_id.is_some() && request.to != WithdrawTo::Signer {
        return Err(Error::InvalidRequest("a move's withdrawal goes to the signer".into()));
    }
    match (&request.dex, &request.venue) {
        (None, _) | (Some(Dex::Xyz), VenueId::Hyperliquid) => {}
        (Some(Dex::Xyz), _) => {
            return Err(Error::InvalidRequest(
                "only a Hyperliquid withdrawal or send pays from trade.xyz".into(),
            ));
        }
        (Some(Dex::Unknown(_)), _) => return Err(unsupported(details::SOURCE_DEX).into()),
    }
    if request.amount == Amount::ZERO {
        return Err(Error::InvalidRequest("amount must be positive".into()));
    }
    if let Some(chain_id) = request.chain_id {
        if !aster_withdrawal(request) {
            return Err(Error::InvalidRequest(
                "a chain goes only with an Aster withdrawal to the signer".into(),
            ));
        }
        if aster::withdraw_chain_name(chain_id).is_none() {
            return Err(Error::InvalidRequest(
                format!("Aster does not withdraw to chain {chain_id}").into(),
            ));
        }
    }
    Ok(())
}

/// An Aster withdrawal, relayed in the account's own envelope.
fn aster_withdrawal(request: &WithdrawalRequest) -> bool {
    request.venue == VenueId::Aster && request.to == WithdrawTo::Signer
}

async fn run(session: &Session, request: &WithdrawalRequest) -> Result<Withdrawal> {
    validate(session, request)?;
    let id = &request.id;
    let signer = session.address();
    let (to, recipient) = target(request.to);
    let journal = session.journal();
    let key = session.record_key(&format!("withdrawal:{id}"));
    let _turn = journal.lock(&key).await;
    let context = Context {
        environment: session.escrow_environment(),
        venue: request.venue.clone(),
        amount: request.amount,
        to: request.to,
        signer,
        move_id: request.move_id,
        dex: request.dex.clone(),
        chain_id: request.chain_id,
    };
    let stored = records::load::<WithdrawalRecord>(journal, &key).await?;
    if let Some(record) = &stored {
        if record.context != context {
            return Err(Error::InvalidRequest(
                format!("withdrawal {id} names another withdrawal").into(),
            ));
        }
        if let Some(code) = &record.refused {
            return Err(Error::WithdrawalRefused { id: id.clone(), code: code.clone() });
        }
        if let Some(result) = record.result.as_ref().filter(|result| is_final(&result.state)) {
            return Ok(result.clone());
        }
    }
    let destination = destination(session, request).await?;
    let record = if let Some(record) = stored {
        check(request, signer, destination, &record.typed_data, signed_at(&record.typed_data)?)?;
        tracing::info!("submitting the saved signature");
        record
    } else {
        let body = PrepareBody {
            venue: &request.venue,
            amount: request.amount,
            to,
            recipient,
            dex: request.dex.as_ref(),
            chain_id: request.chain_id,
        };
        let call = Call::new(&ops::PREPARE_WITHDRAWAL).json(&body)?;
        let prepared: Prepared = session.transport().send(call, session.auth()).await?;
        let now = session.transport().now();
        let verified = check(request, signer, destination, &prepared.typed_data, now)?;
        let signature = session.sign(&verified).await?;
        let record = WithdrawalRecord {
            context,
            typed_data: prepared.typed_data,
            signature,
            result: None,
            refused: None,
        };
        records::save(journal, &key, &record, false).await?;
        tracing::info!("withdrawal signed");
        record
    };
    submit(session, request, &key, record).await
}

/// The withdrawal's destination, as the request names it, after a fresh read of the account
/// linked on the venue: the session address's, and its venue wallet the one the request names.
async fn destination(session: &Session, request: &WithdrawalRequest) -> Result<Address> {
    let balances = session.account().balances().await?;
    let row = linked(&balances, &request.venue, session.address())?;
    Ok(match request.to {
        WithdrawTo::Signer => session.address(),
        WithdrawTo::VenueWallet(wallet) => {
            let linked = row.venue_wallet.as_deref().and_then(|linked| linked.parse().ok());
            if linked != Some(wallet) {
                return Err(changed(details::LINKED_ACCOUNT).into());
            }
            wallet
        }
        WithdrawTo::Account(recipient) => recipient,
    })
}

/// Checks `typed` as `request`'s withdrawal or send to `destination`, signed at `at`.
fn check(
    request: &WithdrawalRequest,
    signer: Address,
    destination: Address,
    typed: &Value,
    at: DateTime<Utc>,
) -> Result<Verified> {
    let (venue, amount, dex) = (&request.venue, request.amount, request.dex.as_ref());
    let checked = match request.to {
        WithdrawTo::Account(_) => check_send(typed, venue, signer, destination, amount, at, dex),
        WithdrawTo::Signer if aster_withdrawal(request) => check_aster_margin_withdrawal(
            typed,
            signer,
            amount,
            at,
            request.chain_id.unwrap_or(aster::CHAIN_ID),
        ),
        WithdrawTo::Signer | WithdrawTo::VenueWallet(_) => {
            check_margin_withdrawal(typed, venue, signer, destination, amount, at, dex)
        }
    };
    Ok(checked?)
}

/// Relays the saved signature and records the outcome: the result, or the venue's refusal.
async fn submit(
    session: &Session,
    request: &WithdrawalRequest,
    key: &str,
    mut record: WithdrawalRecord,
) -> Result<Withdrawal> {
    let journal = session.journal();
    // A fresh envelope each time: the server ignores it on an exact retry it already recorded.
    let envelope = if aster_withdrawal(request) {
        let nonce = u64::try_from(session.transport().now().timestamp_micros())
            .map_err(|_| Error::InvalidRequest("the clock is before 1970".into()))?;
        let verified = aster_withdrawal_envelope(
            &record.typed_data,
            &record.signature,
            nonce,
            session.address(),
        )?;
        let signature = session.sign(&verified).await?;
        Some(Envelope { signer: session.address(), nonce: nonce.to_string(), signature })
    } else {
        None
    };
    let body = SubmitBody {
        venue: &request.venue,
        typed_data: &record.typed_data,
        signature: record.signature,
        envelope,
        move_id: request.move_id,
    };
    let call = Call::new(&ops::SUBMIT_WITHDRAWAL).json(&body)?;
    match session.transport().send::<Withdrawal>(call, session.auth()).await {
        Ok(result) => {
            record.result = Some(result.clone());
            records::save(journal, key, &record, true).await?;
            tracing::info!(state = %result.state, "withdrawal submitted");
            Ok(result)
        }
        Err(error) if refusal(&error) => {
            record.refused = error.code().cloned();
            records::save(journal, key, &record, true).await?;
            Err(error)
        }
        Err(error) => Err(error),
    }
}

/// An outcome running the request again cannot change.
fn is_final(state: &WithdrawalState) -> bool {
    matches!(state, WithdrawalState::Relayed | WithdrawalState::Refused)
}

/// The venue refused the signed withdrawal: it can never go.
fn refusal(error: &Error) -> bool {
    matches!(error.code(), Some(ErrorCode::VenueRejected | ErrorCode::WithdrawalExpired))
}

#[cfg(test)]
mod tests;