1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30#[non_exhaustive]
31pub enum Funding {
32 StoredValue,
34 PrepaidCard,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(rename_all = "camelCase")]
44pub struct DebitRequest {
45 pub reference: String,
47 pub payee: Payee,
49 pub amount: u64,
51 pub currency: String,
53 pub description: String,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "camelCase")]
60pub struct Debit {
61 pub id: String,
63 pub reference: String,
65 pub amount: u64,
67 pub currency: String,
69 pub at: DateTime<Utc>,
71 #[serde(default, skip_serializing_if = "Option::is_none")]
74 pub funding_token: Option<String>,
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
79#[serde(rename_all = "snake_case")]
80#[non_exhaustive]
81pub enum StatementKind {
82 Debit,
84 Reversal,
86 Funding,
88}
89
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92#[serde(rename_all = "camelCase")]
93pub struct StatementEntry {
94 pub id: String,
96 #[serde(default, skip_serializing_if = "Option::is_none")]
98 pub reference: Option<String>,
99 pub kind: StatementKind,
101 pub amount: u64,
103 pub currency: String,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub payee: Option<String>,
108 pub at: DateTime<Utc>,
110}
111
112#[async_trait]
145pub trait WalletProvider: Send + Sync {
146 fn name(&self) -> &str;
148
149 fn funding(&self) -> Funding;
151
152 fn currency(&self) -> &str;
154
155 async fn balance(&self) -> Result<u64>;
161
162 async fn debit(&self, request: &DebitRequest) -> Result<Debit>;
172
173 async fn void(&self, debit: &Debit) -> Result<()>;
181
182 async fn statement(
188 &self,
189 from: DateTime<Utc>,
190 to: DateTime<Utc>,
191 ) -> Result<Vec<StatementEntry>>;
192}
193
194#[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#[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 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 #[must_use]
363 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
364 self.clock = clock;
365 self
366 }
367
368 pub fn fund(&self, amount: u64) {
370 let at = self.clock.now();
371 locked(&self.book).fund(amount, at);
372 }
373
374 pub fn push_statement_entry(&self, entry: StatementEntry) {
377 locked(&self.book).entries.push(entry);
378 }
379
380 pub fn available(&self) -> u64 {
382 locked(&self.book).balance
383 }
384
385 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
431#[serde(rename_all = "camelCase")]
432pub struct PrepaidCard {
433 pub card_id: String,
435 pub last4: String,
437 pub currency: String,
439 pub remaining: u64,
441 pub frozen: bool,
443}
444
445#[async_trait]
451pub trait CardIssuer: Send + Sync {
452 fn name(&self) -> &str;
454
455 async fn card(&self) -> Result<PrepaidCard>;
461
462 async fn charge(&self, request: &DebitRequest) -> Result<Debit>;
469
470 async fn reverse(&self, debit: &Debit) -> Result<()>;
476
477 async fn transactions(
483 &self,
484 from: DateTime<Utc>,
485 to: DateTime<Utc>,
486 ) -> Result<Vec<StatementEntry>>;
487}
488
489pub struct PrepaidCardProvider {
506 issuer: Arc<dyn CardIssuer>,
507 currency: String,
508}
509
510impl PrepaidCardProvider {
511 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#[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 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 #[must_use]
607 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
608 self.clock = clock;
609 self
610 }
611
612 pub fn load(&self, amount: u64) {
614 let at = self.clock.now();
615 locked(&self.book).fund(amount, at);
616 }
617
618 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}