use std::time::Duration;
use reqwest::header::{ACCEPT, CONTENT_TYPE, RETRY_AFTER};
use reqwest::{redirect, Method, Url};
use serde::de::DeserializeOwned;
use serde_json::Value;
use crate::decimal::is_plain_decimal;
use crate::models::{parse_rates, PaymentLinks};
use crate::{
Balances, CreatePaymentLinkParams, CreatePaymentParams, CreatedPayment, Error, ExchangeRate,
ListPaymentsParams, Payment, PaymentLink, PaymentList, PaymentStatus, PayoutParams,
PayoutResponse, RotatedWebhookSecret, UpdateWebhookConfigParams, WebhookConfig,
};
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_MAX_RETRIES: u32 = 2;
const MAX_RETRY_AFTER: Duration = Duration::from_secs(60);
const NETWORK_MESSAGE: &str = "Network error — check your connection and base URL";
#[derive(Debug, Clone)]
pub struct Client {
http: reqwest::Client,
base_url: String,
api_key: String,
max_retries: u32,
}
#[derive(Debug, Clone)]
pub struct ClientBuilder {
api_key: String,
base_url: String,
timeout: Duration,
max_retries: u32,
}
impl ClientBuilder {
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn max_retries(mut self, max_retries: u32) -> Self {
self.max_retries = max_retries;
self
}
pub fn build(self) -> Result<Client, Error> {
if self.api_key.is_empty() {
return Err(Error::invalid("api_key is required"));
}
let base_url = api_origin(&self.base_url)?;
let http = reqwest::Client::builder()
.timeout(self.timeout)
.redirect(redirect::Policy::none())
.user_agent(format!("bitmomo-rust/{}", crate::VERSION))
.build()
.map_err(|e| {
Error::invalid(format!("could not build the HTTP client: {e}")).with_source(e)
})?;
Ok(Client {
http,
base_url,
api_key: self.api_key,
max_retries: self.max_retries,
})
}
}
fn api_origin(raw: &str) -> Result<String, Error> {
let invalid = || Error::invalid("an explicit valid base_url is required");
if raw.is_empty() {
return Err(invalid());
}
let url = Url::parse(raw).map_err(|_| invalid())?;
let host = url.host_str().ok_or_else(invalid)?.to_string();
let scheme = url.scheme();
let loopback = matches!(host.as_str(), "localhost" | "127.0.0.1" | "[::1]");
if (scheme != "https" && !(scheme == "http" && loopback))
|| !url.username().is_empty()
|| url.password().is_some()
|| url.query().is_some_and(|q| !q.is_empty())
|| url.fragment().is_some()
|| url.path() != "/"
{
return Err(Error::invalid(
"base_url must be an HTTPS origin (loopback HTTP is allowed), without credentials, path, query or fragment",
));
}
Ok(match url.port() {
Some(port) => format!("{scheme}://{host}:{port}"),
None => format!("{scheme}://{host}"),
})
}
fn segment(name: &str, value: &str) -> Result<String, Error> {
if value.is_empty() {
return Err(Error::invalid(format!("{name} is required")));
}
let mut out = String::with_capacity(value.len());
for b in value.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
Ok(out)
}
pub(crate) fn retry_delay(retry_after: Option<&str>, attempt: u32) -> Duration {
if let Some(seconds) = retry_after.and_then(|v| v.trim().parse::<f64>().ok()) {
if seconds.is_finite() && seconds >= 0.0 {
return Duration::from_secs_f64(seconds).min(MAX_RETRY_AFTER);
}
}
Duration::from_millis(250u64 << attempt.min(16))
}
fn network(error: reqwest::Error) -> Error {
Error::new(0, "NETWORK_ERROR", NETWORK_MESSAGE).with_source(error)
}
fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, Error> {
if bytes.is_empty() {
return Err(Error::schema("the response body is empty"));
}
serde_json::from_slice(bytes).map_err(|e| {
Error::schema(format!("the response does not match the contract: {e}")).with_source(e)
})
}
fn json_body<T: serde::Serialize>(value: &T) -> Result<Vec<u8>, Error> {
serde_json::to_vec(value)
.map_err(|e| Error::invalid(format!("could not encode the request: {e}")).with_source(e))
}
struct Call {
method: Method,
path: String,
query: Vec<(&'static str, String)>,
body: Option<Vec<u8>>,
idempotency_key: Option<String>,
}
impl Call {
fn new(method: Method, path: impl Into<String>) -> Self {
Call {
method,
path: path.into(),
query: Vec::new(),
body: None,
idempotency_key: None,
}
}
}
impl Client {
pub fn new(api_key: impl Into<String>, base_url: impl Into<String>) -> Result<Self, Error> {
Client::builder(api_key, base_url).build()
}
pub fn builder(api_key: impl Into<String>, base_url: impl Into<String>) -> ClientBuilder {
ClientBuilder {
api_key: api_key.into(),
base_url: base_url.into(),
timeout: DEFAULT_TIMEOUT,
max_retries: DEFAULT_MAX_RETRIES,
}
}
pub fn base_url(&self) -> &str {
&self.base_url
}
async fn execute(&self, call: Call) -> Result<Vec<u8>, Error> {
let url = format!("{}{}", self.base_url, call.path);
let mut attempt = 0u32;
loop {
let mut request = self
.http
.request(call.method.clone(), &url)
.header(ACCEPT, "application/json")
.header("X-API-Key", &self.api_key);
if !call.query.is_empty() {
request = request.query(&call.query);
}
if let Some(body) = &call.body {
request = request
.header(CONTENT_TYPE, "application/json")
.body(body.clone());
}
if let Some(key) = &call.idempotency_key {
request = request.header("Idempotency-Key", key);
}
let response = request.send().await.map_err(network)?;
let status = response.status().as_u16();
let retry_after = response
.headers()
.get(RETRY_AFTER)
.and_then(|v| v.to_str().ok())
.map(str::to_string);
let bytes = response.bytes().await.map_err(network)?;
if call.method == Method::GET
&& attempt < self.max_retries
&& (status == 429 || (500..=599).contains(&status))
{
tokio::time::sleep(retry_delay(retry_after.as_deref(), attempt)).await;
attempt += 1;
continue;
}
if !(200..=299).contains(&status) {
return Err(Error::from_response(
status,
&String::from_utf8_lossy(&bytes),
));
}
return Ok(bytes.to_vec());
}
}
async fn fetch<T: DeserializeOwned>(&self, call: Call) -> Result<T, Error> {
decode(&self.execute(call).await?)
}
pub async fn create_payment(
&self,
params: &CreatePaymentParams,
) -> Result<CreatedPayment, Error> {
if !is_plain_decimal(params.amount.as_str()) {
return Err(Error::invalid(
"amount must be a decimal such as \"150.00\"",
));
}
if params.crypto_type.is_empty() {
return Err(Error::invalid("crypto_type is required"));
}
let mut call = Call::new(Method::POST, "/api/v1/gateway/payments");
call.body = Some(json_body(params)?);
self.fetch(call).await
}
pub async fn get_payment(&self, payment_id: &str) -> Result<Payment, Error> {
let path = format!(
"/api/v1/gateway/payments/{}",
segment("payment_id", payment_id)?
);
self.fetch(Call::new(Method::GET, path)).await
}
pub async fn get_payment_status(&self, payment_id: &str) -> Result<PaymentStatus, Error> {
let path = format!(
"/api/v1/payments/{}/status",
segment("payment_id", payment_id)?
);
let raw: Value = self.fetch(Call::new(Method::GET, path)).await?;
match raw.as_str().map(PaymentStatus::parse) {
Some(status) if status.is_known() => Ok(status),
_ => Err(Error::new(
500,
"INTERNAL_ERROR",
format!("Unexpected payment status payload for {payment_id}"),
)),
}
}
pub async fn list_payments(&self, params: &ListPaymentsParams) -> Result<PaymentList, Error> {
let mut call = Call::new(Method::GET, "/api/v1/gateway/payments");
if let Some(page) = params.page {
call.query.push(("page", page.to_string()));
}
if let Some(limit) = params.limit {
call.query.push(("limit", limit.to_string()));
}
if let Some(status) = ¶ms.status {
call.query
.push(("status_filter", status.as_str().to_string()));
}
self.fetch(call).await
}
pub async fn request_payout(&self, params: &PayoutParams) -> Result<PayoutResponse, Error> {
let key = params.idempotency_key.trim();
if key.is_empty() {
return Err(Error::new(
0,
"MISSING_IDEMPOTENCY_KEY",
"bitmomo: request_payout requires idempotency_key. Mint one with new_idempotency_key() and \
reuse it across retries; a fresh key per call creates a second withdrawal.",
));
}
if !is_plain_decimal(params.amount.as_str()) {
return Err(Error::invalid(
"amount must be a decimal such as \"150.00\"",
));
}
let mut body = serde_json::Map::new();
body.insert(
"amount".into(),
Value::String(params.amount.as_str().to_string()),
);
if let Some(method) = ¶ms.settlement_method {
body.insert("settlement_method".into(), Value::String(method.clone()));
}
let mut call = Call::new(Method::POST, "/api/v1/gateway/payouts");
call.body = Some(json_body(&body)?);
call.idempotency_key = Some(key.to_string());
self.fetch(call).await
}
pub async fn get_rates(&self) -> Result<Vec<ExchangeRate>, Error> {
let raw: Value = self.fetch(Call::new(Method::GET, "/api/v1/rates")).await?;
parse_rates(&raw)
}
pub async fn get_balances(&self) -> Result<Balances, Error> {
self.fetch(Call::new(Method::GET, "/api/v1/gateway/balances"))
.await
}
pub async fn get_webhook_config(&self) -> Result<WebhookConfig, Error> {
self.fetch(Call::new(Method::GET, "/api/v1/gateway/webhooks/config"))
.await
}
pub async fn update_webhook_config(
&self,
params: &UpdateWebhookConfigParams,
) -> Result<WebhookConfig, Error> {
if params.url.is_empty() {
return Err(Error::invalid("url is required"));
}
let mut call = Call::new(Method::PUT, "/api/v1/gateway/webhooks/config");
call.body = Some(json_body(params)?);
self.fetch(call).await
}
pub async fn rotate_webhook_secret(&self) -> Result<RotatedWebhookSecret, Error> {
self.fetch(Call::new(
Method::POST,
"/api/v1/gateway/webhooks/config/rotate",
))
.await
}
pub async fn delete_webhook_config(&self) -> Result<(), Error> {
self.execute(Call::new(Method::DELETE, "/api/v1/gateway/webhooks/config"))
.await?;
Ok(())
}
pub async fn create_payment_link(
&self,
params: &CreatePaymentLinkParams,
) -> Result<PaymentLink, Error> {
if params.name.is_empty() {
return Err(Error::invalid("name is required"));
}
if params.preset_amount_ghs.is_some_and(|a| !a.is_finite()) {
return Err(Error::invalid("preset_amount_ghs must be finite"));
}
let mut call = Call::new(Method::POST, "/api/v1/gateway/payment-links");
call.body = Some(json_body(params)?);
self.fetch(call).await
}
pub async fn list_payment_links(&self) -> Result<Vec<PaymentLink>, Error> {
let links: PaymentLinks = self
.fetch(Call::new(Method::GET, "/api/v1/gateway/payment-links"))
.await?;
Ok(links.payment_links)
}
pub async fn get_payment_link(&self, link_id: &str) -> Result<PaymentLink, Error> {
let path = format!(
"/api/v1/gateway/payment-links/{}",
segment("link_id", link_id)?
);
self.fetch(Call::new(Method::GET, path)).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn retry_delays() {
assert_eq!(retry_delay(None, 0), Duration::from_millis(250));
assert_eq!(retry_delay(None, 1), Duration::from_millis(500));
assert_eq!(retry_delay(Some("2"), 0), Duration::from_secs(2));
assert_eq!(retry_delay(Some(" 1.5 "), 0), Duration::from_millis(1500));
assert_eq!(retry_delay(Some("86400"), 0), MAX_RETRY_AFTER);
assert_eq!(retry_delay(Some("soon"), 1), Duration::from_millis(500));
assert_eq!(retry_delay(Some("-1"), 0), Duration::from_millis(250));
}
#[test]
fn base_url_rules() {
for (input, origin) in [
("https://api.dev.bitmomo.app", "https://api.dev.bitmomo.app"),
(
"https://API.dev.bitmomo.app/",
"https://api.dev.bitmomo.app",
),
(
"https://api.dev.bitmomo.app:8443",
"https://api.dev.bitmomo.app:8443",
),
("http://localhost:3000", "http://localhost:3000"),
("http://127.0.0.1:3000/", "http://127.0.0.1:3000"),
("http://[::1]:3000", "http://[::1]:3000"),
] {
assert_eq!(api_origin(input).unwrap(), origin, "{input}");
}
for input in [
"",
"api.dev.bitmomo.app",
"http://api.dev.bitmomo.app",
"https://user:pass@api.dev.bitmomo.app",
"https://api.dev.bitmomo.app/api/v1",
"https://api.dev.bitmomo.app?x=1",
"https://api.dev.bitmomo.app#frag",
"ftp://api.dev.bitmomo.app",
"https://api.dev.bitmomo.app:notaport",
] {
assert!(api_origin(input).is_err(), "{input}");
}
}
#[test]
fn segments_are_percent_encoded() {
assert_eq!(segment("id", "a/b?c").unwrap(), "a%2Fb%3Fc");
assert_eq!(segment("id", "8d0b6a52-1c4e").unwrap(), "8d0b6a52-1c4e");
assert!(segment("id", "").is_err());
}
}