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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Maker deliveries inside a venue: a fill delivered to a taker's account on Lighter or Aster is
//! the maker's own transfer there, sent and reported by a [`VenueDeliverer`].
//!
//! Each transfer is persisted in the journal before it is sent and never signed again for the
//! same fill: a lost answer resends the same bytes, which the venue executes once. Deliveries
//! whose outcome stays unknown stop new ones, and [`VenueDeliverer::blocked`] tells the pool to
//! stop taking fills.

use std::{
    collections::{BTreeMap, HashMap},
    fmt,
    future::Future,
    sync::Arc,
};

use chrono::{DateTime, TimeDelta, Utc};
use serde::{Deserialize, Serialize, de::DeserializeOwned};

use crate::{
    Error, Quoter, Result,
    error::ErrorCode,
    flows::records,
    model::{Fill, FillRole, FillState, MakerLeg, PaymentLeg},
    store::Journal,
    types::{FillId, VenueId},
};

/// Deliveries stuck this long stop the pool's quotes: a new fill could not be delivered.
const STUCK: TimeDelta = TimeDelta::seconds(15);

/// Where a deliverer reads the identity's fills and reports deliveries: a [`Quoter`], or a
/// host's feed of the same fills.
pub trait FillSource: Send + Sync {
    /// The identity's open fills.
    fn fills(&self) -> impl Future<Output = Result<Vec<Fill>>> + Send;
    /// Accepts fill `id`'s requested delivery.
    fn accept(&self, id: FillId) -> impl Future<Output = Result<()>> + Send;
    /// Reports `hash` as fill `id`'s delivery.
    fn deliver(&self, id: FillId, hash: &str) -> impl Future<Output = Result<Fill>> + Send;
}

impl FillSource for Quoter {
    async fn fills(&self) -> Result<Vec<Fill>> {
        Quoter::fills(self).list().await
    }

    async fn accept(&self, id: FillId) -> Result<()> {
        Quoter::fills(self).accept(id).await
    }

    async fn deliver(&self, id: FillId, hash: &str) -> Result<Fill> {
        Quoter::fills(self).deliver(id, hash).await
    }
}

/// The venue answered a send and refused it: these bytes never execute.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{0}")]
pub struct Refused(pub String);

/// Why a delivery pass stopped.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DeliveryError {
    /// The venue refused a request it read.
    #[error(transparent)]
    Refused(#[from] Refused),
    /// The venue did not answer, or answered something unexpected; its outcome is unknown.
    #[error("{0}")]
    Venue(String),
    /// LaMarge, the journal or a signer failed.
    #[error(transparent)]
    Lamarge(#[from] Error),
}

/// What became of a delivery; none while it moves.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DeliveryOutcome {
    /// LaMarge took the report.
    Reported,
    /// LaMarge will never take it, or the fill no longer awaits it.
    Failed,
    /// Never sent, failed or expired on the venue: it never executes.
    Dropped,
    /// The venue refused its first send: the fill is left to its refund.
    Refused,
    /// Unanswered past its window: it may have executed, and is never signed again.
    Unknown,
}

/// A persisted delivery of one fill.
pub trait DeliveryRecord: Clone + Serialize + DeserializeOwned + Send + Sync + 'static {
    /// The fill it delivers.
    fn fill_id(&self) -> FillId;
    /// What became of it; `None` while it moves.
    fn outcome(&self) -> Option<DeliveryOutcome>;
}

/// The deliveries a deliverer persisted, by fill id: read whole, saved whole.
pub type Deliveries<D> = BTreeMap<String, D>;

/// When an id's next try is due, with a growing wait.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Retry {
    at: DateTime<Utc>,
    wait: TimeDelta,
}

/// Per-fill backoff between tries.
#[derive(Debug, Default, Clone)]
pub struct Backoff(HashMap<String, Retry>);

impl Backoff {
    /// Forgets `id`'s waits.
    pub fn clear(&mut self, id: &str) {
        self.0.remove(id);
    }
}

/// The record a deliverer keeps in its journal.
#[derive(Serialize, Deserialize)]
#[serde(bound = "D: DeliveryRecord")]
struct Record<D> {
    deliveries: Deliveries<D>,
}

/// What every venue's deliverer shares: its journal, its clock, report backoff and whether it
/// still accepts new deliveries.
pub struct DeliveryCore {
    venue: VenueId,
    send_margin: TimeDelta,
    journal: Journal,
    key: String,
    clock: Arc<dyn Fn() -> DateTime<Utc> + Send + Sync>,
    accepting: bool,
    stuck_since: Option<DateTime<Utc>>,
    report_at: HashMap<String, Retry>,
}

impl fmt::Debug for DeliveryCore {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DeliveryCore")
            .field("venue", &self.venue)
            .field("key", &self.key)
            .field("accepting", &self.accepting)
            .field("stuck_since", &self.stuck_since)
            .finish_non_exhaustive()
    }
}

impl DeliveryCore {
    /// The deliverer's clock now.
    pub fn now(&self) -> DateTime<Utc> {
        (self.clock)()
    }

    /// The persisted deliveries.
    pub async fn load<D: DeliveryRecord>(&self) -> Result<Deliveries<D>> {
        let record = records::load::<Record<D>>(&self.journal, &self.key).await?;
        Ok(record.map_or_else(Deliveries::new, |record| record.deliveries))
    }

    /// Persists `deliveries` whole: nothing is sent before this returns.
    pub async fn save<D: DeliveryRecord>(&self, deliveries: &Deliveries<D>) -> Result<()> {
        let record = Record { deliveries: deliveries.clone() };
        records::save(&self.journal, &self.key, &record, false).await
    }

    /// Saves `delivery` into `deliveries`, then all of them.
    pub async fn record<D: DeliveryRecord>(
        &self,
        deliveries: &mut Deliveries<D>,
        delivery: D,
    ) -> Result<()> {
        deliveries.insert(delivery.fill_id().to_string(), delivery);
        self.save(deliveries).await
    }

    /// Whether `fill` still awaits a delivery report: its payment locked, its maker leg open or
    /// abandoned unreported, before `report_by`.
    pub fn awaits(&self, fill: Option<&Fill>) -> bool {
        fill.is_some_and(|fill| {
            fill.payment_leg == PaymentLeg::Locked
                && matches!(fill.maker_leg, MakerLeg::None | MakerLeg::Abandoned)
                && fill.report_by.is_none_or(|by| by > self.now())
        })
    }

    /// False while `id` waits for its next try in `backoff`; otherwise schedules the next one,
    /// twice as far (250 ms doubling, at most 5 s).
    pub fn turn(&self, backoff: &mut Backoff, id: &str) -> bool {
        let now = self.now();
        let last = backoff.0.get(id).copied();
        if last.is_some_and(|last| last.at > now) {
            return false;
        }
        let wait = (last.map_or(TimeDelta::milliseconds(250), |last| last.wait) * 2)
            .min(TimeDelta::seconds(5));
        backoff.0.insert(id.to_owned(), Retry { at: now + wait, wait });
        true
    }

    /// Whether `id`'s report may be sent again.
    pub fn report_due(&self, id: &str) -> bool {
        self.report_at.get(id).is_none_or(|retry| retry.at <= self.now())
    }

    /// Reports `hash` as fill `id`'s delivery: `Reported` once LaMarge records it, `Failed` when
    /// it never will, `None` to retry (less often while the venue does not show it final yet).
    pub async fn report<S: FillSource>(
        &mut self,
        source: &S,
        id: FillId,
        hash: &str,
    ) -> Option<DeliveryOutcome> {
        let key = id.to_string();
        let error = match source.deliver(id, hash).await {
            Ok(fill) if fill.delivery_hash.as_deref() == Some(hash) => {
                self.report_at.remove(&key);
                tracing::info!(fill = %id, state = %fill.state, "delivered");
                return Some(DeliveryOutcome::Reported);
            }
            Ok(_) => Error::InvalidRequest("the server recorded another delivery".into()),
            Err(error) => error,
        };
        let code = error.code().cloned();
        if matches!(
            code,
            Some(ErrorCode::ValidationError | ErrorCode::StateConflict | ErrorCode::NotFound)
        ) {
            tracing::warn!(fill = %id, %error, "delivery refused");
            return Some(DeliveryOutcome::Failed);
        }
        let last = self.report_at.get(&key).map(|retry| retry.wait);
        let wait = if code == Some(ErrorCode::DeliveryPending) {
            (last.unwrap_or(TimeDelta::milliseconds(500)) * 2).min(TimeDelta::seconds(30))
        } else {
            TimeDelta::seconds(1)
        };
        self.report_at.insert(key, Retry { at: self.now() + wait, wait });
        tracing::info!(fill = %id, %error, "report pending");
        None
    }
}

/// A venue's transfers for a [`VenueDeliverer`]: how it signs, sends and settles a fill's
/// delivery there.
pub trait DeliveryVenue: Send {
    /// What it persists for each fill.
    type Record: DeliveryRecord;

    /// The venue.
    fn venue(&self) -> VenueId;

    /// No transfer is first sent closer than this to the fill's `deliver_by`.
    fn send_margin(&self) -> TimeDelta;

    /// Moves the persisted delivery of fill `id` forward; `Ok(false)` while its outcome on the
    /// venue is unknown. `fill` is the fill as listed, if still listed.
    fn settle<S: FillSource>(
        &mut self,
        core: &mut DeliveryCore,
        source: &S,
        id: &str,
        fill: Option<&Fill>,
        deliveries: &mut Deliveries<Self::Record>,
    ) -> impl Future<Output = std::result::Result<bool, DeliveryError>> + Send;

    /// Delivers fills of `due`, the earliest deadline first; `Ok(false)` while one's outcome on
    /// the venue is unknown.
    fn deliver<S: FillSource>(
        &mut self,
        core: &mut DeliveryCore,
        source: &S,
        due: Vec<Fill>,
        deliveries: &mut Deliveries<Self::Record>,
    ) -> impl Future<Output = std::result::Result<bool, DeliveryError>> + Send;
}

/// Delivers a maker identity's fills on one venue: settles persisted deliveries first, then,
/// only once no outcome is unknown, delivers paid fills whose payment LaMarge verified, then
/// accepts requested deliveries. Run it on every change of the fills; one pass at a time.
pub struct VenueDeliverer<V: DeliveryVenue> {
    venue: V,
    core: DeliveryCore,
}

impl<V: DeliveryVenue + fmt::Debug> fmt::Debug for VenueDeliverer<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VenueDeliverer")
            .field("venue", &self.venue)
            .field("core", &self.core)
            .finish()
    }
}

impl<V: DeliveryVenue> VenueDeliverer<V> {
    /// A deliverer of `venue`'s transfers, its deliveries persisted in `journal` under
    /// `deliveries:{venue}`: give each pool its own journal.
    pub fn new(venue: V, journal: Journal) -> Self {
        let id = venue.venue();
        let core = DeliveryCore {
            key: format!("deliveries:{id}"),
            venue: id,
            send_margin: venue.send_margin(),
            journal,
            clock: Arc::new(Utc::now),
            accepting: true,
            stuck_since: None,
            report_at: HashMap::new(),
        };
        Self { venue, core }
    }

    /// Reads time from `clock` instead of the system's.
    #[must_use]
    pub fn clock(mut self, clock: impl Fn() -> DateTime<Utc> + Send + Sync + 'static) -> Self {
        self.core.clock = Arc::new(clock);
        self
    }

    /// The venue's part.
    pub fn venue(&self) -> &V {
        &self.venue
    }

    /// The deliveries persisted, by fill id.
    pub async fn deliveries(&self) -> Result<Deliveries<V::Record>> {
        self.core.load().await
    }

    /// Stops accepting new deliveries while draining those already accepted.
    pub fn stop_accepting(&mut self) {
        self.core.accepting = false;
    }

    /// True while deliveries have been stuck for a while: the pool must stop taking fills.
    pub fn blocked(&self) -> bool {
        self.core.stuck_since.is_some_and(|since| self.core.now() - since >= STUCK)
    }

    /// One pass: settles persisted deliveries, then delivers and accepts as the fills allow.
    pub async fn run<S: FillSource>(
        &mut self,
        source: &S,
    ) -> std::result::Result<(), DeliveryError> {
        let pass = self.pass(source).await;
        let now = self.core.now();
        match pass {
            Ok(true) => self.core.stuck_since = None,
            Ok(false) | Err(_) => {
                self.core.stuck_since.get_or_insert(now);
            }
        }
        pass.map(|_| ())
    }

    /// Unsettled deliveries plus fills this deliverer can still send: a shutdown waits for zero.
    pub async fn outstanding<S: FillSource>(&self, source: &S) -> Result<usize> {
        let deliveries = self.core.load::<V::Record>().await?;
        let open = deliveries.values().filter(|delivery| delivery.outcome().is_none()).count();
        let now = self.core.now();
        let fills = source.fills().await?;
        let sendable = fills
            .iter()
            .filter(|fill| {
                fill.role == FillRole::Maker
                    && fill.to_venue == self.core.venue
                    && fill.maker_leg == MakerLeg::None
                    && (matches!(fill.state, FillState::Reserved | FillState::Paid)
                        || (fill.state == FillState::Prepared && fill.maker_accepted_at.is_some()))
                    && fill.deliver_by.is_some_and(|by| by - self.core.send_margin > now)
            })
            .count();
        Ok(open + sendable)
    }

    async fn pass<S: FillSource>(
        &mut self,
        source: &S,
    ) -> std::result::Result<bool, DeliveryError> {
        let mut deliveries = self.core.load::<V::Record>().await?;
        let fills: Vec<Fill> = source
            .fills()
            .await?
            .into_iter()
            .filter(|fill| {
                fill.role == FillRole::Maker
                    && fill.to_venue == self.core.venue
                    && fill.delivery_to.is_some()
            })
            .collect();
        let open: Vec<String> = deliveries
            .iter()
            .filter(|(_, delivery)| delivery.outcome().is_none())
            .map(|(id, _)| id.clone())
            .collect();
        let mut unknown = false;
        for id in open {
            let fill = fills.iter().find(|fill| fill.id.to_string() == id);
            match self.venue.settle(&mut self.core, source, &id, fill, &mut deliveries).await {
                Ok(settled) => unknown |= !settled,
                Err(error) => {
                    unknown = true;
                    tracing::warn!(fill = %id, %error, "delivery unsettled");
                }
            }
        }
        if unknown {
            return Ok(false);
        }
        let now = self.core.now();
        let margin = self.core.send_margin;
        let mut due: Vec<Fill> = fills
            .iter()
            .filter(|fill| {
                !deliveries.contains_key(&fill.id.to_string())
                    && fill.state == FillState::Paid
                    && fill.maker_leg == MakerLeg::None
                    && fill.delivery_hash.is_none()
                    && fill.payment_verified_at.is_some()
                    && fill.deliver_by.is_some_and(|by| by - now > margin)
            })
            .cloned()
            .collect();
        due.sort_by_key(|fill| fill.deliver_by);
        let progressed = self.venue.deliver(&mut self.core, source, due, &mut deliveries).await?;
        if !progressed || !self.core.accepting {
            return Ok(progressed);
        }
        let requests: Vec<FillId> = fills
            .iter()
            .filter(|fill| {
                fill.maker_accept_by.is_some_and(|by| by > now)
                    && fill.maker_accepted_at.is_none()
                    && matches!(fill.state, FillState::Prepared | FillState::Reserved)
                    && fill.maker_leg == MakerLeg::None
                    && fill.payment_leg == PaymentLeg::None
            })
            .map(|fill| fill.id)
            .collect();
        if !requests.is_empty() {
            // Accept only what the journal can record.
            self.core.save(&deliveries).await?;
            let accepted =
                futures_util::future::join_all(requests.iter().map(|id| source.accept(*id))).await;
            for (id, outcome) in requests.iter().zip(accepted) {
                match outcome {
                    Ok(()) => tracing::info!(fill = %id, "accepted for delivery"),
                    Err(error) => tracing::warn!(fill = %id, %error, "acceptance pending"),
                }
            }
        }
        Ok(true)
    }
}

#[cfg(test)]
pub(crate) mod testing;