cedros-login-server 0.0.37

Authentication server for cedros-login with email/password, Google OAuth, and Solana wallet sign-in
Documentation
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
//! Privacy deposit handlers
//!
//! POST /deposit - Execute a privacy deposit (SSS embedded wallet)
//! GET /deposit/status/{session_id} - Check deposit status
//! GET /deposit/config - Get deposit configuration with tier thresholds
//! POST /deposit/cancel/{session_id} - Cancel a deposit (not supported)
//! GET /deposits - List deposits for authenticated user
//!
//! Tiered deposit handlers (public, micro) are in deposit_tiered.rs.

use axum::{
    extract::{Path, Query, State},
    http::HeaderMap,
    Json,
};
use std::sync::Arc;
use uuid::Uuid;

#[cfg(feature = "postgres")]
use sqlx::FromRow;

use crate::callback::AuthCallback;
use crate::errors::AppError;
use crate::models::{
    ConfirmSplDepositRequest, ConfirmSplDepositResponse, DepositConfigResponse,
    DepositItemResponse, DepositListResponse, DepositStatusResponse, MessageResponse,
    PendingSplDepositItemResponse, PendingSplDepositListResponse,
};
use crate::services::{DepositService, EmailService, SolPriceService};
use crate::utils::authenticate;
use crate::AppState;

/// Request to execute a privacy deposit
#[derive(Debug, serde::Deserialize)]
pub struct PrivacyDepositRequest {
    /// Amount to deposit in lamports
    pub amount_lamports: u64,
}

/// Response from executing a privacy deposit
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PrivacyDepositResponse {
    /// Session ID for tracking
    pub session_id: Uuid,
    /// Transaction signature on Solana
    pub tx_signature: String,
    /// Amount deposited in lamports
    pub amount_lamports: i64,
    /// Human-readable message
    pub message: String,
    /// When withdrawal becomes available
    pub withdrawal_available_at: chrono::DateTime<chrono::Utc>,
}

/// Helper to create a DepositService from AppState
pub(crate) fn create_deposit_service<C: AuthCallback, E: EmailService>(
    state: &Arc<AppState<C, E>>,
) -> Result<DepositService, AppError> {
    let sidecar = state.privacy_sidecar_client.clone().ok_or_else(|| {
        AppError::Internal(anyhow::anyhow!("Privacy sidecar client not configured"))
    })?;

    Ok(DepositService::new(
        state.deposit_repo.clone(),
        state.credit_repo.clone(),
        sidecar,
        state.deposit_credit_service.clone(),
        &state.config.privacy,
    ))
}

/// POST /deposit - Execute a privacy deposit for SSS embedded wallet
///
/// Deposits to the user's Privacy Cash account using their SSS keypair.
/// Server stores Share B during privacy period for later withdrawal.
///
/// Requirements:
/// - User must have SSS wallet enrolled
/// - Wallet must be unlocked (cached encryption key)
/// - Wallet must be enrolled in "no recovery" mode (prevents user front-running withdrawals)
pub async fn execute_deposit<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Json(request): Json<PrivacyDepositRequest>,
) -> Result<Json<PrivacyDepositResponse>, AppError> {
    // GeoIP country screening (fail-open: skipped when header not configured or absent)
    state.sanctions_service.check_country_from_request(&headers).await?;

    // KYC enforcement gate
    if let Some(kyc_service) = &state.kyc_service {
        let auth_user = authenticate(&state, &headers).await?;
        kyc_service.check_enforcement(auth_user.user_id, "deposits").await?;
    }

    // Verify privacy deposits are enabled
    if !state.config.privacy.enabled {
        return Err(AppError::NotFound("Privacy deposits not enabled".into()));
    }

    // Verify wallet is configured for no-recovery mode
    // This is required for Privacy Cash to prevent users from front-running withdrawals
    use crate::config::WalletRecoveryMode;
    if state.config.wallet.recovery_mode != WalletRecoveryMode::None {
        return Err(AppError::Validation(
            "Privacy deposits require no-recovery wallet mode. Contact administrator.".into(),
        ));
    }

    // Authenticate user
    let auth_user = authenticate(&state, &headers).await?;

    // KYC threshold check (amount-based, independent of enforcement mode)
    if let Some(kyc_service) = &state.kyc_service {
        let sol_price = state
            .sol_price_service
            .get_sol_price_usd()
            .await
            .unwrap_or(0.0);
        let deposit_usd =
            (request.amount_lamports as f64 / 1_000_000_000.0) * sol_price;
        let prior_usd = state
            .credit_repo
            .get_user_stats(auth_user.user_id, "SOL")
            .await
            .map(|s| (s.total_deposited as f64 / 1_000_000_000.0) * sol_price)
            .unwrap_or(0.0);
        kyc_service
            .check_threshold(
                auth_user.user_id,
                "deposit",
                deposit_usd,
                Some(prior_usd),
            )
            .await?;
    }

    // Get wallet material - user must have enrolled SSS wallet
    let wallet_material = state
        .wallet_material_repo
        .find_default_by_user(auth_user.user_id)
        .await?
        .ok_or_else(|| {
            AppError::NotFound(
                "SSS wallet not enrolled. Privacy deposits require SSS wallet.".into(),
            )
        })?;

    // Sanctions check on the user's own wallet address
    state
        .sanctions_service
        .check_address(&wallet_material.solana_pubkey)
        .await?;

    // Token gate enforcement
    state
        .token_gating_service
        .check_enforcement(auth_user.user_id, "deposits")
        .await?;

    // Get session ID for wallet unlock cache
    let session_id_for_cache = auth_user.session_id.ok_or_else(|| {
        AppError::Unauthorized("Session required for embedded wallet operations".into())
    })?;

    // Get cached encryption key (wallet must be unlocked)
    let cached_key = state
        .wallet_unlock_cache
        .get(session_id_for_cache)
        .await
        .ok_or_else(|| {
            AppError::Unauthorized("Wallet is locked. Call POST /wallet/unlock first.".into())
        })?;

    // Reconstruct the user's private key from SSS shares
    let user_private_key = state
        .wallet_signing_service
        .reconstruct_private_key(&wallet_material, &cached_key)
        .map_err(|e| {
            tracing::error!(error = %e, "Failed to reconstruct private key for deposit");
            AppError::Internal(anyhow::anyhow!("Failed to reconstruct wallet key"))
        })?;

    // Encrypt private key for storage during privacy period (for later withdrawal)
    // We use NoteEncryptionService which uses a server-side AES-256-GCM key
    let note_encryption = state
        .note_encryption_service
        .as_ref()
        .ok_or_else(|| AppError::Config("Note encryption not configured".into()))?;

    use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
    let encrypted = note_encryption.encrypt(user_private_key.as_bytes())?;

    // Store as: nonce (12 bytes) + ciphertext, all base64 encoded
    let mut combined = encrypted.nonce;
    combined.extend(&encrypted.ciphertext);
    let encrypted_private_key = BASE64.encode(&combined);

    // Read privacy period from database settings
    let privacy_period_secs = state
        .settings_service
        .get_u64("privacy_period_secs")
        .await?
        .unwrap_or(604800); // 7 days default

    // Create deposit service
    let deposit_service = create_deposit_service(&state)?;

    // Execute the deposit
    let result = deposit_service
        .execute_deposit(
            auth_user.user_id,
            &user_private_key,
            &encrypted_private_key,
            request.amount_lamports,
            privacy_period_secs,
        )
        .await?;

    let sol_amount = result.amount_lamports as f64 / 1_000_000_000.0;

    Ok(Json(PrivacyDepositResponse {
        session_id: result.session_id,
        tx_signature: result.tx_signature,
        amount_lamports: result.amount_lamports,
        message: format!("Successfully deposited {:.4} SOL", sol_amount),
        withdrawal_available_at: result.withdrawal_available_at,
    }))
}

/// GET /deposit/status/{session_id} - Get deposit session status
pub async fn deposit_status<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Path(session_id): Path<Uuid>,
) -> Result<Json<DepositStatusResponse>, AppError> {
    if !state.config.privacy.enabled {
        return Err(AppError::NotFound("Privacy deposits not enabled".into()));
    }

    let auth_user = authenticate(&state, &headers).await?;

    // Create deposit service
    let deposit_service = create_deposit_service(&state)?;

    // Get the session
    let session = deposit_service
        .get_session(session_id, auth_user.user_id)
        .await?;

    Ok(Json(DepositStatusResponse::from(&session)))
}

/// Default private deposit minimum in lamports (0.25 SOL)
const DEFAULT_PRIVATE_MIN_LAMPORTS: u64 = 250_000_000;
/// Lamports per SOL
const LAMPORTS_PER_SOL: f64 = 1_000_000_000.0;
/// Jupiter minimum swap USD value
const JUPITER_MIN_USD: f64 = 10.0;
const DEFAULT_QUICK_ACTION_TOKENS: &str = "USDC,USDT,EURC";
const DEFAULT_CUSTOM_TOKENS: &str = "SOL,USDC,USDT,EURC,USD1,PYUSD,USDH,CASH,BONK,ORE";

/// Token mint addresses for price lookups (non-stablecoin tokens)
const BONK_MINT: &str = "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263";
const ORE_MINT: &str = "oreoU2P8bN6jkk3jbaiVxYnG1dCXcYxwhwyK9jSybcp";
const EURC_MINT: &str = "HzwqbKZw8HxMN6bF2yFZNrht3c2iXXzpKcFu7uBEDKtr";

fn parse_token_list(value: String) -> Vec<String> {
    value
        .split(',')
        .map(|token| token.trim())
        .filter(|token| !token.is_empty())
        .map(|token| token.to_uppercase())
        .collect()
}

/// GET /deposit/config - Get deposit configuration with tier thresholds
pub async fn deposit_config<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
) -> Result<Json<DepositConfigResponse>, AppError> {
    // F-11: Parallelize independent async lookups (~40ms sequential → ~10ms parallel)
    let token_mints = &[BONK_MINT, ORE_MINT, EURC_MINT];

    let (
        privacy_period_secs_opt,
        sol_price_usd,
        private_min_lamports_opt,
        treasury_config,
        micro_batch_threshold_opt,
        fee_config,
        quick_action_tokens_opt,
        custom_token_symbols_opt,
        mint_prices_result,
        show_explainer_opt,
        custom_tokens_json_opt,
    ) = tokio::try_join!(
        state.settings_service.get_u64("privacy_period_secs"),
        state.sol_price_service.get_sol_price_usd(),
        state.settings_service.get_u64("private_deposit_min_lamports"),
        async { state.treasury_config_repo.find_for_org(None).await.map(Some) },
        state.settings_service.get_u64("micro_batch_threshold_usd"),
        state.deposit_credit_service.get_fee_config(),
        state.settings_service.get("deposit_quick_action_tokens"),
        state.settings_service.get("deposit_custom_tokens"),
        async { Ok::<_, AppError>(state.sol_price_service.get_token_prices(token_mints).await.unwrap_or_default()) },
        state.settings_service.get_bool("deposit_show_explainer"),
        state.settings_service.get("deposit_custom_tokens_json"),
    )?;

    let privacy_period_secs = privacy_period_secs_opt.unwrap_or(604800); // 7 days default
    let private_min_lamports = private_min_lamports_opt.unwrap_or(DEFAULT_PRIVATE_MIN_LAMPORTS);

    // Calculate tier thresholds
    let private_min_sol = private_min_lamports as f64 / LAMPORTS_PER_SOL;
    let private_min_usd_raw = private_min_sol * sol_price_usd;
    // Round up to nearest $5 (favors company)
    let private_min_usd = SolPriceService::round_up_to_nearest_5(private_min_usd_raw);

    // Company wallet and currency from config
    let company_wallet = state
        .config
        .privacy
        .company_wallet_address
        .clone()
        .unwrap_or_default();
    let company_currency = state.config.privacy.company_currency.clone();

    let micro_deposit_address = treasury_config.flatten().map(|c| c.wallet_address);
    let micro_batch_threshold_usd = micro_batch_threshold_opt
        .map(|v| v as f64)
        .unwrap_or(JUPITER_MIN_USD);

    let fee_policy = match fee_config.policy {
        crate::services::FeePolicy::CompanyPaysAll => "company_pays_all",
        crate::services::FeePolicy::UserPaysSwap => "user_pays_swap",
        crate::services::FeePolicy::UserPaysPrivacy => "user_pays_privacy",
        crate::services::FeePolicy::UserPaysAll => "user_pays_all",
    };

    let quick_action_tokens = quick_action_tokens_opt
        .unwrap_or_else(|| DEFAULT_QUICK_ACTION_TOKENS.to_string());
    let custom_token_symbols = custom_token_symbols_opt
        .unwrap_or_else(|| DEFAULT_CUSTOM_TOKENS.to_string());

    // Build symbol -> price map
    let mut token_prices = std::collections::HashMap::new();
    token_prices.insert("SOL".to_string(), sol_price_usd);
    if let Some(&price) = mint_prices_result.get(BONK_MINT) {
        token_prices.insert("BONK".to_string(), price);
    }
    if let Some(&price) = mint_prices_result.get(ORE_MINT) {
        token_prices.insert("ORE".to_string(), price);
    }
    if let Some(&price) = mint_prices_result.get(EURC_MINT) {
        token_prices.insert("EURC".to_string(), price);
    }

    // Private deposits require no-recovery wallet mode (to prevent front-running)
    use crate::config::WalletRecoveryMode;
    let private_deposits_enabled = state.config.wallet.recovery_mode == WalletRecoveryMode::None;

    let show_explainer = show_explainer_opt.unwrap_or(false);

    // Parse custom token definitions from JSON
    let custom_tokens: Option<Vec<crate::models::CustomTokenDefinition>> = custom_tokens_json_opt
        .and_then(|json_str| serde_json::from_str(&json_str).ok());

    Ok(Json(DepositConfigResponse {
        enabled: state.config.privacy.enabled,
        private_deposits_enabled,
        privacy_period_secs,
        company_wallet,
        company_currency,
        sol_price_usd,
        token_prices,
        private_min_sol,
        private_min_usd,
        public_min_usd: JUPITER_MIN_USD,
        sol_micro_max_usd: JUPITER_MIN_USD,
        supported_currencies: vec!["SOL".to_string(), "USDC".to_string(), "USDT".to_string()],
        quick_action_tokens: parse_token_list(quick_action_tokens),
        custom_token_symbols: parse_token_list(custom_token_symbols),
        micro_deposit_address,
        micro_batch_threshold_usd,
        fee_policy: fee_policy.to_string(),
        privacy_fee_percent: fee_config.privacy_percent_bps as f64 / 100.0,
        privacy_fee_fixed_lamports: fee_config.privacy_fixed_lamports,
        swap_fee_percent: fee_config.swap_percent_bps as f64 / 100.0,
        swap_fee_fixed_lamports: fee_config.swap_fixed_lamports,
        company_fee_percent: fee_config.company_percent_bps as f64 / 100.0,
        company_fee_fixed_lamports: fee_config.company_fixed_lamports,
        show_explainer,
        custom_tokens,
    }))
}

/// Placeholder response for cancel - deposits cannot be cancelled after execution
pub async fn cancel_deposit<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Path(_session_id): Path<Uuid>,
) -> Result<Json<MessageResponse>, AppError> {
    if !state.config.privacy.enabled {
        return Err(AppError::NotFound("Privacy deposits not enabled".into()));
    }

    let _auth_user = authenticate(&state, &headers).await?;

    // In the new flow, deposits are executed immediately and cannot be cancelled
    Err(AppError::Validation(
        "Privacy deposits cannot be cancelled after execution".into(),
    ))
}

/// Query params for listing deposits
#[derive(Debug, serde::Deserialize)]
pub struct ListDepositsQuery {
    /// Max number of deposits to return (default: 20, max: 100)
    #[serde(default = "default_limit")]
    pub limit: u32,
    /// Offset for pagination (default: 0)
    #[serde(default)]
    pub offset: u32,
}

fn default_limit() -> u32 {
    20
}

/// GET /deposits - List deposits for authenticated user
pub async fn list_deposits<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Query(query): Query<ListDepositsQuery>,
) -> Result<Json<DepositListResponse>, AppError> {
    if !state.config.privacy.enabled {
        return Err(AppError::NotFound("Privacy deposits not enabled".into()));
    }

    let auth_user = authenticate(&state, &headers).await?;

    // Clamp limit to max 100
    let limit = query.limit.min(100);

    // Create deposit service
    let deposit_service = create_deposit_service(&state)?;

    // List deposits
    let result = deposit_service
        .list_deposits(auth_user.user_id, limit, query.offset)
        .await?;

    Ok(Json(DepositListResponse {
        deposits: result
            .deposits
            .iter()
            .map(DepositItemResponse::from)
            .collect(),
        total: result.total,
        limit: result.limit,
        offset: result.offset,
    }))
}

// =============================================================================
// Pending SPL Deposits
// =============================================================================

#[cfg(feature = "postgres")]
#[derive(Debug, FromRow)]
struct PendingSplDepositRow {
    id: Uuid,
    wallet_address: String,
    token_mint: String,
    token_amount_raw: String,
    token_amount: Option<i64>,
    tx_signature: String,
    created_at: chrono::DateTime<chrono::Utc>,
    expires_at: chrono::DateTime<chrono::Utc>,
}

/// GET /deposit/pending-spl - List pending SPL deposits awaiting user confirmation
pub async fn list_pending_spl_deposits<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Query(query): Query<ListDepositsQuery>,
) -> Result<Json<PendingSplDepositListResponse>, AppError> {
    if !state.config.privacy.enabled {
        return Err(AppError::NotFound("Privacy deposits not enabled".into()));
    }

    let auth_user = authenticate(&state, &headers).await?;
    let limit = query.limit.min(100);

    #[cfg(feature = "postgres")]
    let pool = state.postgres_pool.as_ref().ok_or_else(|| {
        AppError::Config("Postgres pool is required for pending SPL deposits".into())
    })?;

    #[cfg(not(feature = "postgres"))]
    {
        let _ = auth_user;
        let _ = limit;
        return Err(AppError::Config(
            "Pending SPL deposits require the 'postgres' feature".into(),
        ));
    }

    #[cfg(feature = "postgres")]
    {
        // M-05: Mark expired pending records so they don't accumulate indefinitely
        let _ = sqlx::query(
            "UPDATE pending_spl_deposits SET status = 'expired' WHERE status = 'pending' AND expires_at <= NOW()"
        )
        .execute(pool)
        .await;

        let rows: Vec<PendingSplDepositRow> = sqlx::query_as(
            r#"
            SELECT id, wallet_address, token_mint, token_amount_raw, token_amount,
                   tx_signature, created_at, expires_at
            FROM pending_spl_deposits
            WHERE user_id = $1
              AND status = 'pending'
              AND expires_at > NOW()
            ORDER BY created_at DESC
            LIMIT $2 OFFSET $3
            "#,
        )
        .bind(auth_user.user_id)
        .bind(limit as i64)
        .bind(query.offset as i64)
        .fetch_all(pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;

        let total: i64 = sqlx::query_scalar(
            r#"
            SELECT COUNT(*)
            FROM pending_spl_deposits
            WHERE user_id = $1
              AND status = 'pending'
              AND expires_at > NOW()
            "#,
        )
        .bind(auth_user.user_id)
        .fetch_one(pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;

        let deposits = rows
            .into_iter()
            .filter_map(|r| {
                let token_amount = r.token_amount?;
                Some(PendingSplDepositItemResponse {
                    id: r.id,
                    wallet_address: r.wallet_address,
                    token_mint: r.token_mint,
                    token_amount_raw: r.token_amount_raw,
                    token_amount,
                    tx_signature: r.tx_signature,
                    created_at: r.created_at,
                    expires_at: r.expires_at,
                })
            })
            .collect();

        Ok(Json(PendingSplDepositListResponse {
            deposits,
            total: total as u64,
            limit,
            offset: query.offset,
        }))
    }
}

/// POST /deposit/confirm-spl - Confirm and process a pending SPL deposit
pub async fn confirm_spl_deposit<C: AuthCallback, E: EmailService>(
    State(state): State<Arc<AppState<C, E>>>,
    headers: HeaderMap,
    Json(request): Json<ConfirmSplDepositRequest>,
) -> Result<Json<ConfirmSplDepositResponse>, AppError> {
    if !state.config.privacy.enabled {
        return Err(AppError::NotFound("Privacy deposits not enabled".into()));
    }

    // Privacy deposits require no-recovery wallet mode
    use crate::config::WalletRecoveryMode;
    if state.config.wallet.recovery_mode != WalletRecoveryMode::None {
        return Err(AppError::Validation(
            "Privacy deposits require no-recovery wallet mode. Contact administrator.".into(),
        ));
    }

    let auth_user = authenticate(&state, &headers).await?;

    // KYC enforcement gate (SPL deposits are stablecoin deposits)
    if let Some(kyc_service) = &state.kyc_service {
        kyc_service
            .check_enforcement(auth_user.user_id, "deposits")
            .await?;
    }

    // Token gate enforcement
    state
        .token_gating_service
        .check_enforcement(auth_user.user_id, "deposits")
        .await?;

    #[cfg(feature = "postgres")]
    let pool = state.postgres_pool.as_ref().ok_or_else(|| {
        AppError::Config("Postgres pool is required for confirming SPL deposits".into())
    })?;

    #[cfg(not(feature = "postgres"))]
    {
        let _ = auth_user;
        let _ = request;
        return Err(AppError::Config(
            "Confirming SPL deposits requires the 'postgres' feature".into(),
        ));
    }

    // Fetch and atomically claim the pending record
    #[cfg(feature = "postgres")]
    let pending: PendingSplDepositRow = {
        let row = sqlx::query_as::<_, PendingSplDepositRow>(
            r#"
            UPDATE pending_spl_deposits
            SET status = 'processing'
            WHERE id = $1
              AND user_id = $2
              AND status = 'pending'
              AND expires_at > NOW()
            RETURNING id, wallet_address, token_mint, token_amount_raw, token_amount,
                      tx_signature, created_at, expires_at
            "#,
        )
        .bind(request.pending_id)
        .bind(auth_user.user_id)
        .fetch_optional(pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;

        row.ok_or_else(|| AppError::NotFound("Pending SPL deposit not found".into()))?
    };

    let token_amount = pending
        .token_amount
        .ok_or_else(|| AppError::Validation("Pending SPL deposit missing token_amount".into()))?;

    // H-07: Validate token amount is positive before processing
    if token_amount <= 0 {
        return Err(AppError::Validation(
            "Deposit amount must be positive".into(),
        ));
    }

    // KYC threshold check for SPL deposits (stablecoins — amount is in USD)
    if let Some(kyc_service) = &state.kyc_service {
        // Whitelisted SPL tokens are stablecoins (USDC/USDT) with 6 decimal places
        let deposit_usd = token_amount as f64 / 1_000_000.0;
        let company_currency = &state.config.privacy.company_currency;
        let sol_price = state
            .sol_price_service
            .get_sol_price_usd()
            .await
            .unwrap_or(0.0);
        let prior_usd = state
            .credit_repo
            .get_user_stats(auth_user.user_id, company_currency)
            .await
            .map(|s| {
                if company_currency.eq_ignore_ascii_case("SOL") {
                    (s.total_deposited as f64 / 1_000_000_000.0) * sol_price
                } else {
                    s.total_deposited as f64 / 1_000_000.0
                }
            })
            .unwrap_or(0.0);
        kyc_service
            .check_threshold(auth_user.user_id, "deposit", deposit_usd, Some(prior_usd))
            .await?;
    }

    // CRITICAL: Defense-in-depth validation - verify token is still whitelisted
    // (Token may have been removed from whitelist since webhook received deposit)
    if !state
        .config
        .privacy
        .is_token_whitelisted(&pending.token_mint)
    {
        tracing::warn!(
            pending_id = %pending.id,
            token_mint = %pending.token_mint,
            user_id = %auth_user.user_id,
            "Attempted to confirm deposit with non-whitelisted token"
        );
        return Err(AppError::Validation(format!(
            "Token {} is not whitelisted for deposits",
            pending.token_mint
        )));
    }

    // Get wallet material - user must have enrolled SSS wallet
    let wallet_material = state
        .wallet_material_repo
        .find_default_by_user(auth_user.user_id)
        .await?
        .ok_or_else(|| AppError::NotFound("SSS wallet not enrolled".into()))?;

    // Get session ID for wallet unlock cache
    let session_id_for_cache = auth_user.session_id.ok_or_else(|| {
        AppError::Unauthorized("Session required for embedded wallet operations".into())
    })?;

    // Get cached encryption key (wallet must be unlocked)
    let cached_key = state
        .wallet_unlock_cache
        .get(session_id_for_cache)
        .await
        .ok_or_else(|| {
            AppError::Unauthorized("Wallet is locked. Call POST /wallet/unlock first.".into())
        })?;

    // Reconstruct the user's private key from SSS shares
    let user_private_key = state
        .wallet_signing_service
        .reconstruct_private_key(&wallet_material, &cached_key)
        .map_err(|e| {
            tracing::error!(error = %e, "Failed to reconstruct private key for SPL deposit");
            AppError::Internal(anyhow::anyhow!("Failed to reconstruct wallet key"))
        })?;

    // Encrypt private key for storage during privacy period (for later withdrawal)
    let note_encryption = state
        .note_encryption_service
        .as_ref()
        .ok_or_else(|| AppError::Config("Note encryption not configured".into()))?;

    use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
    let encrypted = note_encryption.encrypt(user_private_key.as_bytes())?;
    let mut combined = encrypted.nonce;
    combined.extend(&encrypted.ciphertext);
    let encrypted_private_key = BASE64.encode(&combined);

    // Read privacy period from database settings
    let privacy_period_secs = state
        .settings_service
        .get_u64("privacy_period_secs")
        .await?
        .unwrap_or(604800);

    let deposit_service = create_deposit_service(&state)?;

    let result = deposit_service
        .execute_spl_deposit(
            auth_user.user_id,
            &user_private_key,
            &encrypted_private_key,
            &pending.token_mint,
            &token_amount.to_string(),
            privacy_period_secs,
        )
        .await;

    // S-02: Log DB update errors instead of silently discarding with `let _ =`
    #[cfg(feature = "postgres")]
    match result {
        Ok(ok) => {
            if let Err(db_err) = sqlx::query(
                r#"
                UPDATE pending_spl_deposits
                SET status = 'completed',
                    deposit_session_id = $2,
                    processed_at = NOW(),
                    error_message = NULL
                WHERE id = $1
                "#,
            )
            .bind(pending.id)
            .bind(ok.session_id)
            .execute(pool)
            .await
            {
                // C-03: Deposit succeeded on-chain but DB status update failed.
                // Return error so client retries instead of silently succeeding.
                // The deposit session and credit were already created, so the
                // user's balance is correct — only pending_spl_deposits tracking
                // is stale. Client can check /deposit/status/{session_id}.
                tracing::error!(
                    pending_id = %pending.id,
                    session_id = %ok.session_id,
                    error = %db_err,
                    "Deposit succeeded on-chain but failed to update pending status"
                );
                // L-08: Don't leak internal session UUID to client
                return Err(AppError::Internal(anyhow::anyhow!(
                    "Deposit completed on-chain but status tracking update failed. \
                     Your balance has been credited. Check deposit status for details."
                )));
            }

            Ok(Json(ConfirmSplDepositResponse {
                success: true,
                pending_id: pending.id,
                deposit_session_id: Some(ok.session_id),
                swap_tx_signature: Some(ok.swap_tx_signature),
                deposit_tx_signature: Some(ok.deposit_tx_signature),
                error: None,
            }))
        }
        Err(e) => {
            let msg = e.to_string();
            if let Err(db_err) = sqlx::query(
                r#"
                UPDATE pending_spl_deposits
                SET status = 'failed',
                    processed_at = NOW(),
                    error_message = $2
                WHERE id = $1
                "#,
            )
            .bind(pending.id)
            .bind(&msg)
            .execute(pool)
            .await
            {
                tracing::error!(
                    pending_id = %pending.id,
                    error = %db_err,
                    "Failed to update pending_spl_deposits status after deposit failure"
                );
            }

            // S-02: Return error status, not HTTP 200 with success:false
            Err(AppError::Internal(anyhow::anyhow!(
                "SPL deposit failed: {}",
                msg
            )))
        }
    }
}