-
Notifications
You must be signed in to change notification settings - Fork 204
Expand file tree
/
Copy pathcharge_core.rs
More file actions
1392 lines (1297 loc) · 54.6 KB
/
Copy pathcharge_core.rs
File metadata and controls
1392 lines (1297 loc) · 54.6 KB
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
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Single charge logic (no auth). Used by charge_subscription and batch_charge.
//!
//! Charge runs only when status is Active or GracePeriod. On insufficient balance the
//! subscription is moved to a recoverable non-active state and an explicit failure
//! event is emitted without mutating financial accounting state.
//! On lifetime cap exhaustion the subscription is cancelled (terminal state).
//!
//! See `docs/subscription_lifecycle.md` for lifecycle details.
//! See `docs/lifetime_caps.md` for cap enforcement semantics.
//!
//! **PRs that only change how one subscription is charged should edit this file only.**
//!
//! # Reentrancy Safety
//!
//! This module does **not make external token transfers**. All state mutations happen
//! before any external interactions:
//!
//! 1. **Checks**: Validate expiration, status, interval, balance, replay protection, caps
//! 2. **Effects**: Update subscription state AND merchant earnings in storage
//! 3. **Interactions**: None (no external calls in this module)
//!
//! The public entry-point `lib.rs::charge_subscription` acquires a `ReentrancyGuard`
//! before calling `charge_one`, providing defense-in-depth protection even though
//! this function is naturally safe from external reentrancy.
//!
//! Merchant crediting happens through internal calls to `merchant::credit_merchant_balance_for_token`,
//! which only updates storage and does not call external contracts.
//!
//! See `docs/reentrancy_hardening.md` for complete charge path analysis.
#![allow(dead_code)]
use crate::oracle_adapter::{dispatch_price, PRICE_SCALE};
use crate::queries::get_subscription;
use crate::safe_math::{safe_add, safe_sub, safe_sub_balance};
use crate::state_machine::transition_to;
use crate::statements::append_statement;
use crate::subscription::{next_charge_time, write_subscription};
use crate::types::{
BillingChargeKind, BillingPeriodSnapshot, ChargeExecutionResult, ChargeFailureEvent, DataKey,
Error, FeeConvertedEvent, GracePeriodEnteredEvent, LifetimeCapReachedEvent,
SubscriptionAutoPausedEvent, SubscriptionCancelledEvent, SubscriptionChargeFailedEvent,
SubscriptionChargedEvent, SubscriptionStatus, TOPIC_CHARGED, UsageChargeRejectedEvent, UsageChargeResult,
UsageLimits, UsageState, UsageStatementEvent, SNAPSHOT_FLAG_CLOSED,
SNAPSHOT_FLAG_INTERVAL_CHARGED, SNAPSHOT_FLAG_USAGE_CHARGED,
};
use soroban_sdk::{Address, Env, String, Symbol};
/// Resolve the effective fee rate in basis points for a charge to `merchant`.
///
/// Priority:
/// 1. If a per-merchant override is set (`DataKey::MerchantFeeBps`), use it.
/// 2. Otherwise fall back to the global `DataKey::FeeBps`.
///
/// A zero return value means no fee is collected.
#[inline(always)]
fn route_fee_bps(env: &Env, merchant: &soroban_sdk::Address) -> u32 {
if let Some(override_bps) = crate::merchant::get_merchant_fee_override_bps(env, merchant) {
return override_bps;
}
crate::admin::get_protocol_fee_bps(env)
}
/// Emits a [`ChargeFailureEvent`] and returns `err` unchanged.
///
/// Call as `return Err(charge_fail(env, id, err, attempted, now))` on every
/// error path inside charge entry-points so that all failures are observable
/// by off-chain indexers regardless of error type.
#[inline(always)]
fn charge_fail(
env: &Env,
subscription_id: u32,
err: Error,
attempted_amount: i128,
ledger: u64,
) -> Error {
env.events().publish(
(Symbol::new(env, "charge_failed_v2"), subscription_id),
ChargeFailureEvent {
subscription_id,
error_code: err.to_code(),
attempted_amount,
ledger,
schema_version: crate::types::EVENT_SCHEMA_VERSION,
},
);
err
}
/// Result of a fee-token conversion attempt.
struct FeeConversion {
/// Converted fee amount in the target token. Equals `original` when no
/// conversion took place.
effective_amount: i128,
/// Target token address, or `None` when no conversion was applied.
target_token: Option<Address>,
/// Oracle price used for conversion (quote per base, scaled by 10^7).
/// 0 when no conversion was applied.
rate: u128,
}
/// Attempt to convert a fee amount from `source_token` to the configured
/// fee-token override using the oracle.
///
/// Returns the fee amount unchanged (with `target_token = None`) when:
/// - No fee-token override is configured.
/// - The override matches `source_token`.
/// - The oracle is not available (not configured, or price fetch fails).
/// - Conversion would round to zero (precision loss guard).
fn convert_fee(
env: &Env,
source_token: &Address,
fee_amount: i128,
) -> FeeConversion {
let fee_token_opt = crate::admin::get_fee_token(env);
let fee_token = match fee_token_opt {
Some(ref t) if t != source_token => t.clone(),
_ => {
return FeeConversion {
effective_amount: fee_amount,
target_token: None,
rate: 0,
};
}
};
let oracle_config = crate::oracle::get_oracle_config(env);
if !oracle_config.enabled || oracle_config.oracle.is_none() {
return FeeConversion {
effective_amount: fee_amount,
target_token: None,
rate: 0,
};
}
match dispatch_price(env, &oracle_config, source_token, &fee_token) {
Ok(price) => {
let converted = (fee_amount as u128)
.checked_mul(price)
.and_then(|v| v.checked_div(PRICE_SCALE))
.unwrap_or(0) as i128;
if converted > 0 {
FeeConversion {
effective_amount: converted,
target_token: Some(fee_token),
rate: price,
}
} else {
FeeConversion {
effective_amount: fee_amount,
target_token: None,
rate: 0,
}
}
}
Err(_) => FeeConversion {
effective_amount: fee_amount,
target_token: None,
rate: 0,
},
}
}
/// Performs a single interval-based charge with optional replay protection.
pub fn charge_one(
env: &Env,
subscription_id: u32,
now: u64,
idempotency_key: Option<soroban_sdk::BytesN<32>>,
admin_config: Option<&crate::admin::CachedAdminConfig>,
) -> Result<ChargeExecutionResult, Error> {
let mut sub = get_subscription(env, subscription_id)
.map_err(|e| charge_fail(env, subscription_id, e, 0, now))?;
// Merchant pause guard — mirrors charge_usage_one enforcement
if crate::merchant::get_merchant_paused(env, sub.merchant.clone()) {
return Err(charge_fail(
env,
subscription_id,
Error::MerchantPaused,
0,
now,
));
}
// Merchant vacation guard — block charges during vacation window
if crate::merchant::is_merchant_in_vacation(env, &sub.merchant, now) {
return Err(charge_fail(
env,
subscription_id,
Error::VacationActive,
0,
now,
));
}
crate::blocklist::require_not_blocklisted(env, &sub.subscriber)
.map_err(|e| charge_fail(env, subscription_id, e, 0, now))?;
crate::blocklist::require_not_blocklisted(env, &sub.merchant)
.map_err(|e| charge_fail(env, subscription_id, e, 0, now))?;
if let Some(split_payees) = crate::subscription::get_split_payees(env, subscription_id) {
for entry in split_payees.entries.iter() {
let (payee, _) = entry;
crate::blocklist::require_not_blocklisted(env, &payee)
.map_err(|e| charge_fail(env, subscription_id, e, 0, now))?;
if crate::merchant::get_merchant_paused(env, payee.clone()) {
return Err(charge_fail(
env,
subscription_id,
Error::MerchantPaused,
0,
now,
));
}
if crate::merchant::is_merchant_in_vacation(env, &payee, now) {
return Err(charge_fail(
env,
subscription_id,
Error::VacationActive,
0,
now,
));
}
}
}
// Expiration guard
if sub.is_expired(now, env.ledger().sequence()) {
if sub.status != SubscriptionStatus::Expired {
transition_to(&mut sub.status, SubscriptionStatus::Expired)?;
write_subscription(env, subscription_id, &sub);
env.events().publish(
(Symbol::new(env, "subscription_expired"), subscription_id),
crate::types::SubscriptionExpiredEvent {
subscription_id,
timestamp: now,
schema_version: crate::types::EVENT_SCHEMA_VERSION,
},
);
}
return Err(charge_fail(
env,
subscription_id,
Error::SubscriptionExpired,
0,
now,
));
}
let charge_amount = crate::oracle::resolve_charge_amount(env, subscription_id, &sub)
.map_err(|e| charge_fail(env, subscription_id, e, 0, now))?;
// ── Coupon discount (before protocol-fee split) ───────────────────────────
// Discount is applied to the oracle-resolved gross amount. The fee split and
// merchant credit then operate on `charge_amount` (the post-discount payable).
// This preserves: Gross = Discount + Merchant Net + Treasury Fee.
let (charge_amount, _discount_amount) = crate::coupon::apply_discount_at_charge(
env,
subscription_id,
now,
&sub.token,
charge_amount,
);
if let Some(cap) = sub.lifetime_cap {
if sub.lifetime_charged >= cap {
if sub.status != SubscriptionStatus::Cancelled {
transition_to(&mut sub.status, SubscriptionStatus::Cancelled)?;
write_subscription(env, subscription_id, &sub);
env.events().publish(
(Symbol::new(env, "lifetime_cap_reached"), subscription_id),
LifetimeCapReachedEvent {
subscription_id,
lifetime_cap: cap,
lifetime_charged: sub.lifetime_charged,
timestamp: now,
schema_version: crate::types::EVENT_SCHEMA_VERSION,
},
);
}
return Ok(ChargeExecutionResult::LifetimeCapReached);
}
}
// Scheduled cancellation: fire when cancel_at has arrived.
if let Some(cancel_at) = sub.cancel_at {
if now >= cancel_at {
if sub.status != SubscriptionStatus::Cancelled {
transition_to(&mut sub.status, SubscriptionStatus::Cancelled)?;
let refund_amount = sub.prepaid_balance;
sub.prepaid_balance = 0;
sub.cancel_at = None;
let token_addr = sub.token.clone();
write_subscription(env, subscription_id, &sub);
if refund_amount > 0 {
let token_client = soroban_sdk::token::Client::new(env, &token_addr);
token_client.transfer(
&env.current_contract_address(),
&sub.subscriber,
&refund_amount,
);
crate::accounting::sub_total_accounted(env, &token_addr, refund_amount)?;
}
env.events().publish(
(
soroban_sdk::Symbol::new(env, "subscription_cancelled"),
subscription_id,
),
SubscriptionCancelledEvent {
subscription_id,
subscriber: sub.subscriber.clone(),
merchant: sub.merchant.clone(),
token: sub.token.clone(),
authorizer: sub.subscriber.clone(),
refund_amount,
timestamp: now,
schema_version: crate::types::EVENT_SCHEMA_VERSION,
},
);
}
return Ok(ChargeExecutionResult::ScheduledCancellation);
}
}
if sub.status != SubscriptionStatus::Active && sub.status != SubscriptionStatus::GracePeriod {
if sub.status == SubscriptionStatus::InsufficientBalance {
let next_allowed = next_charge_time(sub.last_payment_timestamp, sub.interval_seconds)?;
if now < next_allowed {
return Err(charge_fail(
env,
subscription_id,
Error::NotActive,
charge_amount,
now,
));
}
} else {
return Err(charge_fail(
env,
subscription_id,
Error::NotActive,
charge_amount,
now,
));
}
}
// ── Auto-renewal gate ────────────────────────────────────────────────────
// When auto_renew is false the billing engine skips the charge once the
// interval has elapsed. The charge is silently skipped (not an error) so
// that batch operations can continue past non-renewing subscriptions.
if !sub.auto_renew {
let next_allowed = next_charge_time(sub.last_payment_timestamp, sub.interval_seconds)?;
if now >= next_allowed {
// Interval has elapsed but auto-renewal is disabled — skip.
return Ok(ChargeExecutionResult::Skipped);
}
// Interval hasn't elapsed yet: fall through to IntervalNotElapsed below.
}
let period_index = now.saturating_sub(sub.start_time) / sub.interval_seconds;
let period_start = sub
.start_time
.checked_add(period_index.saturating_mul(sub.interval_seconds))
.unwrap_or(u64::MAX);
let period_end = period_start
.checked_add(sub.interval_seconds)
.unwrap_or(u64::MAX);
// Anti-frontrunning salt
let seq = env.ledger().sequence();
let salt = {
let mut salt_buf = [0u8; 20];
salt_buf[..4].copy_from_slice(&subscription_id.to_be_bytes());
salt_buf[4..12].copy_from_slice(&sub.last_payment_timestamp.to_be_bytes());
salt_buf[12..20].copy_from_slice(&seq.to_be_bytes());
let salt_input = soroban_sdk::Bytes::from_slice(env, &salt_buf);
let hash: soroban_sdk::BytesN<32> = env.crypto().sha256(&salt_input).into();
hash
};
let salt_key = DataKey::ChargeSalt(subscription_id);
if let Some(last_salt) = env.storage().instance().get::<_, soroban_sdk::BytesN<32>>(&salt_key) {
if last_salt == salt {
return Err(charge_fail(
env,
subscription_id,
Error::Replay,
charge_amount,
now,
));
}
}
// Idempotent return: same idempotency key already processed
if let Some(ref k) = idempotency_key {
let hashed = crate::idempotency::hash_idem_key(
env,
crate::nonce::DOMAIN_CHARGE_INTERVAL,
subscription_id,
k,
);
if crate::idempotency::check_key(env, subscription_id, &hashed) {
return Ok(ChargeExecutionResult::Charged);
}
}
// Replay: already charged for this billing period
if let Some(stored_period) = env
.storage()
.instance()
.get::<_, u64>(&DataKey::ChargedPeriod(subscription_id))
{
if period_index <= stored_period {
return Err(charge_fail(
env,
subscription_id,
Error::Replay,
charge_amount,
now,
));
}
}
let next_allowed = next_charge_time(sub.last_payment_timestamp, sub.interval_seconds)?;
if now < next_allowed {
return Err(charge_fail(
env,
subscription_id,
Error::IntervalNotElapsed,
charge_amount,
now,
));
}
// -- Lifetime cap pre-check -----------------------------------------------
if let Some(cap) = sub.lifetime_cap {
let remaining = if sub.lifetime_charged >= cap {
0
} else {
safe_sub(cap, sub.lifetime_charged)?
};
if remaining == 0 || charge_amount > remaining {
// Cap already exhausted or this charge would exceed it: cancel without
// moving funds and return an explicit terminal error.
transition_to(&mut sub.status, SubscriptionStatus::Cancelled)?;
write_subscription(env, subscription_id, &sub);
env.events().publish(
(Symbol::new(env, "lifetime_cap_reached"), subscription_id),
LifetimeCapReachedEvent {
subscription_id,
lifetime_cap: cap,
lifetime_charged: sub.lifetime_charged,
timestamp: now,
schema_version: crate::types::EVENT_SCHEMA_VERSION,
},
);
return Ok(ChargeExecutionResult::LifetimeCapReached);
}
}
let storage = env.storage().instance();
match safe_sub_balance(sub.prepaid_balance, charge_amount) {
Ok(new_balance) => {
sub.prepaid_balance = new_balance;
let (fee_bps, treasury_opt) = if let Some(cfg) = admin_config {
(cfg.fee_bps, cfg.treasury.clone())
} else {
(
crate::admin::get_protocol_fee_bps(env),
crate::admin::get_treasury(env),
)
};
// Determine the protocol fee and merchant credit.
//
// Rounding rule: percentage fee is computed with integer division
// (truncating). Any remainder from the division is deterministically
// allocated to the merchant credit (i.e. merchant receives
// `charge_amount - fee`). This ensures `merchant_amount + fee_amount == charge_amount`
// exactly in the charge token and prevents 1-unit dust from remaining
// in the vault. Converted fees (fee-token overrides) are handled
// separately and do not affect the source-token accounting invariant.
let (merchant_amount, fee_amount) = if fee_bps > 0 {
if let Some(ref _t) = treasury_opt {
let fee = charge_amount * fee_bps as i128 / 10_000i128;
let net = charge_amount - fee;
(net, fee)
} else {
(charge_amount, 0i128)
}
} else {
(charge_amount, 0i128)
};
// Invariant sanity check: the split must sum exactly to the charged amount.
// If this ever fails it indicates an arithmetic bug; keep as a debug
// assertion so normal execution is unaffected in release builds.
debug_assert!(
merchant_amount + fee_amount == charge_amount,
"fee + merchant != charge_amount (fee routing invariant)"
);
credit_charge_payees(
env,
subscription_id,
&sub,
merchant_amount,
BillingChargeKind::Interval,
)?;
// Route merchant amount to sub-account if subscription has one
if let Some(ref label) = sub.sub_account_label {
crate::merchant::credit_sub_account(env, &sub.merchant, label, &sub.token, merchant_amount)?;
// Deduct from parent balance (parent earnings stay for roll-up reporting)
let parent_bal = crate::merchant::get_merchant_balance_by_token(env, &sub.merchant, &sub.token);
let new_parent_bal = crate::safe_math::safe_sub(parent_bal, merchant_amount)?;
crate::merchant::set_merchant_balance(env, &sub.merchant, &sub.token, &new_parent_bal);
}
let conversion = if fee_amount > 0 {
Some(convert_fee(env, &sub.token, fee_amount))
} else {
None
};
let should_emit_fee_event = if fee_amount > 0 {
if let Some(ref treasury) = treasury_opt {
let conv = conversion.as_ref().unwrap();
let fee_token = conv.target_token.clone();
let fee_credit_amount = conv.effective_amount;
if let Some(ref ft) = fee_token {
crate::merchant::credit_merchant_balance_for_token(
env,
treasury,
ft,
fee_credit_amount,
BillingChargeKind::Interval,
)?;
} else {
crate::merchant::credit_merchant_balance_for_token(
env,
treasury,
&sub.token,
fee_credit_amount,
BillingChargeKind::Interval,
)?;
}
Some((treasury.clone(), fee_amount))
} else {
None
}
} else {
None
};
sub.last_payment_timestamp = now.max(sub.last_payment_timestamp);
sub.lifetime_charged = safe_add(sub.lifetime_charged, charge_amount)?;
// Recover from grace period or insufficient balance on successful charge.
// Clear the grace clock so the next charge window uses fresh timestamps.
if sub.status == SubscriptionStatus::GracePeriod
|| sub.status == SubscriptionStatus::InsufficientBalance
{
transition_to(&mut sub.status, SubscriptionStatus::Active)?;
sub.grace_start_timestamp = None;
}
// Reset consecutive failure counter on any successful charge.
env.storage()
.instance()
.remove(&DataKey::ChargeFailureCounter(subscription_id));
// Check if cap is now exactly reached -- auto-cancel
let cap_reached = sub
.lifetime_cap
.map(|cap| sub.lifetime_charged >= cap)
.unwrap_or(false);
if cap_reached {
transition_to(&mut sub.status, SubscriptionStatus::Cancelled)?;
}
write_subscription(env, subscription_id, &sub);
// Emit protocol fee event after state is written
if let Some((treasury, fee)) = should_emit_fee_event {
env.events().publish(
(Symbol::new(env, "protocol_fee_charged"), subscription_id),
crate::types::ProtocolFeeChargedEvent {
subscription_id,
merchant: sub.merchant.clone(),
token: sub.token.clone(),
fee_amount: fee,
treasury,
timestamp: now,
schema_version: crate::types::EVENT_SCHEMA_VERSION,
},
);
// Emit fee conversion event when fee-token override was applied
if let Some(conv) = &conversion {
if let Some(ref target) = conv.target_token {
env.events().publish(
(Symbol::new(env, "fee_converted"), subscription_id),
FeeConvertedEvent {
subscription_id,
source_token: sub.token.clone(),
target_token: target.clone(),
original_fee_amount: fee,
converted_fee_amount: conv.effective_amount,
rate: conv.rate,
timestamp: now,
schema_version: crate::types::EVENT_SCHEMA_VERSION,
},
);
}
}
}
append_statement(
env,
subscription_id,
charge_amount,
sub.merchant.clone(),
BillingChargeKind::Interval,
next_allowed.saturating_sub(sub.interval_seconds),
now,
)?;
crate::period_snapshots::write_period_snapshot(
env,
BillingPeriodSnapshot {
subscription_id,
period_index,
period_start: next_allowed.saturating_sub(sub.interval_seconds),
period_end: now,
total_charged: charge_amount,
total_usage_units: 0,
status_flags: SNAPSHOT_FLAG_CLOSED | SNAPSHOT_FLAG_INTERVAL_CHARGED,
finalized_at: now,
},
)?;
// Record charged period and optional idempotency key
storage.set(&DataKey::ChargedPeriod(subscription_id), &period_index);
storage.set(&salt_key, &salt);
if let Some(k) = idempotency_key {
let hashed = crate::idempotency::hash_idem_key(
env,
crate::nonce::DOMAIN_CHARGE_INTERVAL,
subscription_id,
&k,
);
crate::idempotency::push_key(env, subscription_id, &hashed);
}
env.events().publish(
(TOPIC_CHARGED,),
SubscriptionChargedEvent {
subscription_id,
subscriber: sub.subscriber.clone(),
merchant: sub.merchant.clone(),
token: sub.token.clone(),
amount: charge_amount,
lifetime_charged: sub.lifetime_charged,
timestamp: now,
period_start,
period_end,
salt: salt.clone(),
schema_version: crate::types::EVENT_SCHEMA_VERSION,
},
);
if cap_reached {
if let Some(cap) = sub.lifetime_cap {
env.events().publish(
(Symbol::new(env, "lifetime_cap_reached"), subscription_id),
LifetimeCapReachedEvent {
subscription_id,
lifetime_cap: cap,
lifetime_charged: sub.lifetime_charged,
timestamp: now,
schema_version: crate::types::EVENT_SCHEMA_VERSION,
},
);
}
}
Ok(ChargeExecutionResult::Charged)
}
Err(_) => {
let grace_duration = if let Some(cfg) = admin_config {
cfg.grace_duration
} else {
crate::admin::get_grace_period(env)?
};
let previous_status = sub.status;
if sub.status == SubscriptionStatus::GracePeriod {
// Already in grace — check whether the window has expired since
// the clock first started. Keep the original grace_start_timestamp
// so a single deposit within the window restores Active.
if let Some(grace_start) = sub.grace_start_timestamp {
let grace_expires = grace_start.saturating_add(grace_duration);
if grace_duration == 0 || now >= grace_expires {
// Grace window closed — move to InsufficientBalance
transition_to(&mut sub.status, SubscriptionStatus::InsufficientBalance)?;
sub.grace_start_timestamp = None;
}
// else: stay in GracePeriod, keep clock unchanged
} else {
// Sanity: GracePeriod status without a timestamp — treat as
// fresh entry so the clock is always initialised.
sub.grace_start_timestamp = Some(now);
}
} else if grace_duration > 0 {
// First underfunded charge — enter GracePeriod and start the clock
transition_to(&mut sub.status, SubscriptionStatus::GracePeriod)?;
sub.grace_start_timestamp = Some(now);
} else {
// No grace period configured — go straight to InsufficientBalance
transition_to(&mut sub.status, SubscriptionStatus::InsufficientBalance)?;
sub.grace_start_timestamp = None;
}
write_subscription(env, subscription_id, &sub);
// Emit grace_period_entered event after state is written
if grace_duration > 0 && previous_status != SubscriptionStatus::GracePeriod {
let grace_expires_at = now.saturating_add(grace_duration);
env.events().publish(
(Symbol::new(env, "grace_period_entered"), subscription_id),
GracePeriodEnteredEvent {
subscription_id,
previous_status,
grace_expires_at,
timestamp: now,
schema_version: crate::types::EVENT_SCHEMA_VERSION,
},
);
}
let shortfall = charge_amount.saturating_sub(sub.prepaid_balance).max(0);
env.events().publish(
(Symbol::new(env, "charge_failed"), subscription_id),
SubscriptionChargeFailedEvent {
subscription_id,
merchant: sub.merchant,
required_amount: charge_amount,
available_balance: sub.prepaid_balance,
shortfall,
resulting_status: sub.status,
timestamp: now,
schema_version: crate::types::EVENT_SCHEMA_VERSION,
},
);
// Increment consecutive failure counter and auto-pause if threshold reached.
let threshold = if let Some(cfg) = admin_config {
cfg.auto_pause_threshold
} else {
crate::admin::get_auto_pause_threshold(env)
};
if threshold > 0 && sub.status == SubscriptionStatus::InsufficientBalance {
let counter_key = DataKey::ChargeFailureCounter(subscription_id);
let failures: u32 = env
.storage()
.instance()
.get(&counter_key)
.unwrap_or(0u32)
.saturating_add(1);
env.storage().instance().set(&counter_key, &failures);
if failures >= threshold {
// Re-load subscription to apply the Paused transition cleanly.
let mut sub2 =
crate::queries::get_subscription(env, subscription_id).unwrap();
if sub2.status == SubscriptionStatus::InsufficientBalance {
if transition_to(&mut sub2.status, SubscriptionStatus::Paused).is_ok() {
crate::subscription::write_subscription(env, subscription_id, &sub2);
env.storage().instance().remove(&counter_key);
env.events().publish(
(Symbol::new(env, "sub_auto_paused"), subscription_id),
SubscriptionAutoPausedEvent {
subscription_id,
consecutive_failures: failures,
threshold,
timestamp: now,
schema_version: crate::types::EVENT_SCHEMA_VERSION,
},
);
}
}
}
}
Ok(ChargeExecutionResult::InsufficientBalance)
}
}
}
/// Debit a metered `usage_amount` from a subscription's prepaid balance.
pub fn charge_usage_one(
env: &Env,
subscription_id: u32,
usage_amount: i128,
reference: String,
) -> Result<UsageChargeResult, Error> {
let mut sub = get_subscription(env, subscription_id)
.map_err(|e| charge_fail(env, subscription_id, e, 0, env.ledger().timestamp()))?;
let merchant = sub.merchant.clone();
if crate::merchant::get_merchant_paused(env, merchant.clone()) {
return Err(charge_fail(
env,
subscription_id,
Error::MerchantPaused,
0,
env.ledger().timestamp(),
));
}
// Merchant vacation guard — block charges during vacation window
let now = env.ledger().timestamp();
if crate::merchant::is_merchant_in_vacation(env, &merchant, now) {
return Err(charge_fail(
env,
subscription_id,
Error::VacationActive,
0,
now,
));
}
crate::blocklist::require_not_blocklisted(env, &sub.subscriber)
.map_err(|e| charge_fail(env, subscription_id, e, 0, env.ledger().timestamp()))?;
crate::blocklist::require_not_blocklisted(env, &sub.merchant)
.map_err(|e| charge_fail(env, subscription_id, e, 0, env.ledger().timestamp()))?;
if let Some(split_payees) = crate::subscription::get_split_payees(env, subscription_id) {
for entry in split_payees.entries.iter() {
let (payee, _) = entry;
crate::blocklist::require_not_blocklisted(env, &payee)
.map_err(|e| charge_fail(env, subscription_id, e, 0, env.ledger().timestamp()))?;
if crate::merchant::get_merchant_paused(env, payee.clone()) {
return Err(charge_fail(
env,
subscription_id,
Error::MerchantPaused,
0,
env.ledger().timestamp(),
));
}
if crate::merchant::is_merchant_in_vacation(env, &payee, now) {
return Err(charge_fail(
env,
subscription_id,
Error::VacationActive,
0,
now,
));
}
}
}
// Expiration guard
if sub.is_expired(now, env.ledger().sequence()) {
if sub.status != SubscriptionStatus::Expired {
transition_to(&mut sub.status, SubscriptionStatus::Expired)?;
write_subscription(env, subscription_id, &sub);
env.events().publish(
(Symbol::new(env, "subscription_expired"), subscription_id),
crate::types::SubscriptionExpiredEvent {
subscription_id,
timestamp: now,
schema_version: crate::types::EVENT_SCHEMA_VERSION,
},
);
}
return Err(charge_fail(
env,
subscription_id,
Error::SubscriptionExpired,
0,
now,
));
}
if let Some(cap) = sub.lifetime_cap {
if sub.lifetime_charged >= cap {
if sub.status != SubscriptionStatus::Cancelled {
transition_to(&mut sub.status, SubscriptionStatus::Cancelled)?;
write_subscription(env, subscription_id, &sub);
env.events().publish(
(Symbol::new(env, "lifetime_cap_reached"), subscription_id),
LifetimeCapReachedEvent {
subscription_id,
lifetime_cap: cap,
lifetime_charged: sub.lifetime_charged,
timestamp: now,
schema_version: crate::types::EVENT_SCHEMA_VERSION,
},
);
}
return Err(charge_fail(
env,
subscription_id,
Error::LifetimeCapReached,
usage_amount,
now,
));
}
}
if sub.status != SubscriptionStatus::Active {
return Err(charge_fail(
env,
subscription_id,
Error::NotActive,
usage_amount,
now,
));
}
if !sub.usage_enabled {
return Err(charge_fail(
env,
subscription_id,
Error::UsageNotEnabled,
usage_amount,
now,
));
}
if usage_amount <= 0 {
return Err(charge_fail(
env,
subscription_id,
Error::InvalidAmount,
usage_amount,
now,
));
}
if sub.prepaid_balance < usage_amount {
return Err(charge_fail(
env,
subscription_id,
Error::InsufficientPrepaidBalance,
usage_amount,
now,
));
}
// -- Replay protection (Reference-based) ----------------------------------
// We use the reference as a unique idempotency key for usage charges.
// If the reference has been seen before for this subscription, we return Replay.
let ref_key = (
Symbol::new(env, "usage_ref"),
subscription_id,
reference.clone(),
);
if env.storage().instance().has(&ref_key) {
env.events().publish(
(Symbol::new(env, "usage_charge_rejected"), subscription_id),
UsageChargeRejectedEvent {
subscription_id,
merchant: sub.merchant.clone(),
token: sub.token.clone(),
usage_amount,
timestamp: now,
reference,
result: UsageChargeResult::Replay,
schema_version: crate::types::EVENT_SCHEMA_VERSION,
},
);
return Ok(UsageChargeResult::Replay);
}
// -- Usage Limits & State -------------------------------------------------
let now = env.ledger().timestamp();
let limits_key = DataKey::UsageLimits(subscription_id);
let maybe_limits: Option<UsageLimits> = env.storage().instance().get(&limits_key);
if let Some(limits) = maybe_limits {
let state_key = DataKey::UsageState(subscription_id);
let mut state = env
.storage()
.instance()
.get(&state_key)
.unwrap_or(UsageState {
last_usage_timestamp: 0,
window_start_timestamp: now,
window_call_count: 0,
current_period_usage_units: 0,
period_index: now.saturating_sub(sub.start_time) / sub.interval_seconds,