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
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
//! 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.

use std::{fmt, sync::Arc, time::Duration};

use alloy_primitives::{Address, U256};
use alloy_signer::Signer;
use chrono::{DateTime, TimeDelta, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::{
    Error, HttpExchange, HttpRequest,
    delivery::{
        Backoff, Deliveries, DeliveryCore, DeliveryError, DeliveryOutcome, DeliveryRecord,
        DeliveryVenue, FillSource, Refused, VenueDeliverer,
    },
    deployments,
    model::{Fill, PaymentLeg},
    protocol::{self, aster, deliveries, eip712, signing::SigningKey},
    transport::Clock,
    types::{Amount, FillId, VenueId},
};

/// Aster's nonce window is about one minute: identical bytes are sent again for 50 seconds at
/// most.
const WINDOW: TimeDelta = TimeDelta::seconds(50);
/// Leaves Aster's 10-second synchronous request timeout before `deliver_by`.
const SEND_MARGIN: TimeDelta = TimeDelta::seconds(15);
/// Aster's own request timeout.
const TIMEOUT: Duration = Duration::from_secs(10);
/// USDT's decimals on Aster.
const DECIMALS: u8 = 18;

/// Aster's API bases.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct AsterApi {
    /// Transfers between accounts.
    pub chain: String,
    /// Futures: the margin.
    pub futures: String,
    /// Spot.
    pub spot: String,
}

impl AsterApi {
    /// Aster's mainnet.
    pub fn mainnet() -> Self {
        Self::new(
            "https://chainapi.asterdex.com",
            "https://fapi.asterdex.com",
            "https://sapi.asterdex.com",
        )
    }

    /// Other bases, a test double's.
    pub fn new(
        chain: impl Into<String>,
        futures: impl Into<String>,
        spot: impl Into<String>,
    ) -> Self {
        Self { chain: chain.into(), futures: futures.into(), spot: spot.into() }
    }
}

/// One fill's transfer, persisted before it is sent: `attempted` is set before each send,
/// `transfer_id` on Aster's acknowledgement. An `Unknown` outcome may have executed and is never
/// signed again; `Refused`, its first send refused; `Dropped`, never sent.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AsterDelivery {
    /// The fill.
    pub fill_id: FillId,
    /// The signed request, sent as is.
    pub query: String,
    /// Its nonce, in microseconds.
    pub nonce: u64,
    /// What it delivers, in USDT base units.
    pub amount: Amount,
    /// The taker's account.
    pub to: Address,
    /// Sent at least once.
    pub attempted: bool,
    /// Aster's transfer id, once acknowledged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transfer_id: Option<String>,
    /// What became of it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub outcome: Option<DeliveryOutcome>,
    /// When it was signed.
    pub created_at: DateTime<Utc>,
}

impl DeliveryRecord for AsterDelivery {
    fn fill_id(&self) -> FillId {
        self.fill_id
    }

    fn outcome(&self) -> Option<DeliveryOutcome> {
        self.outcome
    }
}

/// Aster's part of an [`AsterDeliverer`]: the account's owner signs transfers; its agent,
/// allowed only to trade, moves margin to Spot.
pub struct AsterVenue {
    owner: SigningKey,
    agent: SigningKey,
    http: Arc<dyn HttpExchange>,
    api: AsterApi,
    last_nonce: u64,
    send_at: Backoff,
}

impl fmt::Debug for AsterVenue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AsterVenue")
            .field("owner", &self.owner.address())
            .field("agent", &self.agent.address())
            .field("api", &self.api)
            .finish_non_exhaustive()
    }
}

/// Delivers a maker's fills into takers' Aster accounts.
pub type AsterDeliverer = VenueDeliverer<AsterVenue>;

impl AsterVenue {
    /// `owner` signs the account's transfers; `agent`, an agent of the same account allowed
    /// only to trade, moves its margin to Spot. Aster is reached through `http` at `api`.
    pub fn new(
        owner: impl Signer + Send + Sync + 'static,
        agent: impl Signer + Send + Sync + 'static,
        http: impl HttpExchange + 'static,
        api: AsterApi,
    ) -> Self {
        Self {
            owner: SigningKey::new(owner),
            agent: SigningKey::new(agent),
            http: Arc::new(http),
            api,
            last_nonce: 0,
            send_at: Backoff::default(),
        }
    }

    /// Microseconds, distinct for each request.
    fn nonce(&mut self, now: DateTime<Utc>) -> u64 {
        let micros = u64::try_from(now.timestamp_micros()).unwrap_or_default();
        self.last_nonce = micros.max(self.last_nonce + 1);
        self.last_nonce
    }

    /// Aster's JSON answer; a `{code<0}` answer to a request it read is a refusal, anything else
    /// unanswered an error.
    async fn request(
        &self,
        method: &'static str,
        url: String,
    ) -> Result<Map<String, Value>, DeliveryError> {
        let path = url.split('?').next().unwrap_or_default().to_owned();
        let mut headers = vec![("accept", "application/json".to_owned())];
        if method == "POST" {
            headers.push(("content-type", "application/x-www-form-urlencoded".to_owned()));
        }
        let request = HttpRequest { method, url, headers, body: None };
        let answer = tokio::time::timeout(TIMEOUT, self.http.send(request))
            .await
            .map_err(|_| DeliveryError::Venue(format!("Aster {path}: timed out")))?
            .map_err(|error| DeliveryError::Venue(format!("Aster {path}: {error}")))?;
        let status = answer.status();
        let body = match serde_json::from_slice::<Value>(&answer.into_body()) {
            Ok(Value::Object(body)) => Some(body),
            _ => None,
        };
        if let Some(body) = &body
            && let Some(code) = body.get("code").and_then(Value::as_i64).filter(|code| *code < 0)
            && status < 500
            && status != 429
        {
            let message = body.get("msg").and_then(Value::as_str).unwrap_or_default();
            return Err(Refused(format!("Aster refused: {code} {message}")).into());
        }
        match body {
            Some(body) if (200..300).contains(&status) => Ok(body),
            _ => Err(DeliveryError::Venue(format!("Aster {path}: HTTP {status}"))),
        }
    }

    /// A request signed by the agent for the owner's account.
    async fn by_agent(
        &mut self,
        now: DateTime<Utc>,
        method: &'static str,
        url: &str,
        params: &[(&str, String)],
    ) -> Result<Map<String, Value>, DeliveryError> {
        let mut fields = params.to_vec();
        fields.push(("nonce", self.nonce(now).to_string()));
        fields.push(("user", self.owner.address().to_checksum(None)));
        fields.push(("signer", self.agent.address().to_checksum(None)));
        let message = query(&fields);
        let signature = sign(&self.agent, &message, now).await?;
        self.request(method, format!("{url}?{message}&signature={signature}")).await
    }

    /// The USDT the account's Spot wallet holds, in base units. Spot without a USDT entry holds
    /// none; an entry without a readable `free` is refused.
    async fn spot(&mut self, now: DateTime<Utc>) -> Result<U256, DeliveryError> {
        let url = format!("{}/api/v3/account", self.api.spot);
        let account = self.by_agent(now, "GET", &url, &[]).await?;
        let balances = account
            .get("balances")
            .and_then(Value::as_array)
            .ok_or_else(|| DeliveryError::Venue("Aster answered no Spot balances".into()))?;
        let free = balances
            .iter()
            .find(|balance| balance.get("asset").and_then(Value::as_str) == Some("USDT"))
            .map_or(Some("0"), |balance| balance.get("free").and_then(Value::as_str));
        free.and_then(units)
            .ok_or_else(|| DeliveryError::Venue("Unexpected Aster Spot balance".into()))
    }

    /// Tops up Spot for `fill`, idempotently: returns what Spot holds after the transfer, or
    /// `None` after a margin move (Spot is read again).
    async fn fund_spot(
        &mut self,
        now: DateTime<Utc>,
        fill: &Fill,
        held: Option<U256>,
    ) -> Result<Option<U256>, DeliveryError> {
        let needed = deployments::venue_units(fill.amount_out.get(), &VenueId::Aster)
            .ok_or_else(|| DeliveryError::Venue("Unexpected Aster amount".into()))?;
        let held = match held {
            Some(held) => held,
            None => self.spot(now).await?,
        };
        if held >= needed {
            return Ok(Some(held - needed));
        }
        let url = format!("{}/fapi/v3/asset/wallet/transfer", self.api.futures);
        let params = [
            ("amount", amount_text(needed - held)?),
            ("asset", aster::TOKEN.to_owned()),
            ("clientTranId", format!("m{}", aster::client_id(fill.id))),
            ("kindType", "FUTURE_SPOT".to_owned()),
        ];
        self.by_agent(now, "POST", &url, &params).await?;
        Ok(None)
    }

    /// Signs `fill`'s transfer at `nonce`, by the account's owner at Aster's transfer chain.
    pub async fn sign(
        &self,
        fill: &Fill,
        nonce: u64,
        now: DateTime<Utc>,
    ) -> Result<AsterDelivery, DeliveryError> {
        let to = fill
            .delivery_to
            .as_deref()
            .and_then(eip712::address_text)
            .filter(|_| fill.to_venue == VenueId::Aster)
            .ok_or_else(|| DeliveryError::Venue("Not an Aster delivery".into()))?;
        let fields = [
            ("asset", aster::TOKEN.to_owned()),
            ("amount", amount_text(fill.amount_out.get())?),
            ("toAddress", to.to_checksum(None)),
            ("clientTranId", aster::client_id(fill.id)),
            ("nonce", nonce.to_string()),
            ("user", self.owner.address().to_checksum(None)),
        ];
        let message = query(&fields);
        let signature = sign(&self.owner, &message, now).await?;
        Ok(AsterDelivery {
            fill_id: fill.id,
            query: format!("{message}&signature={signature}"),
            nonce,
            amount: fill.amount_out,
            to,
            attempted: false,
            transfer_id: None,
            outcome: None,
            created_at: now,
        })
    }

    /// Sends the persisted bytes; Aster's transfer id.
    async fn send(&self, delivery: &AsterDelivery) -> Result<String, DeliveryError> {
        let url = format!("{}/aster-chain/v3/transfer?{}", self.api.chain, delivery.query);
        let reply = self.request("POST", url).await?;
        let id = match reply.get("transferId") {
            Some(Value::Number(id)) => Some(id.to_string()),
            Some(Value::String(id)) => Some(id.clone()),
            _ => None,
        };
        let status = reply.get("status").and_then(Value::as_str);
        match id {
            Some(id)
                if !id.is_empty()
                    && id.bytes().all(|b| b.is_ascii_digit())
                    && matches!(status, Some("SUCCESS" | "PENDING")) =>
            {
                Ok(id)
            }
            _ => Err(DeliveryError::Venue("Unexpected Aster transfer answer".into())),
        }
    }

    /// Signs, persists and sends `fill`'s transfer once Spot holds its amount; `spot`, what
    /// Spot holds as last read and spent since.
    async fn deliver_one<S: FillSource>(
        &mut self,
        core: &mut DeliveryCore,
        source: &S,
        fill: &Fill,
        spot: &mut Option<U256>,
        deliveries: &mut Deliveries<AsterDelivery>,
    ) -> Result<bool, DeliveryError> {
        let key = fill.id.to_string();
        if !core.turn(&mut self.send_at, &key) {
            return Ok(false);
        }
        // Signed only once Spot holds the amount, so the whole nonce window is left for
        // sending.
        let now = core.now();
        *spot = self.fund_spot(now, fill, *spot).await?;
        let nonce = self.nonce(now);
        let delivery = self.sign(fill, nonce, now).await?;
        core.record(deliveries, delivery.clone()).await?;
        self.send_at.clear(&key);
        self.settle_one(core, source, delivery, Some(fill), deliveries).await
    }

    /// Moves one delivery forward and records it; `Ok(false)` while Aster has not answered.
    #[allow(clippy::too_many_lines, reason = "the TypeScript settle(), step by step")]
    async fn settle_one<S: FillSource>(
        &mut self,
        core: &mut DeliveryCore,
        source: &S,
        mut delivery: AsterDelivery,
        fill: Option<&Fill>,
        deliveries: &mut Deliveries<AsterDelivery>,
    ) -> Result<bool, DeliveryError> {
        let id = delivery.fill_id;
        let key = id.to_string();
        let now = core.now();
        if let (None, Some(transfer)) = (fill, delivery.transfer_id.clone()) {
            // Fills listed after a resync or a restart are the open ones: this one may have
            // ended with this transfer, and the server's answer to the report tells.
            if core.report_due(&key)
                && let Some(outcome) = core.report(source, id, &transfer).await
            {
                delivery.outcome = Some(outcome);
                core.record(deliveries, delivery).await?;
            }
            return Ok(true);
        }
        let reported = delivery.transfer_id.is_some()
            && fill.and_then(|fill| fill.delivery_hash.as_ref()) == delivery.transfer_id.as_ref();
        let Some(fill) = fill.filter(|_| core.awaits(fill) && !reported) else {
            delivery.outcome =
                Some(if reported { DeliveryOutcome::Reported } else { DeliveryOutcome::Failed });
            core.record(deliveries, delivery).await?;
            tracing::info!(fill = %id, "fill no longer awaits this delivery");
            return Ok(true);
        };
        let transfer = if let Some(transfer) = delivery.transfer_id.clone() {
            transfer
        } else {
            let signed_at = micros(delivery.nonce);
            let late = fill.deliver_by.is_none_or(|by| by - now <= SEND_MARGIN);
            if now >= signed_at + WINDOW || late {
                // Past its window Aster refuses these bytes; an attempted one may have
                // executed, and another request for the fill could pay twice.
                let attempted = delivery.attempted;
                delivery.outcome = Some(if attempted {
                    DeliveryOutcome::Unknown
                } else {
                    DeliveryOutcome::Dropped
                });
                core.record(deliveries, delivery).await?;
                if attempted {
                    tracing::warn!(
                        fill = %id,
                        client_id = %aster::client_id(id),
                        "Aster never answered this transfer; not signed again: report its transferId if the account's history shows it"
                    );
                } else {
                    tracing::warn!(fill = %id, "too close to the delivery deadline, transfer not sent");
                }
                return Ok(true);
            }
            if !core.turn(&mut self.send_at, &key) {
                return Ok(false);
            }
            // Recorded before the request: a lost answer is never taken for a refusal.
            let first = !delivery.attempted;
            delivery.attempted = true;
            core.record(deliveries, delivery.clone()).await?;
            let transfer = match self.send(&delivery).await {
                Ok(transfer) => transfer,
                // Only a first send's refusal is final: after a lost answer, the earlier
                // send may have executed, and the resend's refusal says nothing of it.
                Err(DeliveryError::Refused(refused)) if first => {
                    // A private account or Spot short: left to its refund, never signed
                    // again.
                    delivery.outcome = Some(DeliveryOutcome::Refused);
                    core.record(deliveries, delivery).await?;
                    tracing::warn!(fill = %id, %refused, "transfer refused");
                    return Ok(true);
                }
                Err(error) => return Err(error),
            };
            self.send_at.clear(&key);
            delivery.transfer_id = Some(transfer.clone());
            core.record(deliveries, delivery.clone()).await?;
            tracing::info!(fill = %id, transfer = %transfer, "transfer sent");
            transfer
        };
        if core.report_due(&key)
            && let Some(outcome) = core.report(source, id, &transfer).await
        {
            delivery.outcome = Some(outcome);
            core.record(deliveries, delivery).await?;
        }
        Ok(true)
    }
}

impl DeliveryVenue for AsterVenue {
    type Record = AsterDelivery;

    fn venue(&self) -> VenueId {
        VenueId::Aster
    }

    fn send_margin(&self) -> TimeDelta {
        SEND_MARGIN
    }

    async fn settle<S: FillSource>(
        &mut self,
        core: &mut DeliveryCore,
        source: &S,
        id: &str,
        fill: Option<&Fill>,
        deliveries: &mut Deliveries<AsterDelivery>,
    ) -> Result<bool, DeliveryError> {
        let Some(delivery) = deliveries.get(id).cloned() else { return Ok(true) };
        self.settle_one(core, source, delivery, fill, deliveries).await
    }

    /// Signs and sends due fills whose payment is locked, one at a time, while each transfer
    /// gets an answer from Aster. Spot is read once and each amount deducted here; it is read
    /// again after a margin move.
    async fn deliver<S: FillSource>(
        &mut self,
        core: &mut DeliveryCore,
        source: &S,
        due: Vec<Fill>,
        deliveries: &mut Deliveries<AsterDelivery>,
    ) -> Result<bool, DeliveryError> {
        let mut spot = None;
        for fill in due.iter().filter(|fill| fill.payment_leg == PaymentLeg::Locked) {
            match self.deliver_one(core, source, fill, &mut spot, deliveries).await {
                Ok(true) => {}
                Ok(false) => return Ok(false),
                Err(error) => {
                    tracing::warn!(fill = %fill.id, %error, "delivery not sent");
                    return Ok(false);
                }
            }
        }
        Ok(true)
    }
}

/// `name=value` pairs joined by `&`, as Aster signs them: unencoded.
fn query(fields: &[(&str, String)]) -> String {
    fields.iter().map(|(name, value)| format!("{name}={value}")).collect::<Vec<_>>().join("&")
}

/// `msg` signed by `key` as Aster's `Message` at its transfer chain: `0x` and 130 hex digits.
async fn sign(key: &SigningKey, msg: &str, now: DateTime<Utc>) -> Result<String, DeliveryError> {
    let verified = deliveries::aster_request(msg, key.address()).map_err(Error::from)?;
    let clock: Clock = Arc::new(move || now);
    let signature = key.sign(&verified, &clock).await?;
    Ok(format!("0x{}", alloy_primitives::hex::encode(signature.as_bytes())))
}

/// Microseconds as a time.
fn micros(micros: u64) -> DateTime<Utc> {
    DateTime::from_timestamp_micros(i64::try_from(micros).unwrap_or(i64::MAX)).unwrap_or_default()
}

/// A decimal USDT amount (`"12.5"`) in base units, digits beyond the eighteenth decimal dropped
/// (rounded down: never more than Spot holds); `None` for any other text.
fn units(text: &str) -> Option<U256> {
    let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
    let digits = |part: &str| part.bytes().all(|b| b.is_ascii_digit());
    if whole.is_empty() || !digits(whole) || !digits(fraction) || text.ends_with('.') {
        return None;
    }
    // Beyond its eighteen decimals, Aster's Spot holds nothing a transfer could use.
    let fraction: String =
        fraction.chars().chain(std::iter::repeat('0')).take(DECIMALS.into()).collect();
    let unit = U256::from(10u8).pow(U256::from(DECIMALS));
    let whole = U256::from_str_radix(whole, 10).ok()?;
    whole.checked_mul(unit)?.checked_add(U256::from_str_radix(&fraction, 10).ok()?)
}

/// Base units of USDT as Aster takes them: six decimals at most, rounded up.
fn amount_text(units: U256) -> Result<String, DeliveryError> {
    protocol::aster_amount(units)
        .ok_or_else(|| DeliveryError::Venue("Unexpected Aster amount".into()))
}

#[cfg(test)]
mod tests;