-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathlib.rs
More file actions
4899 lines (4299 loc) · 185 KB
/
Copy pathlib.rs
File metadata and controls
4899 lines (4299 loc) · 185 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
#![no_std]
#![allow(clippy::too_many_arguments, clippy::inconsistent_digit_grouping)]
#[cfg(test)]
extern crate std;
mod admin;
mod batch;
#[cfg(feature = "bench")]
mod bench;
mod charge_exec;
mod errors;
mod events;
mod fee;
mod grace;
mod merchant_stats;
mod migration;
mod min_interval;
mod referral;
mod spending_limit;
mod storage;
mod subscription_count;
mod subscription_history;
mod subscription_metadata;
mod test;
mod trial;
mod upgrade;
mod validation;
mod whitelist;
use crate::errors::ContractError;
use soroban_sdk::{
contract, contractimpl, contracttype, token, Address, BytesN, Env, String, Symbol, Vec,
};
pub use batch::ChargeResult;
pub use batch::CancelResult;
pub use charge_exec::ChargeSimResult;
pub use charge_exec::PayPerUseSimResult;
// ─────────────────────────────────────────────────────────────
// Storage keys
// ─────────────────────────────────────────────────────────────
#[contracttype]
#[derive(Clone)]
pub enum DataKey {
Subscription(Address),
Token,
// Admin
Admin,
// Grace period
GracePeriod,
// Merchant whitelist
MerchantWhitelist(Address),
WhitelistEnabled,
WhitelistIndex(u32),
WhitelistIndexSize,
// Merchant freeze: blocks new subscriptions, independent of whitelist status
MerchantFrozen(Address),
MerchantFreezeReason(Address),
// Protocol fee
FeeCollector,
FeeBps,
// Feature: subscription count
ActiveCount,
// Feature: merchant revenue stats
MerchantRevenue(Address),
// Per-day merchant revenue buckets (keyed by Unix day)
MerchantRevenueDay(Address, u64),
// Index of which days have revenue buckets for a merchant
MerchantRevenueDayIndex(Address),
// Feature: daily spending limits (temporary storage)
DailyLimit(Address),
DailySpent(Address),
DayStart(Address),
// Feature: referral tracking
Referral(Address),
// Feature: state migration
SchemaVersion,
// Feature: subscription metadata labels
SubscriptionMeta(Address),
// Feature: charge history
ChargeHistory(Address),
// Feature: global volume cap
GlobalVolumeWindow,
// Feature: batch size limit override
MaxBatchSize,
// Feature: contract pause
ContractPaused,
// Feature: minimum subscription interval floor
MinInterval,
// Feature: consolidated merchant revenue history (Vec<i128>)
MerchantRevenueHistory(Address),
// Feature: subscriber index (append-only log)
SubscriberIndex(u64),
SubscriberIndexSize,
// Reverse lookup of a subscriber's slot, used to prune on cancel
SubscriberIndexSlot(Address),
// Tombstone marking a pruned (cancelled) subscriber index slot
SubscriberIndexRemoved(u64),
// Feature: per-merchant subscriber count
MerchantSubCount(Address),
// Feature: merchant index for governance/ranking
MerchantIndex(u32),
MerchantIndexSize,
MerchantKnown(Address),
// Pending admin for two-step transfer
PendingAdmin,
// Two-step auth for protocol fee
PendingFee,
// Per-merchant custom fee recipient (merchant -> destination)
MerchantFeeRecipient(Address),
// Two-step auth for grace period
PendingGracePeriod,
// Two-step auth for upgrade
PendingUpgrade,
// Feature: pause expiry (bounded pause with auto-resume)
PauseExpiry(Address),
// Feature: cumulative protocol fees collected across all merchants
TotalProtocolFees,
// Feature: configurable global hourly volume cap override
GlobalVolumeCapOverride,
// Feature: configurable min/max fee bps bounds
MinFeeBps,
MaxFeeBps,
// Feature: configurable whitelist batch size limit override
MaxWhitelistBatchSize,
}
// ─────────────────────────────────────────────────────────────
// Constants
// ─────────────────────────────────────────────────────────────
pub const SUBSCRIPTION_TTL_LEDGERS: u32 = 6307200; // ~1 year (assuming 5s blocks)
pub const MAX_BATCH_PAUSE_SUBSCRIPTIONS: u32 = 25;
/// Default cap for the admin whitelist batch entrypoints. Overridable at
/// runtime via `set_max_whitelist_batch_size`, bounded by `MAX_BATCH_SIZE_CEILING`.
pub const MAX_WHITELIST_BATCH_SIZE: u32 = 50;
/// Hard ceiling shared by every admin-configurable batch limit. Configured
/// limits are never allowed above this value, so batches stay bounded even if
/// an admin key is compromised.
pub const MAX_BATCH_SIZE_CEILING: u32 = 200;
pub const GLOBAL_MAX_VOLUME_PER_HOUR: i128 = 50_000_000_000_000; // 50 trillion stroops
pub const HOUR_IN_SECONDS: u64 = 3600;
pub const MAX_AMOUNT: i128 = 100_000_000_000;
pub const MAX_SUBSCRIPTION_AMOUNT: i128 = 100_000_000_000_000;
// ─────────────────────────────────────────────────────────────
// Data types
// ─────────────────────────────────────────────────────────────
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct Subscription {
pub merchant: Address,
pub amount: i128,
pub interval: u64,
pub last_charged: u64,
pub active: bool,
pub paused: bool, // true if paused, false otherwise
pub token: Address, // SAC token used for this subscription
pub referrer: Option<Address>, // optional referral address
pub label: Symbol, // user-assigned label for this subscription
pub trial_duration: u64, // optional trial duration in seconds
pub created_at: u64, // timestamp of subscription creation
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct SubscriptionHealth {
pub active: bool,
pub charge_due: bool,
pub within_grace: bool,
pub has_sufficient_allowance: bool,
pub is_paused: bool,
pub trial_active: bool,
pub daily_limit_set: bool,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct DailyLimitStatus {
pub limit: Option<i128>,
pub spent: i128,
pub day_start: Option<u64>,
pub remaining: Option<i128>,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct HealthReport {
pub is_healthy: bool,
pub contract_paused: bool,
pub token_configured: bool,
pub admin_configured: bool,
/// Approximate instance TTL in ledgers. On-chain, this is a hardcoded
/// lower-bound estimate (100_000) because Soroban does not expose
/// `get_ttl()` outside test builds. Do not treat as precise.
pub instance_ttl_ledgers: u32,
pub active_subscription_count: u64,
pub schema_version: u32,
pub fee_collector_set: bool,
pub global_volume_utilization_pct: u32,
/// Number of merchants with unwithdrawn revenue > 0.
pub pending_merchant_rev_count: u32,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct GlobalVolumeWindow {
pub current_window_start: u64,
pub accumulated_volume: i128,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct ProtocolStats {
pub active_count: u64,
pub fee_bps: u32,
pub fee_collector: Option<Address>,
pub grace_period: u64,
pub whitelist_enabled: bool,
pub schema_version: u32,
pub contract_paused: bool,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct ContractConfig {
pub fee_bps: u32,
pub fee_collector: Option<Address>,
pub grace_period: u64,
pub min_interval: u64,
pub max_batch_size: u32,
pub global_volume_cap: i128,
pub whitelist_enabled: bool,
pub paused: bool,
pub schema_version: u32,
}
// ─────────────────────────────────────────────────────────────
// Contract
// ─────────────────────────────────────────────────────────────
pub(crate) fn cancel_inner(env: &Env, user: &Address) -> Subscription {
let key = DataKey::Subscription(user.clone());
let mut sub: Subscription = env
.storage()
.persistent()
.get(&key)
.unwrap_or_else(|| env.panic_with_error(ContractError::NoSubscriptionFound));
sub.active = false;
env.storage().persistent().set(&key, &sub);
extend_subscription_ttl(env, user);
subscription_count::decrement(env);
subscription_count::remove_subscriber_index(env, user);
merchant_stats::decrement_subscriber_count(env, &sub.merchant);
referral::remove_referral(env, user);
sub
}
#[contract]
pub struct FlowPay;
#[contractimpl]
impl FlowPay {
/// One-time deploy entrypoint: persists the default SAC token and the
/// contract admin. Admin must authorize this invoke.
///
/// Deploy scripts (`scripts/deploy-pipeline.ts`, `scripts/testnet-setup.ts`)
/// depend on these invariants:
/// - arity is `initialize(token, admin)`
/// - a second call returns typed `ContractError::AlreadyInitialized` (code 1)
/// - success stores both token and admin, readable via `get_token` / `get_admin`
pub fn initialize(env: Env, token: Address, admin: Address) {
bump_instance_ttl(&env);
if env.storage().instance().has(&DataKey::Token) {
env.panic_with_error(ContractError::AlreadyInitialized);
}
// Authorize and persist admin before writing Token so a missing/invalid
// admin signature cannot leave a token-only (partial) initialization.
admin::initialize_admin(&env, &admin);
env.storage().instance().set(&DataKey::Token, &token);
}
/// Permissionlessly refreshes the shared instance storage TTL.
///
/// Keeper liveness probes may call this entrypoint during read- or
/// simulation-heavy periods. It does not require auth, inspect pause
/// state, transfer funds, or mutate protocol state.
pub fn bump_instance_ttl(env: Env) {
bump_instance_ttl(&env);
}
pub fn get_max_batch_size(env: Env) -> u32 {
batch::get_max_batch_size(&env)
}
pub fn set_max_batch_size(env: Env, size: u32) {
admin::require_admin(&env);
if size > MAX_BATCH_SIZE_CEILING {
env.panic_with_error(ContractError::InvalidBatchSize);
}
env.storage().instance().set(&DataKey::MaxBatchSize, &size);
}
/// Returns the batch cap applied to the admin whitelist batch entrypoints
/// (`whitelist_batch_add`, `whitelist_batch_remove`, `get_merchant_statuses`).
///
/// This is a **separate** knob from `get_max_batch_size`, which bounds the
/// charge batches — see the design note in `whitelist.rs`. Defaults to
/// `MAX_WHITELIST_BATCH_SIZE` (50).
pub fn get_max_whitelist_batch_size(env: Env) -> u32 {
whitelist::get_max_whitelist_batch_size(&env)
}
/// Admin-only: overrides the whitelist batch cap.
///
/// Panics with `InvalidBatchSize` when `size` is zero or exceeds
/// `MAX_BATCH_SIZE_CEILING` (200), so whitelist batches always stay bounded.
pub fn set_max_whitelist_batch_size(env: Env, size: u32) {
admin::require_admin(&env);
whitelist::set_max_whitelist_batch_size(&env, size);
}
pub fn get_contract_config(env: Env) -> ContractConfig {
ContractConfig {
fee_bps: fee::get_fee_bps(&env),
fee_collector: fee::get_fee_collector(&env),
grace_period: grace::get_grace_period(&env),
min_interval: min_interval::get_min_interval(&env),
max_batch_size: batch::get_max_batch_size(&env),
global_volume_cap: GLOBAL_MAX_VOLUME_PER_HOUR,
whitelist_enabled: whitelist::is_whitelist_enabled(&env),
paused: is_contract_paused(&env),
schema_version: env
.storage()
.instance()
.get(&DataKey::SchemaVersion)
.unwrap_or(1),
}
}
pub fn get_batch_charge_estimate(env: Env, users: Vec<Address>) -> Vec<ChargeResult> {
if users.len() > 200 {
env.panic_with_error(ContractError::BatchTooLarge);
}
let mut results: Vec<ChargeResult> = Vec::new(&env);
let now = env.ledger().timestamp();
let grace_period = grace::get_grace_period(&env);
for user in users.iter() {
let key = DataKey::Subscription(user.clone());
let sub_opt: Option<Subscription> = env.storage().persistent().get(&key);
let result = match sub_opt {
None => ChargeResult::NoSubscription,
Some(mut sub) => {
if sub.paused && charge_exec::try_auto_resume(&env, &user, &mut sub, now) {
// Auto-resumed — fall through to allowance check below.
// Re-run precheck on the now-active sub to be safe, then
// mirror the same allowance check as the live batch path.
match charge_exec::precheck_charge(&sub, now, grace_period) {
Err(skip) => skip,
Ok(()) => {
if !validation::has_sufficient_allowance(
&env, &user, &sub.token, sub.amount,
) {
ChargeResult::AllowanceInsufficient
} else {
ChargeResult::Charged
}
}
}
} else {
match charge_exec::precheck_charge(&sub, now, grace_period) {
Err(skip) => skip,
Ok(()) => {
if !validation::has_sufficient_allowance(
&env, &user, &sub.token, sub.amount,
) {
ChargeResult::AllowanceInsufficient
} else {
ChargeResult::Charged
}
}
}
}
}
};
results.push_back(result);
}
results
}
/// Creates or replaces a recurring subscription for `user`.
///
/// # Parameters
///
/// - `user`: Subscriber address. Must authorize the call.
/// - `merchant`: Recipient that receives recurring and pay-per-use transfers.
/// - `amount`: Amount transferred per billing period. Must be greater than zero.
/// - `interval`: Billing cadence in seconds. Must be greater than zero.
/// - `token`: Stellar Asset Contract used for this subscription.
/// - `trial_period`: Optional seconds to delay the first charge.
/// - `referrer`: Optional referrer stored for the subscriber.
///
/// # Returns
///
/// Returns nothing.
///
/// # Auth
///
/// Requires authorization from `user`.
///
/// # Errors
///
/// Panics if the contract is paused, the merchant whitelist rejects `merchant`,
/// `amount` or `interval` is zero, or the contract allowance is below `amount`.
///
/// # Side Effects
///
/// Stores the subscription, refreshes its TTL, updates active subscription
/// count and referral storage, and emits `subscribed`.
pub fn subscribe(
env: Env,
user: Address,
merchant: Address,
amount: i128,
interval: u64,
token: Address,
trial_period: Option<u64>,
referrer: Option<Address>,
) {
subscribe_inner(
&env,
user,
merchant,
amount,
interval,
token,
trial_period,
referrer,
);
}
pub fn subscribe_with_metadata(
env: Env,
user: Address,
merchant: Address,
amount: i128,
interval: u64,
token: Address,
trial_period: Option<u64>,
referrer: Option<Address>,
label: String,
) {
if label.len() > 64 {
env.panic_with_error(ContractError::MetadataLabelTooLong);
}
subscribe_inner(
&env,
user.clone(),
merchant,
amount,
interval,
token,
trial_period,
referrer,
);
let _ = subscription_metadata::set_metadata(&env, &user, label);
}
/// Charges the next due recurring payment for `user`.
///
/// # Parameters
///
/// - `user`: Subscriber whose active subscription should be charged.
///
/// # Returns
///
/// Returns nothing.
///
/// # Auth
///
/// No subscriber signature is required. The contract spends through the
/// previously granted token allowance.
///
/// # Errors
///
/// Panics if the contract is paused, no subscription exists, the subscription
/// is inactive or paused, the interval has not elapsed, the grace period has
/// elapsed, or token transfer authorization/allowance is insufficient.
///
/// # Side Effects
///
/// Transfers `amount` from `user` to the merchant, records merchant revenue
/// and charge history, refreshes subscription TTL, updates `last_charged`,
/// and emits `charged`.
pub fn charge(env: Env, user: Address) {
bump_instance_ttl(&env);
ensure_contract_not_paused(&env);
let key = DataKey::Subscription(user.clone());
let mut sub: Subscription = env
.storage()
.persistent()
.get(&key)
.unwrap_or_else(|| env.panic_with_error(ContractError::NoSubscriptionFound));
let now = env.ledger().timestamp();
if sub.paused {
if charge_exec::try_auto_resume(&env, &user, &mut sub, now) {
// Auto-resumed; fall through to charge immediately
} else {
env.panic_with_error(ContractError::SubscriptionPaused);
}
} else if !sub.active {
env.panic_with_error(ContractError::SubscriptionInactive);
}
let next = charge_exec::compute_next_charge_at(&sub)
.unwrap_or_else(|| env.panic_with_error(ContractError::SubscriptionPaused));
if now < next {
env.panic_with_error(ContractError::IntervalNotElapsed);
}
let grace_period = grace::get_grace_period(&env);
if grace_period > 0 && now > next + grace_period {
env.panic_with_error(ContractError::GracePeriodElapsed);
}
charge_exec::execute_charge(&env, &user, &key, &mut sub, now);
}
pub fn extend_subscription_ttl(env: Env, user: Address) {
extend_subscription_ttl(&env, &user);
}
/// Permissionlessly refreshes the TTL of any subscription entry.
/// Returns early (no-op) if no subscription exists for `user`.
/// No auth required — safe for keeper bots to call for dormant subscribers.
pub fn bump_subscription(env: Env, user: Address) {
extend_subscription_ttl(&env, &user);
}
/// Bumps TTL for multiple subscription entries in a single call.
/// Returns a list of addresses whose TTLs were actually extended.
pub fn batch_extend_subscription_ttl(env: Env, users: Vec<Address>) -> Vec<Address> {
batch::batch_extend_subscription_ttl(&env, users)
}
/// Dry-run simulation of a charge call. Returns ChargeSimResult variant indicating
/// whether charge would succeed or the reason it would fail.
pub fn simulate_charge(env: Env, user: Address) -> ChargeSimResult {
charge_exec::simulate_charge(&env, user)
}
/// Dry-run simulation of a `pay_per_use` call. Returns a PayPerUseSimResult
/// variant indicating whether the pay-per-use would succeed or the reason it
/// would fail (contract paused, invalid/inactive/paused subscription, daily
/// limit exceeded, or insufficient allowance). Performs no state writes.
pub fn simulate_pay_per_use(env: Env, user: Address, amount: i128) -> PayPerUseSimResult {
charge_exec::simulate_pay_per_use(&env, user, amount, None)
}
/// Dry-run simulation of a `pay_per_use_to` call. Mirrors
/// `simulate_pay_per_use` but also validates the `recipient` (contract-address
/// self-reference and merchant whitelist). Performs no state writes.
pub fn simulate_pay_per_use_to(
env: Env,
user: Address,
amount: i128,
recipient: Address,
) -> PayPerUseSimResult {
charge_exec::simulate_pay_per_use(&env, user, amount, Some(recipient))
}
/// Executes an immediate pay-per-use charge for an active subscription.
///
/// # Parameters
///
/// - `user`: Subscriber address. Must authorize the call.
/// - `amount`: One-time amount to transfer. Must be greater than zero.
///
/// # Returns
///
/// Returns nothing.
///
/// # Auth
///
/// Requires authorization from `user`.
///
/// # Errors
///
/// Panics if the contract is paused, `amount` is zero, no subscription
/// exists, the subscription is inactive or paused, the daily spending limit
/// would be exceeded, or token transfer authorization/allowance is insufficient.
///
/// # Side Effects
///
/// Transfers `amount` to the subscription merchant, updates merchant revenue
/// and daily spend tracking, and emits `pay_per_use`.
pub fn pay_per_use(env: Env, user: Address, amount: i128) {
bump_instance_ttl(&env);
pay_per_use_inner(&env, user, amount, None);
}
/// Executes an immediate pay-per-use charge for an active subscription,
/// routing payment to `recipient` instead of the subscription's merchant.
///
/// # Parameters
///
/// - `user`: Subscriber address. Must authorize the call.
/// - `amount`: One-time amount to transfer. Must be greater than zero.
/// - `recipient`: Address that receives the net payment instead of `sub.merchant`.
///
/// # Auth
///
/// Requires authorization from `user`.
///
/// # Errors
///
/// Same as `pay_per_use`, plus panics if the merchant whitelist is enabled
/// and `recipient` is not whitelisted.
///
/// # Side Effects
///
/// Transfers `amount` to `recipient`, updates `recipient`'s merchant revenue
/// and the user's daily spend tracking (shared with `pay_per_use`), and
/// emits `pay_per_use` with `recipient` in place of `sub.merchant`.
pub fn pay_per_use_to(env: Env, user: Address, amount: i128, recipient: Address) {
pay_per_use_inner(&env, user, amount, Some(recipient));
}
pub fn get_day_start(env: Env, user: Address) -> Option<u64> {
spending_limit::get_day_start(&env, &user)
}
/// Cancels `user`'s active subscription.
///
/// # Parameters
///
/// - `user`: Subscriber address. Must authorize the call.
///
/// # Returns
///
/// Returns nothing.
///
/// # Auth
///
/// Requires authorization from `user`.
///
/// # Errors
///
/// Panics if no subscription exists for `user`.
///
/// # Side Effects
///
/// Marks the subscription inactive, decrements active subscription count, and
/// emits `cancelled`.
pub fn cancel(env: Env, user: Address) {
bump_instance_ttl(&env);
user.require_auth();
cancel_inner(&env, &user);
events::publish_cancelled(&env, &user);
}
/// Extends an active subscription's trial period (or delays next charge)
/// by adding `additional_seconds` to its `last_charged` timestamp.
///
/// # Panics
/// - If `additional_seconds` is 0 (`IntervalMustBePositive`).
/// - If the subscription is cancelled/inactive (`SubscriptionInactive`).
/// - If the subscription is paused (`SubscriptionPaused`).
/// - If the subscription doesn't exist (`NoSubscriptionFound`).
/// - If `last_charged + additional_seconds` overflows `u64` (`ArithmeticOverflow`).
pub fn extend_trial(env: Env, user: Address, additional_seconds: u64) {
bump_instance_ttl(&env);
user.require_auth();
trial::extend_trial(&env, &user, additional_seconds);
}
pub fn cancel_and_refund_prorated(env: Env, user: Address, merchant: Address) {
bump_instance_ttl(&env);
user.require_auth();
merchant.require_auth();
let key = DataKey::Subscription(user.clone());
let sub: Subscription = env
.storage()
.persistent()
.get(&key)
.unwrap_or_else(|| env.panic_with_error(ContractError::NoSubscriptionFound));
if !sub.active {
env.panic_with_error(ContractError::SubscriptionInactive);
}
if sub.paused {
env.panic_with_error(ContractError::SubscriptionPaused);
}
if sub.merchant != merchant {
env.panic_with_error(ContractError::RefundMerchantMismatch);
}
let now = env.ledger().timestamp();
let elapsed = now.saturating_sub(sub.last_charged);
let remaining = sub.interval.saturating_sub(elapsed);
if sub.interval == 0 {
env.panic_with_error(ContractError::IntervalMustBePositive);
}
let refund = (sub.amount * i128::from(remaining)) / i128::from(sub.interval);
if refund <= 0 {
env.panic_with_error(ContractError::RefundAmountMustBePositive);
}
// Refunds are merchant-funded; no protocol escrow is used. Validate the
// source balance before the transfer so an underfunded merchant cannot
// reach an opaque SAC failure or a partial cancellation.
let token_client = token::Client::new(&env, &sub.token);
if token_client.balance(&merchant) < refund {
env.panic_with_error(ContractError::InsufficientMerchantBalance);
}
token_client.transfer(&merchant, &user, &refund);
cancel_inner(&env, &user);
events::publish_cancelled_with_refund(&env, &user, refund);
}
/// Pauses `user`'s subscription without cancelling it.
///
/// # Parameters
///
/// - `user`: Subscriber address. Must authorize the call.
///
/// # Returns
///
/// Returns nothing.
///
/// # Auth
///
/// Requires authorization from `user`.
///
/// # Errors
///
/// Panics if no subscription exists or the subscription is inactive.
///
/// # Side Effects
///
/// Sets the subscription `paused` flag and emits `paused`.
pub fn pause(env: Env, user: Address) {
bump_instance_ttl(&env);
user.require_auth();
let key = DataKey::Subscription(user.clone());
let mut sub: Subscription = env
.storage()
.persistent()
.get(&key)
.unwrap_or_else(|| env.panic_with_error(ContractError::NoSubscriptionFound));
if !sub.active {
env.panic_with_error(ContractError::SubscriptionInactive);
}
sub.paused = true;
env.storage().persistent().set(&key, &sub);
extend_subscription_ttl(&env, &user);
storage::set_pause_expiry(&env, &user, u64::MAX);
events::publish_paused(&env, &user);
}
/// Pauses `user`'s subscription until a specific expiry timestamp.
/// The subscription will auto-resume via `charge` or `batch_charge`
/// when the ledger timestamp reaches `expiry`.
pub fn pause_until(env: Env, user: Address, expiry: u64) {
bump_instance_ttl(&env);
user.require_auth();
let now = env.ledger().timestamp();
if expiry <= now {
env.panic_with_error(ContractError::InvalidPauseExpiry);
}
let key = DataKey::Subscription(user.clone());
let mut sub: Subscription = env
.storage()
.persistent()
.get(&key)
.unwrap_or_else(|| env.panic_with_error(ContractError::NoSubscriptionFound));
if !sub.active {
env.panic_with_error(ContractError::SubscriptionNotActive);
}
sub.paused = true;
sub.active = false;
env.storage().persistent().set(&key, &sub);
storage::set_pause_expiry(&env, &user, expiry);
events::publish_paused(&env, &user);
}
/// Resumes `user`'s paused subscription.
///
/// # Parameters
///
/// - `user`: Subscriber address. Must authorize the call.
///
/// # Returns
///
/// Returns nothing.
///
/// # Auth
///
/// Requires authorization from `user`.
///
/// # Errors
///
/// Panics if no subscription exists or the subscription is inactive.
///
/// # Side Effects
///
/// Clears the subscription `paused` flag and emits `resumed`.
pub fn resume(env: Env, user: Address) {
bump_instance_ttl(&env);
user.require_auth();
let key = DataKey::Subscription(user.clone());
let mut sub: Subscription = env
.storage()
.persistent()
.get(&key)
.unwrap_or_else(|| env.panic_with_error(ContractError::NoSubscriptionFound));
// Reject cancelled subscriptions (inactive and not paused).
// pause_until sets active=false while paused=true; those must still be resumable.
if !sub.active && !sub.paused {
env.panic_with_error(ContractError::SubscriptionInactive);
}
// Recovery rule: if the grace window has closed the subscription is no longer
// chargeable. Resume is rejected to prevent false recoverability signals.
// The only allowed exit is cancel(); re-subscribe to restore chargeability.
// See docs/SUBSCRIBER-LIFECYCLE.md.
if grace::is_grace_lapsed(&env, &sub) {
env.panic_with_error(ContractError::ResumeGraceLapsed);
}
sub.paused = false;
sub.active = true;
env.storage().persistent().set(&key, &sub);
extend_subscription_ttl(&env, &user);
storage::clear_pause_expiry(&env, &user);
events::publish_resumed(&env, &user);
}
/// Batch-pauses subscriptions for a list of user addresses.
///
/// Admin-only emergency tool to freeze groups of related accounts in a
/// single transaction. The vector is capped at 25 items to stay within
/// ledger size constraints.
///
/// # Parameters
///
/// - `users`: List of subscriber addresses to pause. Max 25 items.
///
/// # Returns
///
/// Returns nothing.
///
/// # Auth
///
/// Requires authorization from the contract admin.
///
/// # Side Effects
///
/// For every valid active subscription, sets `paused = true`, persists the
/// update, extends the subscription TTL, and emits a `subscription_paused`
/// event. Invalid (non-existent) and already-paused entries are silently
/// skipped. The contract pause flag does **not** block this call.
pub fn batch_pause_subscriptions(env: Env, users: Vec<Address>) {
admin::require_admin(&env);
let max_batch: u32 = 25;
if users.len() > max_batch {
env.panic_with_error(ContractError::BatchTooLarge);
}
for user in users.iter() {
let key = DataKey::Subscription(user.clone());
let sub_opt: Option<Subscription> = env.storage().persistent().get(&key);
if let Some(mut sub) = sub_opt {
if !sub.active || sub.paused {
if sub.paused {
extend_subscription_ttl(&env, &user);
}
continue;
}
sub.paused = true;
env.storage().persistent().set(&key, &sub);
extend_subscription_ttl(&env, &user);
events::publish_subscription_paused(&env, &user);
}
}
}
pub fn batch_cancel(env: Env, users: Vec<Address>) -> Vec<CancelResult> {
admin::require_admin(&env);
batch::batch_cancel(&env, users)
}
/// Proposes a new admin (step 1 of two-step transfer).
/// The proposed address must call `accept_admin()` to complete the transfer.
///
/// # Auth
///
/// Requires authorization from the current admin.
pub fn transfer_admin(env: Env, new_admin: Address) {
admin::transfer_admin(&env, &new_admin);
}
/// Accepts a pending admin transfer (step 2 of two-step transfer).
/// Emits `admin_transferred` and replaces the active admin.
///
/// # Auth
///
/// Requires authorization from the pending (new) admin.
pub fn accept_admin(env: Env) {
admin::accept_admin(&env);
}
/// Returns the proposed admin address awaiting `accept_admin()`, or
/// `None` if there is no pending transfer.
pub fn get_pending_admin(env: Env) -> Option<Address> {
admin::get_pending_admin(&env)
}
/// Returns whether the contract is currently paused.
pub fn is_contract_paused(env: Env) -> bool {
is_contract_paused(&env)
}
/// Returns the current admin address, or `None` if no admin has been set.
pub fn get_admin(env: Env) -> Option<Address> {
storage::get_admin_optional(&env)
}
/// Returns the default token address set during `initialize()`, or `None` if not initialized.
pub fn get_token(env: Env) -> Option<Address> {
storage::get_token(&env)
}
pub fn propose_upgrade(env: Env, new_wasm_hash: BytesN<32>) {
upgrade::propose_upgrade(&env, new_wasm_hash);
}
pub fn cancel_pending_upgrade(env: Env) {
upgrade::cancel_pending_upgrade(&env);
}
pub fn commit_upgrade(env: Env) {
upgrade::commit_upgrade(&env);
}
/// Returns the pending WASM hash queued for the two-step upgrade flow,
/// or `None` if no upgrade has been proposed.
///
/// # Auth
///
/// None required — view-only read.
///
/// # Storage
///
/// Reads `DataKey::PendingUpgrade` from temporary storage (TTL ~24 h).
/// Returns `None` when the key has expired or was never set.
pub fn get_pending_upgrade(env: Env) -> Option<BytesN<32>> {