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
//! Doubles for the deliverers' tests: a fill source, a venue's HTTP API and a movable clock.

use std::{
    future::Future,
    sync::{
        Arc, Mutex,
        atomic::{AtomicI64, Ordering},
    },
};

use chrono::{DateTime, Utc};
use serde_json::{Value, json};

use super::FillSource;
use crate::{
    HostError, HttpAnswer, HttpExchange, HttpExchangeFuture, HttpRequest, Result,
    model::Fill,
    testing::{
        NOW,
        fixtures::{fill, model},
        stamp,
    },
    types::FillId,
};

/// A clock in milliseconds that a test moves.
#[derive(Clone)]
pub(crate) struct Clock(Arc<AtomicI64>);

impl Clock {
    pub(crate) fn new() -> Self {
        Self(Arc::new(AtomicI64::new(NOW * 1000)))
    }

    pub(crate) fn now(&self) -> DateTime<Utc> {
        DateTime::from_timestamp_millis(self.0.load(Ordering::SeqCst)).unwrap()
    }

    pub(crate) fn advance(&self, millis: i64) {
        self.0.fetch_add(millis, Ordering::SeqCst);
    }

    pub(crate) fn reader(&self) -> impl Fn() -> DateTime<Utc> + Send + Sync + 'static {
        let clock = self.clone();
        move || clock.now()
    }
}

/// A maker's fill paid and verified, delivered on `venue` to `to`, due in two minutes.
pub(crate) fn due(venue: &str, id: &str, amount_out: &str, to: &str, now: DateTime<Utc>) -> Fill {
    let mut value = fill("hyperliquid", venue, amount_out, amount_out);
    let patch = json!({
        "id": id, "role": "maker", "state": "PAID", "payment_leg": "LOCKED", "maker_leg": "NONE",
        "deliver_by": stamp(now + chrono::TimeDelta::seconds(120)),
        "report_by": stamp(now + chrono::TimeDelta::seconds(6_600)),
        "delivery_to": to, "delivery_hash": null, "payment_verified_at": stamp(now),
        "maker_accept_by": null, "maker_accepted_at": null,
    });
    value.as_object_mut().unwrap().extend(patch.as_object().unwrap().clone());
    model(&value)
}

/// The identity's fills, its reports recorded and answered with the fill, delivered.
pub(crate) struct Fills {
    pub(crate) listed: Mutex<Vec<Fill>>,
    pub(crate) reported: Mutex<Vec<(FillId, String)>>,
    pub(crate) accepted: Mutex<Vec<FillId>>,
}

impl Fills {
    pub(crate) fn new(fills: Vec<Fill>) -> Self {
        Self { listed: Mutex::new(fills), reported: Mutex::default(), accepted: Mutex::default() }
    }

    pub(crate) fn reported(&self) -> Vec<(FillId, String)> {
        self.reported.lock().unwrap().clone()
    }
}

impl FillSource for Fills {
    fn fills(&self) -> impl Future<Output = Result<Vec<Fill>>> {
        std::future::ready(Ok(self.listed.lock().unwrap().clone()))
    }

    fn accept(&self, id: FillId) -> impl Future<Output = Result<()>> {
        self.accepted.lock().unwrap().push(id);
        std::future::ready(Ok(()))
    }

    fn deliver(&self, id: FillId, hash: &str) -> impl Future<Output = Result<Fill>> {
        self.reported.lock().unwrap().push((id, hash.to_owned()));
        let mut fill =
            self.listed.lock().unwrap().iter().find(|fill| fill.id == id).cloned().unwrap();
        fill.delivery_hash = Some(hash.to_owned());
        std::future::ready(Ok(fill))
    }
}

/// A request a venue double received.
#[derive(Debug, Clone)]
pub(crate) struct Received {
    pub(crate) url: String,
    pub(crate) body: Option<String>,
}

type Handler = Box<dyn Fn(&Received) -> std::result::Result<(u16, Value), HostError> + Send + Sync>;

/// A venue's HTTP API: each request recorded, then answered by the handler.
pub(crate) struct Venue {
    pub(crate) received: Mutex<Vec<Received>>,
    handler: Handler,
}

impl Venue {
    pub(crate) fn new(
        handler: impl Fn(&Received) -> std::result::Result<(u16, Value), HostError>
        + Send
        + Sync
        + 'static,
    ) -> Arc<Self> {
        Arc::new(Self { received: Mutex::default(), handler: Box::new(handler) })
    }

    /// The requests received at URLs containing `path`.
    pub(crate) fn at(&self, path: &str) -> Vec<Received> {
        self.received
            .lock()
            .unwrap()
            .iter()
            .filter(|request| request.url.contains(path))
            .cloned()
            .collect()
    }
}

impl HttpExchange for Venue {
    fn send(&self, request: HttpRequest) -> HttpExchangeFuture<'_> {
        let received = Received {
            url: request.url,
            body: request.body.map(|body| String::from_utf8(body).unwrap()),
        };
        self.received.lock().unwrap().push(received.clone());
        let answer = (self.handler)(&received)
            .map(|(status, body)| HttpAnswer::new(status, serde_json::to_vec(&body).unwrap()));
        Box::pin(async move { answer })
    }
}