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
//! Maker credentials: create, rotate and delete.

use std::time::Duration;

use alloy_primitives::Address;
use chrono::{DateTime, Utc};

use super::Credentials;
use crate::{
    Error, Result,
    model::{
        CredentialCreated, CredentialInput, CredentialRotated, CredentialScope, RotationBody,
        expires_at,
    },
    protocol::checks::maker::check_created_credential,
    transport::{Call, ops},
    types::QuoteIdentityId,
};

/// A maker credential to create: a bearer bound to one quote identity and quote signer, never
/// able to move capital.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CredentialRequest {
    name: String,
    quote_signer: Address,
    scopes: Vec<CredentialScope>,
    expires_in: Duration,
}

impl CredentialRequest {
    /// A credential named `name` (1 to 80 characters, not blank) for `quote_signer` (nonzero),
    /// valid for `expires_in` (1 second to 90 days), with scopes read, quote and cancel.
    pub fn new(name: impl Into<String>, quote_signer: Address, expires_in: Duration) -> Self {
        Self {
            name: name.into(),
            quote_signer,
            scopes: vec![CredentialScope::Read, CredentialScope::Quote, CredentialScope::Cancel],
            expires_in,
        }
    }

    /// Replaces the scopes; duplicates are dropped, the first occurrence kept.
    #[must_use]
    pub fn scopes(mut self, scopes: impl IntoIterator<Item = CredentialScope>) -> Self {
        self.scopes.clear();
        for scope in scopes {
            if !self.scopes.contains(&scope) {
                self.scopes.push(scope);
            }
        }
        self
    }

    /// The wire body at `now`, or `InvalidRequest` for an input the API refuses.
    fn body(&self, now: DateTime<Utc>) -> Result<CredentialInput> {
        let chars = self.name.chars().count();
        if self.name.trim().is_empty() || chars > 80 {
            return Err(Error::InvalidRequest("name must be 1 to 80 characters, not blank".into()));
        }
        if self.quote_signer.is_zero() {
            return Err(Error::InvalidRequest("quote_signer must be nonzero".into()));
        }
        if self.scopes.is_empty() || self.scopes.iter().any(CredentialScope::is_unknown) {
            return Err(Error::InvalidRequest("scopes must be some of read, quote, cancel".into()));
        }
        Ok(CredentialInput {
            name: self.name.clone(),
            quote_signer: self.quote_signer,
            scopes: self.scopes.clone(),
            expires_at: expires_at(now, self.expires_in)?,
        })
    }
}

impl Credentials<'_> {
    /// Creates a maker credential; its token is returned only once.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidRequest`], before anything is sent, for a request the API refuses.
    /// - [`Error::Verification`] when the answer does not echo the quote signer and scopes.
    pub async fn create(&self, request: &CredentialRequest) -> Result<CredentialCreated> {
        let body = request.body(self.inner.now())?;
        let created: CredentialCreated =
            self.inner.send(Call::new(&ops::CREATE_CREDENTIAL).json(&body)?, self.auth).await?;
        check_created_credential(&created, body.quote_signer, &body.scopes)?;
        Ok(created)
    }

    /// Replaces a credential's token, valid for `expires_in` (1 second to 90 days), keeping its
    /// identity and quote signer; the previous token stops working and the identity's quotes
    /// and lease end. Works on expired, not revoked, credentials.
    pub async fn rotate(
        &self,
        id: QuoteIdentityId,
        expires_in: Duration,
    ) -> Result<CredentialRotated> {
        let body = RotationBody { expires_at: expires_at(self.inner.now(), expires_in)? };
        let call = Call::new(&ops::ROTATE_CREDENTIAL).segment(id).json(&body)?;
        self.inner.send(call, self.auth).await
    }

    /// Revokes a credential and its identity for good, removing its quotes; reserved fills still
    /// settle. Repeats succeed.
    pub async fn delete(&self, id: QuoteIdentityId) -> Result<()> {
        self.inner.send(Call::new(&ops::DELETE_CREDENTIAL).segment(id), self.auth).await
    }
}

#[cfg(test)]
mod tests;