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
//! Deposit service for Privacy Cash integration (SSS wallets only)
//!
//! Executes deposits to user's Privacy Cash account using their SSS keypair.
//! Stores Share B during "privacy period" for later withdrawal to company wallet.
//!
//! Tiered deposit recording (public, micro) is in deposit_tiered_service.rs.
use chrono::{Duration, Utc};
use std::sync::Arc;
use uuid::Uuid;
use crate::config::PrivacyConfig;
use crate::errors::AppError;
use crate::repositories::{
CreditRepository, CreditTransactionEntity, DepositRepository, DepositSessionEntity,
};
use crate::services::{CreditParams, DepositCreditService, PrivacySidecarClient};
/// M-10: Minimum privacy period (60 seconds)
const MIN_PRIVACY_PERIOD_SECS: u64 = 60;
/// M-10: Maximum privacy period (30 days)
const MAX_PRIVACY_PERIOD_SECS: u64 = 30 * 24 * 3600;
/// Validate privacy period is within sane bounds (60s to 30 days).
fn validate_privacy_period(secs: u64) -> Result<(), AppError> {
if secs < MIN_PRIVACY_PERIOD_SECS || secs > MAX_PRIVACY_PERIOD_SECS {
return Err(AppError::Validation(format!(
"Privacy period must be between {}s and {}s, got {}s",
MIN_PRIVACY_PERIOD_SECS, MAX_PRIVACY_PERIOD_SECS, secs
)));
}
Ok(())
}
/// Result of executing a deposit
pub struct DepositResult {
/// Session ID for tracking
pub session_id: Uuid,
/// Transaction signature on Solana
pub tx_signature: String,
/// Amount deposited (in lamports)
pub amount_lamports: i64,
/// User's public key (Privacy Cash account owner)
pub user_pubkey: String,
/// When the privacy period ends (withdrawal can occur)
pub withdrawal_available_at: chrono::DateTime<Utc>,
}
/// Result of executing an SPL token deposit (swap + deposit)
pub struct SplDepositResult {
/// Session ID for tracking
pub session_id: Uuid,
/// Transaction signature of the swap
pub swap_tx_signature: String,
/// Transaction signature of the Privacy Cash deposit
pub deposit_tx_signature: String,
/// Amount of SOL deposited (in lamports) after swap
pub sol_amount_lamports: i64,
/// Input token mint address
pub input_mint: String,
/// Input token amount (pre-swap) - this is what user is credited
pub input_amount: i64,
/// Currency credited (e.g., "USD" for stablecoins)
pub credit_currency: String,
/// User's public key
pub user_pubkey: String,
/// When the privacy period ends
pub withdrawal_available_at: chrono::DateTime<Utc>,
}
/// Well-known stablecoin mint addresses
const USDC_MINT: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const USDT_MINT: &str = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB";
/// Determine credit currency from token mint.
/// R2-M01: Returns error for unrecognized mints instead of silently defaulting to USD.
fn currency_from_mint(mint: &str) -> Result<&'static str, AppError> {
match mint {
USDC_MINT | USDT_MINT => Ok("USD"),
_ => Err(AppError::Validation(format!(
"Unsupported token mint for credit currency: {}",
mint
))),
}
}
/// Deposit service configuration
///
/// Note: privacy_period_secs is read from the database (system_settings table)
/// and passed to methods at call time for dynamic configuration.
pub struct DepositServiceConfig {
/// Minimum deposit amount in lamports
pub min_deposit_lamports: u64,
/// Maximum deposit amount in lamports (0 = no limit)
pub max_deposit_lamports: u64,
}
/// Result of listing deposits
pub struct DepositListResult {
pub deposits: Vec<DepositSessionEntity>,
pub total: u64,
pub limit: u32,
pub offset: u32,
}
/// Deposit service for SSS embedded wallets
pub struct DepositService {
deposit_repo: Arc<dyn DepositRepository>,
credit_repo: Arc<dyn CreditRepository>,
sidecar: Arc<PrivacySidecarClient>,
credit_service: Arc<DepositCreditService>,
config: DepositServiceConfig,
}
impl DepositService {
/// Create a new deposit service
pub fn new(
deposit_repo: Arc<dyn DepositRepository>,
credit_repo: Arc<dyn CreditRepository>,
sidecar: Arc<PrivacySidecarClient>,
credit_service: Arc<DepositCreditService>,
config: &PrivacyConfig,
) -> Self {
// M-02: Log when max_deposit_lamports=0 (no limit) for visibility
if config.max_deposit_lamports == 0 {
tracing::info!(
"Deposit service configured with no maximum deposit limit (max_deposit_lamports=0)"
);
}
Self {
deposit_repo,
credit_repo,
sidecar,
credit_service,
config: DepositServiceConfig {
min_deposit_lamports: config.min_deposit_lamports,
max_deposit_lamports: config.max_deposit_lamports,
},
}
}
/// Execute a Privacy Cash deposit for an SSS embedded wallet
///
/// The deposit goes to the USER's Privacy Cash account (user's pubkey is owner).
/// This provides privacy because the withdrawal to company wallet is unlinkable.
///
/// Requirements:
/// - User must have no-recovery wallet (no Share C)
/// - Encrypted private key must be stored for later withdrawal
///
/// # Arguments
/// * `privacy_period_secs` - Read from system_settings table via SettingsService
pub async fn execute_deposit(
&self,
user_id: Uuid,
user_private_key: &str,
encrypted_private_key: &str,
amount_lamports: u64,
privacy_period_secs: u64,
) -> Result<DepositResult, AppError> {
// M-10: Validate privacy period is within sane bounds
validate_privacy_period(privacy_period_secs)?;
// R2-H04: Explicit zero-amount guard regardless of min_deposit_lamports config
if amount_lamports == 0 {
return Err(AppError::Validation(
"Deposit amount must be positive".into(),
));
}
// Validate amount
if amount_lamports < self.config.min_deposit_lamports {
return Err(AppError::Validation(format!(
"Minimum deposit is {} lamports",
self.config.min_deposit_lamports
)));
}
// Check max limit (0 means no limit)
if self.config.max_deposit_lamports > 0
&& amount_lamports > self.config.max_deposit_lamports
{
tracing::warn!(
user_id = %user_id,
amount_lamports = amount_lamports,
max_allowed = self.config.max_deposit_lamports,
"Deposit amount exceeds maximum limit"
);
return Err(AppError::Validation(format!(
"Maximum deposit is {} lamports",
self.config.max_deposit_lamports
)));
}
// Generate session ID
let session_id = Uuid::new_v4();
// Calculate when withdrawal becomes available
let withdrawal_available_at = Utc::now() + Duration::seconds(privacy_period_secs as i64);
// Execute deposit via sidecar (deposits to user's Privacy Cash account)
let sidecar_response = self
.sidecar
.deposit(user_private_key, amount_lamports)
.await
.map_err(|e| {
tracing::error!(
session_id = %session_id,
user_id = %user_id,
error = %e,
"Failed to execute deposit via sidecar"
);
e
})?;
// Create deposit session with encrypted private key for later withdrawal
let deposit_session = DepositSessionEntity::new_privacy_deposit(
user_id,
session_id,
sidecar_response.user_pubkey.clone(),
amount_lamports as i64,
sidecar_response.tx_signature.clone(),
encrypted_private_key.to_string(),
withdrawal_available_at,
);
self.deposit_repo.create(deposit_session).await?;
// Calculate credit amount (converts to company currency, applies fee policy)
let credit_result = self
.credit_service
.calculate(CreditParams {
deposit_amount: amount_lamports as i64,
deposit_currency: "SOL".to_string(),
has_swap: false,
has_privacy: true,
})
.await?;
// Credit the user (H-06: persist conversion rate)
let mut credit_tx = CreditTransactionEntity::new_privacy_deposit(
user_id,
credit_result.amount,
&credit_result.currency,
session_id,
);
credit_tx.conversion_rate = credit_result.conversion_rate;
self.credit_repo
.add_credit(
user_id,
credit_result.amount,
&credit_result.currency,
credit_tx,
)
.await?;
tracing::info!(
session_id = %session_id,
user_id = %user_id,
user_pubkey = %sidecar_response.user_pubkey,
amount_lamports = %amount_lamports,
credit_amount = %credit_result.amount,
credit_currency = %credit_result.currency,
fee_deducted = %credit_result.fee_deducted,
tx_signature = %sidecar_response.tx_signature,
withdrawal_available_at = %withdrawal_available_at,
"Privacy deposit completed successfully"
);
Ok(DepositResult {
session_id,
tx_signature: sidecar_response.tx_signature,
amount_lamports: amount_lamports as i64,
user_pubkey: sidecar_response.user_pubkey,
withdrawal_available_at,
})
}
/// Get deposits ready for withdrawal (privacy period elapsed)
pub async fn get_pending_withdrawals(&self) -> Result<Vec<DepositSessionEntity>, AppError> {
self.deposit_repo
.find_ready_for_withdrawal(Utc::now())
.await
}
/// Mark a deposit as withdrawn
pub async fn mark_withdrawn(
&self,
session_id: Uuid,
withdrawal_tx_signature: &str,
) -> Result<(), AppError> {
self.deposit_repo
.mark_withdrawn(session_id, withdrawal_tx_signature)
.await
}
/// Get a deposit session by ID (for status checks)
pub async fn get_session(
&self,
session_id: Uuid,
user_id: Uuid,
) -> Result<DepositSessionEntity, AppError> {
let session = self
.deposit_repo
.find_by_id(session_id)
.await?
.ok_or_else(|| AppError::NotFound("Deposit session not found".into()))?;
if session.user_id != user_id {
return Err(AppError::Forbidden(
"Not authorized to view this deposit".into(),
));
}
Ok(session)
}
/// List deposits for a user with pagination
pub async fn list_deposits(
&self,
user_id: Uuid,
limit: u32,
offset: u32,
) -> Result<DepositListResult, AppError> {
let deposits = self
.deposit_repo
.list_by_user(user_id, None, limit, offset)
.await?;
let total = self.deposit_repo.count_by_user(user_id, None).await?;
Ok(DepositListResult {
deposits,
total,
limit,
offset,
})
}
/// Execute an SPL token deposit (swap to SOL + Privacy Cash deposit)
///
/// Uses Jupiter gasless swap to convert SPL tokens to SOL, then deposits
/// to the user's Privacy Cash account.
///
/// Requirements:
/// - User wallet must have < 0.01 SOL (gasless requirement)
/// - Trade size must be > ~$10 USD (Jupiter minimum)
/// - User must have no-recovery wallet
///
/// # Arguments
/// * `privacy_period_secs` - Read from system_settings table via SettingsService
pub async fn execute_spl_deposit(
&self,
user_id: Uuid,
user_private_key: &str,
encrypted_private_key: &str,
input_mint: &str,
amount: &str,
privacy_period_secs: u64,
) -> Result<SplDepositResult, AppError> {
// M-10: Validate privacy period is within sane bounds
validate_privacy_period(privacy_period_secs)?;
// H-07: Validate SPL deposit amount is positive
let parsed_amount: f64 = amount
.parse()
.map_err(|_| AppError::Validation(format!("Invalid deposit amount: {}", amount)))?;
if parsed_amount <= 0.0 {
return Err(AppError::Validation(
"Deposit amount must be positive".into(),
));
}
// Generate session ID
let session_id = Uuid::new_v4();
// Calculate when withdrawal becomes available
let withdrawal_available_at = Utc::now() + Duration::seconds(privacy_period_secs as i64);
// Execute swap and deposit via sidecar
let sidecar_response = self
.sidecar
.swap_and_deposit(user_private_key, input_mint, amount)
.await
.map_err(|e| {
tracing::error!(
session_id = %session_id,
user_id = %user_id,
input_mint = %input_mint,
error = %e,
"Failed to execute SPL swap and deposit via sidecar"
);
e
})?;
let sol_amount_lamports = sidecar_response.sol_amount_lamports;
// M-03: Parse and validate input amount from sidecar
let input_amount: i64 = sidecar_response.input_amount.parse().map_err(|_| {
AppError::Internal(anyhow::anyhow!("Invalid input amount from sidecar"))
})?;
if input_amount <= 0 {
return Err(AppError::Internal(anyhow::anyhow!(
"Sidecar returned non-positive input_amount: {}",
input_amount
)));
}
// Determine deposit currency from token mint
let deposit_currency = currency_from_mint(&sidecar_response.input_mint)?;
// Create deposit session with encrypted private key for later withdrawal
// Note: We store sol_amount_lamports for Privacy Cash tracking
let deposit_session = DepositSessionEntity::new_privacy_deposit(
user_id,
session_id,
sidecar_response.user_pubkey.clone(),
sol_amount_lamports,
sidecar_response.deposit_tx_signature.clone(),
encrypted_private_key.to_string(),
withdrawal_available_at,
);
self.deposit_repo.create(deposit_session).await?;
// Calculate credit amount (converts to company currency, applies fee policy)
let credit_result = self
.credit_service
.calculate(CreditParams {
deposit_amount: input_amount,
deposit_currency: deposit_currency.to_string(),
has_swap: true,
has_privacy: true,
})
.await?;
// Credit the user (H-06: persist conversion rate)
let mut credit_tx = CreditTransactionEntity::new_privacy_deposit(
user_id,
credit_result.amount,
&credit_result.currency,
session_id,
);
credit_tx.conversion_rate = credit_result.conversion_rate;
self.credit_repo
.add_credit(
user_id,
credit_result.amount,
&credit_result.currency,
credit_tx,
)
.await?;
tracing::info!(
session_id = %session_id,
user_id = %user_id,
user_pubkey = %sidecar_response.user_pubkey,
input_mint = %input_mint,
input_amount = %input_amount,
credit_amount = %credit_result.amount,
credit_currency = %credit_result.currency,
fee_deducted = %credit_result.fee_deducted,
sol_amount_lamports = %sol_amount_lamports,
swap_tx = %sidecar_response.swap_tx_signature,
deposit_tx = %sidecar_response.deposit_tx_signature,
withdrawal_available_at = %withdrawal_available_at,
"SPL deposit (swap + privacy deposit) completed"
);
Ok(SplDepositResult {
session_id,
swap_tx_signature: sidecar_response.swap_tx_signature,
deposit_tx_signature: sidecar_response.deposit_tx_signature,
sol_amount_lamports,
input_mint: sidecar_response.input_mint,
input_amount,
credit_currency: credit_result.currency,
user_pubkey: sidecar_response.user_pubkey,
withdrawal_available_at,
})
}
}