Skip to main content

adk_payments/wallet/
provider.rs

1//! Funding providers: where the owner's money sits (spec 3.5 §7.14).
2//!
3//! The owner funds the wallet with a payment provider (stored value) or a prepaid virtual
4//! card from an issuing adapter; the site holds no custody of its own. Neither trait has a
5//! method to open an account, add a payment method, raise a limit or top up: those are the
6//! owner's acts with the provider, outside the site (A-I16).
7
8use std::collections::HashMap;
9use std::sync::{Arc, Mutex};
10
11use adk_core::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
12use async_trait::async_trait;
13use chrono::{DateTime, Utc};
14use serde::{Deserialize, Serialize};
15
16use super::error::{WALLET_CURRENCY_MISMATCH_CODE, WALLET_INSUFFICIENT_FUNDS_CODE, conflict};
17use super::policy::Payee;
18
19/// How the owner funds the wallet (spec 3.5 §7.14).
20///
21/// # Example
22///
23/// ```
24/// use adk_payments::wallet::Funding;
25///
26/// assert_eq!(serde_json::to_value(Funding::PrepaidCard).unwrap(), "prepaid_card");
27/// ```
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30#[non_exhaustive]
31pub enum Funding {
32    /// Stored value held by a payment provider on the owner's account.
33    StoredValue,
34    /// A prepaid virtual card issued to the owner through an issuing adapter.
35    PrepaidCard,
36}
37
38/// A request to move money out of the owner's funds for one payment.
39///
40/// `reference` is the wallet's payment id: a provider answers a repeated reference with
41/// the debit it already made, so a retried payment is debited once.
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(rename_all = "camelCase")]
44pub struct DebitRequest {
45    /// The wallet's payment id.
46    pub reference: String,
47    /// Who the money is for.
48    pub payee: Payee,
49    /// Amount in minor units of `currency`.
50    pub amount: u64,
51    /// ISO 4217 currency code.
52    pub currency: String,
53    /// What the payment is for.
54    pub description: String,
55}
56
57/// Money a provider moved out of the owner's funds for one payment.
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "camelCase")]
60pub struct Debit {
61    /// The provider's id for the debit.
62    pub id: String,
63    /// The wallet's payment id it was made for.
64    pub reference: String,
65    /// Amount in minor units.
66    pub amount: u64,
67    /// ISO 4217 currency code.
68    pub currency: String,
69    /// When the provider made it.
70    pub at: DateTime<Utc>,
71    /// A token a rail presents to the payee for these funds, such as a virtual card's id;
72    /// never a card number or a secret.
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub funding_token: Option<String>,
75}
76
77/// What a statement line records.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
79#[serde(rename_all = "snake_case")]
80#[non_exhaustive]
81pub enum StatementKind {
82    /// Money left the owner's funds.
83    Debit,
84    /// A debit was returned.
85    Reversal,
86    /// The owner added funds.
87    Funding,
88}
89
90/// One line of a provider's statement, as reconciliation reads it.
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92#[serde(rename_all = "camelCase")]
93pub struct StatementEntry {
94    /// The provider's id for the line.
95    pub id: String,
96    /// The wallet payment id the line belongs to, when the provider recorded one.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub reference: Option<String>,
99    /// What the line records.
100    pub kind: StatementKind,
101    /// Amount in minor units.
102    pub amount: u64,
103    /// ISO 4217 currency code.
104    pub currency: String,
105    /// The payee, when the provider knows it.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub payee: Option<String>,
108    /// When it happened.
109    pub at: DateTime<Utc>,
110}
111
112/// Where the owner's money sits (spec 3.5 §7.14).
113///
114/// The wallet debits it for every payment a rail settles with the wallet's funds, voids
115/// the debit when the payment does not happen, and reconciles against its statement. It
116/// has no method to open an account, add a payment method, raise a limit or add funds:
117/// the owner does those with the provider.
118///
119/// [`conformance::wallet_provider_conformance`](super::conformance::wallet_provider_conformance)
120/// checks an implementation.
121///
122/// # Example
123///
124/// ```
125/// use adk_payments::wallet::{DebitRequest, InMemoryWalletProvider, Payee, WalletProvider};
126///
127/// # #[tokio::main(flavor = "current_thread")]
128/// # async fn main() -> adk_core::Result<()> {
129/// let provider = InMemoryWalletProvider::stored_value("treasury", "USD", 10_000);
130/// let debit = provider
131///     .debit(&DebitRequest {
132///         reference: "pay-1".into(),
133///         payee: Payee::new("registrar"),
134///         amount: 1_500,
135///         currency: "USD".into(),
136///         description: "domain renewal".into(),
137///     })
138///     .await?;
139/// assert_eq!(debit.amount, 1_500);
140/// assert_eq!(provider.balance().await?, 8_500);
141/// # Ok(())
142/// # }
143/// ```
144#[async_trait]
145pub trait WalletProvider: Send + Sync {
146    /// The provider's name, as reports and audit records cite it.
147    fn name(&self) -> &str;
148
149    /// How the owner funds the wallet through this provider.
150    fn funding(&self) -> Funding;
151
152    /// The ISO 4217 currency the funds are held in.
153    fn currency(&self) -> &str;
154
155    /// The funds available, in minor units.
156    ///
157    /// # Errors
158    ///
159    /// Returns the provider's error when it cannot answer.
160    async fn balance(&self) -> Result<u64>;
161
162    /// Moves `request.amount` out of the owner's funds for one payment.
163    ///
164    /// A repeated `reference` with the same amount returns the debit already made.
165    ///
166    /// # Errors
167    ///
168    /// Returns `wallet.insufficient_funds` when the funds do not cover the amount,
169    /// `wallet.currency_mismatch` for another currency, `wallet.key_reused` for a repeated
170    /// reference with another amount, or the provider's error.
171    async fn debit(&self, request: &DebitRequest) -> Result<Debit>;
172
173    /// Returns a debit's money because its payment did not happen. Voiding a voided debit
174    /// does nothing.
175    ///
176    /// # Errors
177    ///
178    /// Returns the provider's error; the wallet then records the payment as failed with the
179    /// debit outstanding, for reconciliation.
180    async fn void(&self, debit: &Debit) -> Result<()>;
181
182    /// The provider's statement lines in `[from, to)`.
183    ///
184    /// # Errors
185    ///
186    /// Returns the provider's error when it cannot answer.
187    async fn statement(
188        &self,
189        from: DateTime<Utc>,
190        to: DateTime<Utc>,
191    ) -> Result<Vec<StatementEntry>>;
192}
193
194/// The state of an in-memory book of funds, shared by [`InMemoryWalletProvider`] and
195/// [`InMemoryCardIssuer`].
196#[derive(Debug)]
197struct Book {
198    name: String,
199    currency: String,
200    balance: u64,
201    debits: HashMap<String, (Debit, bool)>,
202    entries: Vec<StatementEntry>,
203    next: u64,
204}
205
206impl Book {
207    fn new(name: &str, currency: &str, balance: u64) -> Self {
208        Self {
209            name: name.to_string(),
210            currency: currency.to_ascii_uppercase(),
211            balance,
212            debits: HashMap::new(),
213            entries: Vec::new(),
214            next: 0,
215        }
216    }
217
218    fn next_id(&mut self, prefix: &str) -> String {
219        self.next += 1;
220        format!("{}-{prefix}-{}", self.name, self.next)
221    }
222
223    fn debit(
224        &mut self,
225        request: &DebitRequest,
226        at: DateTime<Utc>,
227        funding_token: Option<String>,
228    ) -> Result<Debit> {
229        if !request.currency.eq_ignore_ascii_case(&self.currency) {
230            return Err(conflict(
231                WALLET_CURRENCY_MISMATCH_CODE,
232                format!(
233                    "{} holds {}, so it cannot pay {} {}",
234                    self.name, self.currency, request.amount, request.currency
235                ),
236            ));
237        }
238        if let Some((existing, _)) = self.debits.get(&request.reference) {
239            if existing.amount != request.amount {
240                return Err(conflict(
241                    super::error::WALLET_KEY_REUSED_CODE,
242                    format!(
243                        "payment {} was already debited for {}, not {}",
244                        request.reference, existing.amount, request.amount
245                    ),
246                ));
247            }
248            return Ok(existing.clone());
249        }
250        if self.balance < request.amount {
251            return Err(AdkError::new(
252                ErrorComponent::Guardrail,
253                ErrorCategory::ResourceExhausted,
254                WALLET_INSUFFICIENT_FUNDS_CODE,
255                format!(
256                    "{} has {} {} available and cannot cover {}; the owner adds funds with the provider",
257                    self.name, self.balance, self.currency, request.amount
258                ),
259            ));
260        }
261        self.balance -= request.amount;
262        let debit = Debit {
263            id: self.next_id("debit"),
264            reference: request.reference.clone(),
265            amount: request.amount,
266            currency: self.currency.clone(),
267            at,
268            funding_token,
269        };
270        self.entries.push(StatementEntry {
271            id: debit.id.clone(),
272            reference: Some(request.reference.clone()),
273            kind: StatementKind::Debit,
274            amount: request.amount,
275            currency: self.currency.clone(),
276            payee: Some(request.payee.id.clone()),
277            at,
278        });
279        self.debits.insert(request.reference.clone(), (debit.clone(), false));
280        Ok(debit)
281    }
282
283    fn void(&mut self, debit: &Debit, at: DateTime<Utc>) {
284        let Some((recorded, voided)) = self.debits.get_mut(&debit.reference) else {
285            return;
286        };
287        if *voided {
288            return;
289        }
290        *voided = true;
291        let amount = recorded.amount;
292        self.balance = self.balance.saturating_add(amount);
293        let id = self.next_id("reversal");
294        self.entries.push(StatementEntry {
295            id,
296            reference: Some(debit.reference.clone()),
297            kind: StatementKind::Reversal,
298            amount,
299            currency: self.currency.clone(),
300            payee: None,
301            at,
302        });
303    }
304
305    fn fund(&mut self, amount: u64, at: DateTime<Utc>) {
306        self.balance = self.balance.saturating_add(amount);
307        let id = self.next_id("funding");
308        self.entries.push(StatementEntry {
309            id,
310            reference: None,
311            kind: StatementKind::Funding,
312            amount,
313            currency: self.currency.clone(),
314            payee: None,
315            at,
316        });
317    }
318
319    fn statement(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Vec<StatementEntry> {
320        self.entries.iter().filter(|entry| entry.at >= from && entry.at < to).cloned().collect()
321    }
322}
323
324fn locked<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
325    mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
326}
327
328/// A stored-value [`WalletProvider`] kept in memory, so tests are hermetic.
329///
330/// [`fund`](Self::fund) stands for the owner adding money with the provider; it is not
331/// part of [`WalletProvider`], so nothing the site holds can call it.
332///
333/// # Example
334///
335/// ```
336/// use adk_payments::wallet::{Funding, InMemoryWalletProvider, WalletProvider};
337///
338/// let provider = InMemoryWalletProvider::stored_value("treasury", "USD", 0);
339/// provider.fund(5_000);
340/// assert_eq!(provider.funding(), Funding::StoredValue);
341/// ```
342#[derive(Debug, Clone)]
343pub struct InMemoryWalletProvider {
344    name: String,
345    currency: String,
346    book: Arc<Mutex<Book>>,
347    clock: Arc<dyn Clock>,
348}
349
350impl InMemoryWalletProvider {
351    /// A stored-value provider `name` holding `balance` minor units of `currency`.
352    pub fn stored_value(name: &str, currency: &str, balance: u64) -> Self {
353        Self {
354            name: name.to_string(),
355            currency: currency.to_ascii_uppercase(),
356            book: Arc::new(Mutex::new(Book::new(name, currency, balance))),
357            clock: Arc::new(SystemClock),
358        }
359    }
360
361    /// Sets the clock that stamps debits and statement lines.
362    #[must_use]
363    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
364        self.clock = clock;
365        self
366    }
367
368    /// Adds `amount` to the funds: the owner topping up with the provider.
369    pub fn fund(&self, amount: u64) {
370        let at = self.clock.now();
371        locked(&self.book).fund(amount, at);
372    }
373
374    /// Adds a statement line the wallet did not make, such as a charge the owner made with
375    /// the provider directly; reconciliation reports it.
376    pub fn push_statement_entry(&self, entry: StatementEntry) {
377        locked(&self.book).entries.push(entry);
378    }
379
380    /// The funds available now, for tests.
381    pub fn available(&self) -> u64 {
382        locked(&self.book).balance
383    }
384
385    /// Every statement line so far, for tests.
386    pub fn entries(&self) -> Vec<StatementEntry> {
387        locked(&self.book).entries.clone()
388    }
389}
390
391#[async_trait]
392impl WalletProvider for InMemoryWalletProvider {
393    fn name(&self) -> &str {
394        &self.name
395    }
396
397    fn funding(&self) -> Funding {
398        Funding::StoredValue
399    }
400
401    fn currency(&self) -> &str {
402        &self.currency
403    }
404
405    async fn balance(&self) -> Result<u64> {
406        Ok(locked(&self.book).balance)
407    }
408
409    async fn debit(&self, request: &DebitRequest) -> Result<Debit> {
410        let at = self.clock.now();
411        locked(&self.book).debit(request, at, None)
412    }
413
414    async fn void(&self, debit: &Debit) -> Result<()> {
415        let at = self.clock.now();
416        locked(&self.book).void(debit, at);
417        Ok(())
418    }
419
420    async fn statement(
421        &self,
422        from: DateTime<Utc>,
423        to: DateTime<Utc>,
424    ) -> Result<Vec<StatementEntry>> {
425        Ok(locked(&self.book).statement(from, to))
426    }
427}
428
429/// A prepaid virtual card as its issuer reports it.
430#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
431#[serde(rename_all = "camelCase")]
432pub struct PrepaidCard {
433    /// The issuer's id for the card: a token, never the card number.
434    pub card_id: String,
435    /// The card number's last four digits, for display.
436    pub last4: String,
437    /// ISO 4217 currency code.
438    pub currency: String,
439    /// What the card can still spend, in minor units.
440    pub remaining: u64,
441    /// Whether the owner froze the card.
442    pub frozen: bool,
443}
444
445/// An issuing platform holding the owner's prepaid virtual card (spec 3.5 §7.14).
446///
447/// The owner issues and loads the card with the platform; the adapter only reads it,
448/// charges it and reverses charges. [`PrepaidCardProvider`] turns it into a
449/// [`WalletProvider`].
450#[async_trait]
451pub trait CardIssuer: Send + Sync {
452    /// The issuing platform's name.
453    fn name(&self) -> &str;
454
455    /// The card.
456    ///
457    /// # Errors
458    ///
459    /// Returns the platform's error when it cannot answer.
460    async fn card(&self) -> Result<PrepaidCard>;
461
462    /// Charges the card for one payment; a repeated `reference` returns the charge made.
463    ///
464    /// # Errors
465    ///
466    /// Returns `wallet.insufficient_funds` when the card cannot cover the amount, or the
467    /// platform's error.
468    async fn charge(&self, request: &DebitRequest) -> Result<Debit>;
469
470    /// Reverses a charge whose payment did not happen.
471    ///
472    /// # Errors
473    ///
474    /// Returns the platform's error.
475    async fn reverse(&self, debit: &Debit) -> Result<()>;
476
477    /// The card's transactions in `[from, to)`.
478    ///
479    /// # Errors
480    ///
481    /// Returns the platform's error.
482    async fn transactions(
483        &self,
484        from: DateTime<Utc>,
485        to: DateTime<Utc>,
486    ) -> Result<Vec<StatementEntry>>;
487}
488
489/// A [`WalletProvider`] over a prepaid virtual card from a [`CardIssuer`]
490/// (spec 3.5 §7.14).
491///
492/// A frozen card pays nothing. Each debit carries the card's id as its funding token, so a
493/// rail can present the card without the agent ever seeing its number.
494///
495/// # Example
496///
497/// ```
498/// use std::sync::Arc;
499/// use adk_payments::wallet::{Funding, InMemoryCardIssuer, PrepaidCardProvider, WalletProvider};
500///
501/// let issuer = Arc::new(InMemoryCardIssuer::new("issuer", "USD", 20_000));
502/// let provider = PrepaidCardProvider::new(issuer, "USD");
503/// assert_eq!(provider.funding(), Funding::PrepaidCard);
504/// ```
505pub struct PrepaidCardProvider {
506    issuer: Arc<dyn CardIssuer>,
507    currency: String,
508}
509
510impl PrepaidCardProvider {
511    /// A provider over `issuer`'s card, which is loaded in `currency`. A debit checks the
512    /// card's own currency too.
513    pub fn new(issuer: Arc<dyn CardIssuer>, currency: &str) -> Self {
514        Self { issuer, currency: currency.to_ascii_uppercase() }
515    }
516}
517
518impl std::fmt::Debug for PrepaidCardProvider {
519    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
520        f.debug_struct("PrepaidCardProvider").field("issuer", &self.issuer.name()).finish()
521    }
522}
523
524#[async_trait]
525impl WalletProvider for PrepaidCardProvider {
526    fn name(&self) -> &str {
527        self.issuer.name()
528    }
529
530    fn funding(&self) -> Funding {
531        Funding::PrepaidCard
532    }
533
534    fn currency(&self) -> &str {
535        &self.currency
536    }
537
538    async fn balance(&self) -> Result<u64> {
539        let card = self.issuer.card().await?;
540        Ok(if card.frozen { 0 } else { card.remaining })
541    }
542
543    async fn debit(&self, request: &DebitRequest) -> Result<Debit> {
544        let card = self.issuer.card().await?;
545        if card.frozen {
546            return Err(AdkError::new(
547                ErrorComponent::Guardrail,
548                ErrorCategory::Forbidden,
549                WALLET_INSUFFICIENT_FUNDS_CODE,
550                format!("card ending {} is frozen by its owner", card.last4),
551            ));
552        }
553        if !card.currency.eq_ignore_ascii_case(&request.currency) {
554            return Err(conflict(
555                WALLET_CURRENCY_MISMATCH_CODE,
556                format!(
557                    "card ending {} is in {}, not {}",
558                    card.last4, card.currency, request.currency
559                ),
560            ));
561        }
562        let mut debit = self.issuer.charge(request).await?;
563        debit.funding_token.get_or_insert(card.card_id);
564        Ok(debit)
565    }
566
567    async fn void(&self, debit: &Debit) -> Result<()> {
568        self.issuer.reverse(debit).await
569    }
570
571    async fn statement(
572        &self,
573        from: DateTime<Utc>,
574        to: DateTime<Utc>,
575    ) -> Result<Vec<StatementEntry>> {
576        self.issuer.transactions(from, to).await
577    }
578}
579
580/// A [`CardIssuer`] kept in memory, so tests are hermetic.
581///
582/// [`load`](Self::load) and [`freeze`](Self::freeze) stand for the owner's acts with the
583/// issuing platform; neither is part of [`CardIssuer`].
584#[derive(Debug, Clone)]
585pub struct InMemoryCardIssuer {
586    name: String,
587    book: Arc<Mutex<Book>>,
588    card_id: String,
589    frozen: Arc<Mutex<bool>>,
590    clock: Arc<dyn Clock>,
591}
592
593impl InMemoryCardIssuer {
594    /// An issuer `name` holding one card loaded with `remaining` minor units of `currency`.
595    pub fn new(name: &str, currency: &str, remaining: u64) -> Self {
596        Self {
597            name: name.to_string(),
598            book: Arc::new(Mutex::new(Book::new(name, currency, remaining))),
599            card_id: format!("{name}-card-1"),
600            frozen: Arc::new(Mutex::new(false)),
601            clock: Arc::new(SystemClock),
602        }
603    }
604
605    /// Sets the clock that stamps charges.
606    #[must_use]
607    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
608        self.clock = clock;
609        self
610    }
611
612    /// Loads `amount` onto the card: the owner's act with the issuing platform.
613    pub fn load(&self, amount: u64) {
614        let at = self.clock.now();
615        locked(&self.book).fund(amount, at);
616    }
617
618    /// Freezes or unfreezes the card: the owner's act with the issuing platform.
619    pub fn freeze(&self, frozen: bool) {
620        *locked(&self.frozen) = frozen;
621    }
622}
623
624#[async_trait]
625impl CardIssuer for InMemoryCardIssuer {
626    fn name(&self) -> &str {
627        &self.name
628    }
629
630    async fn card(&self) -> Result<PrepaidCard> {
631        let book = locked(&self.book);
632        Ok(PrepaidCard {
633            card_id: self.card_id.clone(),
634            last4: "4242".to_string(),
635            currency: book.currency.clone(),
636            remaining: book.balance,
637            frozen: *locked(&self.frozen),
638        })
639    }
640
641    async fn charge(&self, request: &DebitRequest) -> Result<Debit> {
642        let at = self.clock.now();
643        locked(&self.book).debit(request, at, Some(self.card_id.clone()))
644    }
645
646    async fn reverse(&self, debit: &Debit) -> Result<()> {
647        let at = self.clock.now();
648        locked(&self.book).void(debit, at);
649        Ok(())
650    }
651
652    async fn transactions(
653        &self,
654        from: DateTime<Utc>,
655        to: DateTime<Utc>,
656    ) -> Result<Vec<StatementEntry>> {
657        Ok(locked(&self.book).statement(from, to))
658    }
659}