1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! Credit service for balance, spending, and hold operations
//!
//! Provides a professional-grade credit system with:
//! - Balance queries with held amount tracking
//! - Direct spend operations with idempotency
//! - Hold/capture pattern for two-phase commits
//! - Full audit trail for all transactions
use chrono::Duration;
use std::sync::Arc;
use uuid::Uuid;
use crate::errors::AppError;
use crate::repositories::{
CreditHoldEntity, CreditHoldRepository, CreditRepository, CreditTransactionEntity,
};
// Re-export types for external consumers
pub use super::credit_types::{
AdjustResult, CreditBalance, CreditHistory, CreditHistoryItem, HoldResult, SpendResult,
};
/// Default hold TTL (15 minutes)
const DEFAULT_HOLD_TTL_MINUTES: i64 = 15;
/// Credit service for balance, spending, and hold operations
pub struct CreditService {
credit_repo: Arc<dyn CreditRepository>,
hold_repo: Arc<dyn CreditHoldRepository>,
/// Maximum spend per transaction in lamports (0 = no limit)
max_spend_per_transaction_lamports: u64,
}
impl CreditService {
/// Create a new credit service
pub fn new(
credit_repo: Arc<dyn CreditRepository>,
hold_repo: Arc<dyn CreditHoldRepository>,
) -> Self {
Self::with_config(credit_repo, hold_repo, 0)
}
/// Create a new credit service with spend limit configuration
pub fn with_config(
credit_repo: Arc<dyn CreditRepository>,
hold_repo: Arc<dyn CreditHoldRepository>,
max_spend_per_transaction_lamports: u64,
) -> Self {
Self {
credit_repo,
hold_repo,
max_spend_per_transaction_lamports,
}
}
/// Get user's credit balance for a specific currency
pub async fn get_balance(
&self,
user_id: Uuid,
currency: &str,
) -> Result<CreditBalance, AppError> {
let balance_entity = self
.credit_repo
.get_or_create_balance(user_id, currency)
.await?;
Ok(CreditBalance::from_entity(balance_entity))
}
/// Get user's credit balance in lamports (simple lookup)
pub async fn get_balance_lamports(
&self,
user_id: Uuid,
currency: &str,
) -> Result<i64, AppError> {
self.credit_repo.get_balance(user_id, currency).await
}
/// Get all balances for a user (SOL + USD)
pub async fn get_all_balances(&self, user_id: Uuid) -> Result<Vec<CreditBalance>, AppError> {
// L-01: Fetch both SOL and USD balances
let mut balances = Vec::new();
for currency in &["SOL", "USD"] {
let entity = self
.credit_repo
.get_or_create_balance(user_id, currency)
.await?;
if entity.balance != 0 || entity.held_balance != 0 {
balances.push(CreditBalance::from_entity(entity));
}
}
// Always include SOL even if zero
if balances.is_empty() {
let sol = self
.credit_repo
.get_or_create_balance(user_id, "SOL")
.await?;
balances.push(CreditBalance::from_entity(sol));
}
Ok(balances)
}
/// Get transaction history for a user
pub async fn get_history(
&self,
user_id: Uuid,
currency: Option<&str>,
tx_type: Option<&str>,
limit: u32,
offset: u32,
) -> Result<CreditHistory, AppError> {
let (transactions, total) = tokio::join!(
self.credit_repo
.get_transactions(user_id, currency, tx_type, limit, offset),
self.credit_repo
.count_transactions(user_id, currency, tx_type)
);
let items: Vec<CreditHistoryItem> = transactions?
.into_iter()
.map(CreditHistoryItem::from)
.collect();
Ok(CreditHistory {
items,
total: total?,
limit,
offset,
})
}
/// Get user credit statistics (usage analytics)
pub async fn get_user_stats(
&self,
user_id: Uuid,
currency: &str,
) -> Result<crate::repositories::UserCreditStats, AppError> {
self.credit_repo.get_user_stats(user_id, currency).await
}
/// Check if user has sufficient available balance for a spend operation
///
/// Returns true if available balance (total - held) >= amount
pub async fn has_sufficient_balance(
&self,
user_id: Uuid,
currency: &str,
amount: i64,
) -> Result<bool, AppError> {
let balance = self
.credit_repo
.get_or_create_balance(user_id, currency)
.await?;
Ok(balance.available() >= amount)
}
// =========================================================================
// SPEND OPERATIONS
// =========================================================================
/// Spend credits immediately (direct debit)
///
/// Use this for simple, idempotent spend operations.
/// For two-phase commits, use hold() + capture().
///
/// # Arguments
/// * `user_id` - User to debit
/// * `amount` - Amount in lamports (must be positive)
/// * `currency` - Currency code (e.g., "SOL")
/// * `idempotency_key` - Unique key to prevent duplicate charges
/// * `reference_type` - What this spend is for (e.g., "order")
/// * `reference_id` - ID of the related entity
/// * `metadata` - Optional additional context
#[allow(clippy::too_many_arguments)]
pub async fn spend(
&self,
user_id: Uuid,
amount: i64,
currency: &str,
idempotency_key: String,
reference_type: &str,
reference_id: Uuid,
metadata: Option<serde_json::Value>,
) -> Result<SpendResult, AppError> {
if amount <= 0 {
return Err(AppError::Validation("Amount must be positive".into()));
}
// Check max spend limit (0 = no limit)
if self.max_spend_per_transaction_lamports > 0
&& amount > self.max_spend_per_transaction_lamports as i64
{
tracing::warn!(
user_id = %user_id,
amount = amount,
max_allowed = self.max_spend_per_transaction_lamports,
"Spend amount exceeds maximum per-transaction limit"
);
return Err(AppError::Validation(format!(
"Maximum spend per transaction is {} lamports",
self.max_spend_per_transaction_lamports
)));
}
// H-01: Idempotency — check if this idempotency_key was already used.
// The DB has a UNIQUE(user_id, idempotency_key) index, but checking
// first gives a clean idempotent response instead of an internal error.
if let Some(existing) = self
.credit_repo
.find_transaction_by_idempotency_key(user_id, &idempotency_key)
.await?
{
tracing::info!(
user_id = %user_id,
idempotency_key = %idempotency_key,
transaction_id = %existing.id,
"Spend already processed (idempotent return)"
);
let balance = self.credit_repo.get_balance(user_id, currency).await?;
return Ok(SpendResult {
transaction_id: existing.id,
new_balance_lamports: balance,
amount_lamports: existing.amount.abs(),
currency: currency.to_string(),
});
}
let tx = CreditTransactionEntity::new_spend_with_reference(
user_id,
amount,
currency,
idempotency_key,
reference_type,
reference_id,
metadata,
);
let tx_id = tx.id;
let new_balance = self
.credit_repo
.deduct_credit(user_id, amount, currency, tx)
.await?;
Ok(SpendResult {
transaction_id: tx_id,
new_balance_lamports: new_balance,
amount_lamports: amount,
currency: currency.to_string(),
})
}
// =========================================================================
// HOLD/CAPTURE OPERATIONS (Two-Phase Commit)
// =========================================================================
/// Create a hold to reserve credits
///
/// Holds reserve credits for a future capture. If the operation fails,
/// call release() to return the credits. Holds auto-expire after TTL.
///
/// # Arguments
/// * `user_id` - User to hold credits from
/// * `amount` - Amount in lamports (must be positive)
/// * `currency` - Currency code (e.g., "SOL")
/// * `idempotency_key` - Unique key (returns existing hold if duplicate)
/// * `ttl_minutes` - Hold duration (None = default 15 minutes)
/// * `reference_type` - What this hold is for
/// * `reference_id` - ID of related entity
/// * `metadata` - Optional context
#[allow(clippy::too_many_arguments)]
pub async fn hold(
&self,
user_id: Uuid,
amount: i64,
currency: &str,
idempotency_key: String,
ttl_minutes: Option<i64>,
reference_type: Option<&str>,
reference_id: Option<Uuid>,
metadata: Option<serde_json::Value>,
) -> Result<HoldResult, AppError> {
if amount <= 0 {
return Err(AppError::Validation("Amount must be positive".into()));
}
// Check max spend limit (holds are reservations for spending)
if self.max_spend_per_transaction_lamports > 0
&& amount > self.max_spend_per_transaction_lamports as i64
{
tracing::warn!(
user_id = %user_id,
amount = amount,
max_allowed = self.max_spend_per_transaction_lamports,
"Hold amount exceeds maximum per-transaction limit"
);
return Err(AppError::Validation(format!(
"Maximum hold per transaction is {} lamports",
self.max_spend_per_transaction_lamports
)));
}
// Fast-path balance check — rejects most insufficient-balance requests
// without touching the hold table. The authoritative atomic check is in
// the repository's create_hold transaction (SRV-01).
let balance = self
.credit_repo
.get_or_create_balance(user_id, currency)
.await?;
if balance.available() < amount {
return Err(AppError::Validation(format!(
"Insufficient available balance: have {}, need {}",
balance.available(),
amount
)));
}
let ttl = Duration::minutes(ttl_minutes.unwrap_or(DEFAULT_HOLD_TTL_MINUTES));
let hold = CreditHoldEntity::new(
user_id,
amount,
currency,
idempotency_key,
ttl,
reference_type,
reference_id,
metadata,
);
let result = self.hold_repo.create_hold(hold).await?;
Ok(HoldResult {
hold_id: result.hold().id,
is_new: result.is_new(),
amount_lamports: result.hold().amount,
expires_at: result.hold().expires_at,
})
}
/// Capture a hold, converting it to a spend
///
/// This finalizes the two-phase commit, deducting the held credits.
/// Returns an error if the hold has expired.
pub async fn capture(&self, hold_id: Uuid) -> Result<SpendResult, AppError> {
// Get the hold first to know the details
let hold = self
.hold_repo
.get_hold(hold_id)
.await?
.ok_or_else(|| AppError::NotFound(format!("Hold {} not found", hold_id)))?;
// CRITICAL: Validate hold can be captured (prevents race condition with expiry job)
if !hold.can_capture() {
if hold.is_expired() {
tracing::warn!(
hold_id = %hold_id,
user_id = %hold.user_id,
expires_at = %hold.expires_at,
"Attempted to capture expired hold"
);
return Err(AppError::Validation(format!(
"Hold {} has expired at {}",
hold_id, hold.expires_at
)));
}
tracing::warn!(
hold_id = %hold_id,
user_id = %hold.user_id,
status = hold.status.as_str(),
"Attempted to capture hold with invalid status"
);
return Err(AppError::Validation(format!(
"Hold {} cannot be captured, status: {}",
hold_id,
hold.status.as_str()
)));
}
// Create the transaction from the hold
let tx = CreditTransactionEntity::from_captured_hold(
hold.user_id,
hold.amount,
&hold.currency,
hold_id,
&hold.idempotency_key,
hold.reference_type.as_deref(),
hold.reference_id,
hold.metadata.clone(),
);
let tx_id = tx.id;
// SRV-02: Capture hold + deduct balance + insert transaction record
// in a single DB transaction to prevent inconsistency on crash.
let (_captured, new_balance) = self.hold_repo.capture_hold(hold_id, tx_id, tx).await?;
Ok(SpendResult {
transaction_id: tx_id,
new_balance_lamports: new_balance,
amount_lamports: hold.amount,
currency: hold.currency,
})
}
/// Release a hold, returning credits to available balance
///
/// Use this when an operation is cancelled or fails.
pub async fn release(&self, hold_id: Uuid) -> Result<(), AppError> {
self.hold_repo.release_hold(hold_id).await?;
Ok(())
}
/// Get pending holds for a user
pub async fn get_pending_holds(
&self,
user_id: Uuid,
currency: Option<&str>,
) -> Result<Vec<CreditHoldEntity>, AppError> {
self.hold_repo.get_pending_holds(user_id, currency).await
}
/// Expire stale holds that have passed their TTL
///
/// Returns the number of holds expired. Called by the background task.
pub async fn expire_holds(&self) -> Result<u64, AppError> {
self.hold_repo.expire_holds().await
}
// =========================================================================
// ADMIN OPERATIONS
// =========================================================================
/// Adjust a user's credit balance (admin operation)
///
/// Use for refunds, bonuses, promotional credits, or manual corrections.
/// Positive amounts add credits, negative amounts remove credits.
///
/// # Arguments
/// * `admin_id` - ID of the admin performing the adjustment
/// * `user_id` - User whose balance to adjust
/// * `amount` - Amount in lamports (positive = credit, negative = debit)
/// * `currency` - Currency code (e.g., "SOL")
/// * `reason` - Human-readable reason for the adjustment
/// * `reference_type` - Optional type (e.g., "refund", "bonus", "promo")
/// * `reference_id` - Optional ID of related entity
#[allow(clippy::too_many_arguments)]
pub async fn adjust(
&self,
admin_id: Uuid,
user_id: Uuid,
amount: i64,
currency: &str,
reason: &str,
reference_type: Option<&str>,
reference_id: Option<Uuid>,
) -> Result<AdjustResult, AppError> {
if amount == 0 {
return Err(AppError::Validation("Amount cannot be zero".into()));
}
if reason.trim().is_empty() {
return Err(AppError::Validation("Reason is required".into()));
}
let tx = CreditTransactionEntity::new_adjustment(
user_id,
amount,
currency,
admin_id,
reason,
reference_type,
reference_id,
);
let tx_id = tx.id;
let new_balance = if amount > 0 {
// Adding credits
self.credit_repo
.add_credit(user_id, amount, currency, tx)
.await?
} else {
// M-04: deduct_credit does an atomic check-and-deduct (WHERE balance >= amount).
// No separate balance check needed — that was a TOCTOU race.
let debit_amount = amount.abs();
self.credit_repo
.deduct_credit(user_id, debit_amount, currency, tx)
.await?
};
Ok(AdjustResult {
transaction_id: tx_id,
new_balance_lamports: new_balance,
amount_lamports: amount,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::repositories::{InMemoryCreditHoldRepository, InMemoryCreditRepository};
fn create_service() -> CreditService {
let credit_repo: Arc<dyn CreditRepository> = Arc::new(InMemoryCreditRepository::new());
let hold_repo: Arc<dyn CreditHoldRepository> =
Arc::new(InMemoryCreditHoldRepository::new());
CreditService::new(credit_repo, hold_repo)
}
#[tokio::test]
async fn test_get_balance_new_user() {
let service = create_service();
let balance = service.get_balance(Uuid::new_v4(), "SOL").await.unwrap();
assert_eq!(balance.balance_lamports, 0);
assert_eq!(balance.available_lamports, 0);
assert_eq!(balance.currency, "SOL");
}
#[tokio::test]
async fn test_has_sufficient_balance() {
let service = create_service();
let user_id = Uuid::new_v4();
// New user has zero balance
let has_balance = service
.has_sufficient_balance(user_id, "SOL", 1000)
.await
.unwrap();
assert!(!has_balance);
}
#[tokio::test]
async fn test_spend_insufficient_balance() {
let service = create_service();
let user_id = Uuid::new_v4();
let order_id = Uuid::new_v4();
// Try to spend without balance
let result = service
.spend(
user_id,
1000,
"SOL",
"order-123".to_string(),
"order",
order_id,
None,
)
.await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_hold_insufficient_balance() {
let service = create_service();
let user_id = Uuid::new_v4();
// Try to hold without balance
let result = service
.hold(
user_id,
1000,
"SOL",
"order-123".to_string(),
None,
Some("order"),
Some(Uuid::new_v4()),
None,
)
.await;
assert!(result.is_err());
}
}