1use std::collections::{BTreeMap, HashMap};
5use std::sync::Arc;
6
7use adk_core::Result;
8use adk_core::principal::SubjectRef;
9use async_trait::async_trait;
10use chrono::{DateTime, Utc};
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use tokio::sync::RwLock;
14
15use super::policy::{Payee, RailRef, SpendCategory};
16use super::provider::Debit;
17use super::rail::RailSettlement;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
30#[serde(rename_all = "snake_case")]
31#[non_exhaustive]
32pub enum PaymentState {
33 Held,
35 Executing,
37 Settled,
39 Rejected,
41 Failed,
43}
44
45impl PaymentState {
46 pub fn is_spent(self) -> bool {
48 matches!(self, Self::Settled)
49 }
50
51 pub fn is_final(self) -> bool {
53 matches!(self, Self::Settled | Self::Rejected | Self::Failed)
54 }
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(tag = "reason", rename_all = "snake_case")]
69#[non_exhaustive]
70pub enum HoldReason {
71 OverPaymentLimit {
73 max_per_payment: u64,
75 requested: u64,
77 },
78 OverCategoryCap {
80 cap: u64,
82 spent: u64,
84 requested: u64,
86 },
87}
88
89impl std::fmt::Display for HoldReason {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 match self {
92 Self::OverPaymentLimit { max_per_payment, requested } => write!(
93 f,
94 "{requested} is over the mandate's limit of {max_per_payment} per payment"
95 ),
96 Self::OverCategoryCap { cap, spent, requested } => write!(
97 f,
98 "{requested} on top of {spent} spent this period is over the category cap of {cap}"
99 ),
100 }
101 }
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
106#[serde(rename_all = "camelCase")]
107pub struct OwnerDecisionRecord {
108 pub decided_by: SubjectRef,
110 pub approved: bool,
112 pub source: String,
115 #[serde(default, skip_serializing_if = "Option::is_none")]
117 pub message: Option<String>,
118 pub decided_at: DateTime<Utc>,
120}
121
122#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
124#[serde(rename_all = "camelCase")]
125pub struct PaymentRecord {
126 pub id: String,
128 pub wallet: String,
130 pub key: String,
132 pub request_digest: String,
134 pub category: SpendCategory,
136 pub payee: Payee,
138 pub amount: u64,
140 pub currency: String,
142 pub rail: RailRef,
144 pub description: String,
146 #[serde(default, skip_serializing_if = "Option::is_none")]
148 pub rail_data: Option<Value>,
149 pub state: PaymentState,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub hold: Option<HoldReason>,
154 #[serde(default, skip_serializing_if = "Option::is_none")]
156 pub agent: Option<String>,
157 #[serde(default, skip_serializing_if = "Option::is_none")]
159 pub decision: Option<OwnerDecisionRecord>,
160 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub debit: Option<Debit>,
163 #[serde(default)]
165 pub debit_outstanding: bool,
166 #[serde(default, skip_serializing_if = "Option::is_none")]
168 pub settlement: Option<RailSettlement>,
169 #[serde(default, skip_serializing_if = "Option::is_none")]
171 pub error: Option<String>,
172 pub created_at: DateTime<Utc>,
174 #[serde(default, skip_serializing_if = "Option::is_none")]
176 pub settled_at: Option<DateTime<Utc>>,
177}
178
179impl PaymentRecord {
180 pub fn owner_approved(&self) -> bool {
182 self.decision.as_ref().is_some_and(|decision| decision.approved)
183 }
184
185 pub fn use_based_proof(&self) -> Option<super::PaymentProof> {
187 let proof = self.settlement.as_ref()?.proof.clone()?;
188 serde_json::from_value(proof).ok()
189 }
190}
191
192#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct PaymentQuery {
204 pub wallet: String,
206 pub category: Option<SpendCategory>,
208 pub state: Option<PaymentState>,
210 pub from: Option<DateTime<Utc>>,
212 pub to: Option<DateTime<Utc>>,
214}
215
216impl PaymentQuery {
217 pub fn new(wallet: impl Into<String>) -> Self {
219 Self { wallet: wallet.into(), category: None, state: None, from: None, to: None }
220 }
221
222 #[must_use]
224 pub fn category(mut self, category: SpendCategory) -> Self {
225 self.category = Some(category);
226 self
227 }
228
229 #[must_use]
231 pub fn state(mut self, state: PaymentState) -> Self {
232 self.state = Some(state);
233 self
234 }
235
236 #[must_use]
238 pub fn between(mut self, from: DateTime<Utc>, to: DateTime<Utc>) -> Self {
239 self.from = Some(from);
240 self.to = Some(to);
241 self
242 }
243
244 pub fn matches(&self, record: &PaymentRecord) -> bool {
246 let at = record.settled_at.unwrap_or(record.created_at);
247 record.wallet == self.wallet
248 && self.category.is_none_or(|category| record.category == category)
249 && self.state.is_none_or(|state| record.state == state)
250 && self.from.is_none_or(|from| at >= from)
251 && self.to.is_none_or(|to| at < to)
252 }
253}
254
255#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
257#[serde(rename_all = "camelCase")]
258pub struct CategoryPause {
259 pub wallet: String,
261 pub category: SpendCategory,
263 pub reason: String,
265 pub paused_at: DateTime<Utc>,
267}
268
269#[async_trait]
276pub trait WalletStore: Send + Sync {
277 async fn insert(&self, record: PaymentRecord) -> Result<(PaymentRecord, bool)>;
284
285 async fn update(&self, record: &PaymentRecord) -> Result<()>;
291
292 async fn update_if(&self, record: &PaymentRecord, expected: PaymentState) -> Result<bool> {
321 let stored = self.get(&record.wallet, &record.id).await?.ok_or_else(|| {
322 super::error::not_found(
323 super::error::WALLET_PAYMENT_NOT_FOUND_CODE,
324 format!("wallet {} has no payment {}", record.wallet, record.id),
325 )
326 })?;
327 if stored.state != expected {
328 return Ok(false);
329 }
330 self.update(record).await?;
331 Ok(true)
332 }
333
334 async fn get(&self, wallet: &str, id: &str) -> Result<Option<PaymentRecord>>;
340
341 async fn by_key(&self, wallet: &str, key: &str) -> Result<Option<PaymentRecord>>;
347
348 async fn list(&self, query: &PaymentQuery) -> Result<Vec<PaymentRecord>>;
354
355 async fn pause(&self, pause: CategoryPause) -> Result<()>;
361
362 async fn resume(&self, wallet: &str, category: SpendCategory) -> Result<Option<CategoryPause>>;
368
369 async fn pauses(&self, wallet: &str) -> Result<Vec<CategoryPause>>;
375}
376
377#[derive(Debug, Default)]
378struct StoreState {
379 payments: Vec<PaymentRecord>,
380 by_id: HashMap<(String, String), usize>,
381 by_key: HashMap<(String, String), usize>,
382 pauses: BTreeMap<(String, SpendCategory), CategoryPause>,
383}
384
385#[derive(Debug, Clone, Default)]
396pub struct InMemoryWalletStore {
397 state: Arc<RwLock<StoreState>>,
398}
399
400impl InMemoryWalletStore {
401 pub fn new() -> Self {
403 Self::default()
404 }
405}
406
407#[async_trait]
408impl WalletStore for InMemoryWalletStore {
409 async fn insert(&self, record: PaymentRecord) -> Result<(PaymentRecord, bool)> {
410 let mut state = self.state.write().await;
411 let key = (record.wallet.clone(), record.key.clone());
412 if let Some(index) = state.by_key.get(&key) {
413 return Ok((state.payments[*index].clone(), false));
414 }
415 let index = state.payments.len();
416 state.by_id.insert((record.wallet.clone(), record.id.clone()), index);
417 state.by_key.insert(key, index);
418 state.payments.push(record.clone());
419 Ok((record, true))
420 }
421
422 async fn update(&self, record: &PaymentRecord) -> Result<()> {
423 let mut state = self.state.write().await;
424 let index =
425 *state.by_id.get(&(record.wallet.clone(), record.id.clone())).ok_or_else(|| {
426 super::error::not_found(
427 super::error::WALLET_PAYMENT_NOT_FOUND_CODE,
428 format!("wallet {} has no payment {}", record.wallet, record.id),
429 )
430 })?;
431 state.payments[index] = record.clone();
432 Ok(())
433 }
434
435 async fn update_if(&self, record: &PaymentRecord, expected: PaymentState) -> Result<bool> {
436 let mut state = self.state.write().await;
437 let index =
438 *state.by_id.get(&(record.wallet.clone(), record.id.clone())).ok_or_else(|| {
439 super::error::not_found(
440 super::error::WALLET_PAYMENT_NOT_FOUND_CODE,
441 format!("wallet {} has no payment {}", record.wallet, record.id),
442 )
443 })?;
444 if state.payments[index].state != expected {
445 return Ok(false);
446 }
447 state.payments[index] = record.clone();
448 Ok(true)
449 }
450
451 async fn get(&self, wallet: &str, id: &str) -> Result<Option<PaymentRecord>> {
452 let state = self.state.read().await;
453 Ok(state
454 .by_id
455 .get(&(wallet.to_string(), id.to_string()))
456 .map(|index| state.payments[*index].clone()))
457 }
458
459 async fn by_key(&self, wallet: &str, key: &str) -> Result<Option<PaymentRecord>> {
460 let state = self.state.read().await;
461 Ok(state
462 .by_key
463 .get(&(wallet.to_string(), key.to_string()))
464 .map(|index| state.payments[*index].clone()))
465 }
466
467 async fn list(&self, query: &PaymentQuery) -> Result<Vec<PaymentRecord>> {
468 let state = self.state.read().await;
469 Ok(state.payments.iter().filter(|record| query.matches(record)).cloned().collect())
470 }
471
472 async fn pause(&self, pause: CategoryPause) -> Result<()> {
473 let mut state = self.state.write().await;
474 state.pauses.entry((pause.wallet.clone(), pause.category)).or_insert(pause);
475 Ok(())
476 }
477
478 async fn resume(&self, wallet: &str, category: SpendCategory) -> Result<Option<CategoryPause>> {
479 Ok(self.state.write().await.pauses.remove(&(wallet.to_string(), category)))
480 }
481
482 async fn pauses(&self, wallet: &str) -> Result<Vec<CategoryPause>> {
483 let state = self.state.read().await;
484 Ok(state
485 .pauses
486 .iter()
487 .filter(|((owner, _), _)| owner == wallet)
488 .map(|(_, pause)| pause.clone())
489 .collect())
490 }
491}