settlem 0.1.0

Typed Rust client foundations for integrating with Settlem settlement infrastructure.
Documentation
#![forbid(unsafe_code)]
#![deny(missing_docs)]
//! Public Rust client types for Settlem settlement infrastructure.
//!
//! The crate is deliberately transport-agnostic. Applications keep control of
//! their HTTP stack and Solana wallet while sharing Settlem's stable public
//! identifiers and response formats.

use serde::{Deserialize, Serialize};
use std::{error::Error, fmt};

/// The current public Settlem Devnet program address.
pub const DEVNET_PROGRAM_ID: &str = "AWk6gYZDfKBmJd8LTYNrxP7wmcxhTjZkTUr4j3Hyfh68";

macro_rules! identifier {
    ($name:ident, $description:literal) => {
        #[doc = $description]
        #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
        #[serde(transparent)]
        pub struct $name(String);

        impl $name {
            /// Creates a validated non-empty identifier.
            pub fn new(value: impl Into<String>) -> Result<Self, ClientConfigurationError> {
                let value = value.into();
                if value.trim().is_empty() {
                    return Err(ClientConfigurationError::EmptyIdentifier(stringify!($name)));
                }
                Ok(Self(value))
            }

            /// Returns the identifier as text.
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str(&self.0)
            }
        }
    };
}

identifier!(SettlementId, "A durable Settlem settlement identifier.");
identifier!(ActionId, "A durable, idempotent Settlem action identifier.");

/// Errors detected before any request or wallet action is attempted.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ClientConfigurationError {
    /// An identifier contained no usable characters.
    EmptyIdentifier(&'static str),
    /// The API base URL was empty or used an unsupported scheme.
    InvalidApiBase,
}

impl fmt::Display for ClientConfigurationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyIdentifier(kind) => write!(formatter, "{kind} must not be empty"),
            Self::InvalidApiBase => formatter.write_str("API base must use http:// or https://"),
        }
    }
}

impl Error for ClientConfigurationError {}

/// A wallet-signable transaction prepared by the Settlem hosted API.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PreparedTransaction {
    /// Durable settlement associated with the action, when already known.
    pub settlement_id: Option<SettlementId>,
    /// Durable action used for confirmation and idempotent retry.
    pub action_id: Option<ActionId>,
    /// Base64-encoded Solana transaction message for wallet approval.
    pub prepared_transaction: String,
    /// Recent Solana blockhash used by the prepared transaction.
    pub blockhash: String,
    /// Last block height at which the prepared transaction remains valid.
    pub last_valid_block_height: u64,
    /// Wallets that must approve the prepared transaction.
    pub required_signers: Vec<String>,
    /// Estimated Solana network fee in lamports.
    pub estimated_network_fee_lamports: String,
    /// Estimated refundable account rent in lamports.
    pub estimated_rent_lamports: String,
    /// Amount transferred by the action in lamports, when applicable.
    pub estimated_transfer_lamports: String,
}

/// The minimal confirmation payload sent after the user's wallet broadcasts.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConfirmationRequest {
    /// The exact action that was prepared before wallet approval.
    pub action_id: ActionId,
    /// Confirmed Solana transaction signature.
    pub signature: String,
}

/// Transport-neutral URL builder for the Settlem hosted API.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SettlemClient {
    api_base: String,
}

impl SettlemClient {
    /// Creates a client URL builder for an official or self-managed endpoint.
    pub fn new(api_base: impl Into<String>) -> Result<Self, ClientConfigurationError> {
        let api_base = api_base.into().trim().trim_end_matches('/').to_owned();
        if !(api_base.starts_with("https://") || api_base.starts_with("http://")) {
            return Err(ClientConfigurationError::InvalidApiBase);
        }
        Ok(Self { api_base })
    }

    /// Returns the configured API base URL.
    pub fn api_base(&self) -> &str {
        &self.api_base
    }

    /// Returns the canonical read endpoint for a settlement.
    pub fn settlement_url(&self, settlement_id: &SettlementId) -> String {
        format!("{}/api/v1/settlements/{}", self.api_base, settlement_id)
    }

    /// Returns the canonical confirmation endpoint for a prepared action.
    pub fn action_confirmation_url(&self, action_id: &ActionId) -> String {
        format!("{}/api/v1/actions/{}/confirm", self.api_base, action_id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn builds_stable_public_urls() {
        let client = SettlemClient::new("https://api.settlem.io/").unwrap();
        let settlement = SettlementId::new("settlement_01").unwrap();
        let action = ActionId::new("action_01").unwrap();

        assert_eq!(
            client.settlement_url(&settlement),
            "https://api.settlem.io/api/v1/settlements/settlement_01"
        );
        assert_eq!(
            client.action_confirmation_url(&action),
            "https://api.settlem.io/api/v1/actions/action_01/confirm"
        );
    }

    #[test]
    fn prepared_transaction_matches_camel_case_api_shape() {
        let parsed: PreparedTransaction = serde_json::from_str(
            r#"{
              "settlementId":"settlement_01",
              "actionId":"action_01",
              "preparedTransaction":"base64",
              "blockhash":"hash",
              "lastValidBlockHeight":42,
              "requiredSigners":["wallet"],
              "estimatedNetworkFeeLamports":"5000",
              "estimatedRentLamports":"0",
              "estimatedTransferLamports":"0"
            }"#,
        )
        .unwrap();

        assert_eq!(parsed.action_id.unwrap().as_str(), "action_01");
    }
}