forked from Parashield-Protocol/parashield-contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1818 lines (1583 loc) · 76.2 KB
/
Copy pathlib.rs
File metadata and controls
1818 lines (1583 loc) · 76.2 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
// Address/state validation must fail with a typed contract error so callers
// can match on it programmatically, never with a raw panic! and a string
// message.
#![deny(clippy::panic)]
//! Parashield Claims Processor
//!
//! Evaluates whether a policy's trigger condition has been met by querying the
//! Oracle Verifier, then instructs the Policy Engine to pay out or expire.
//!
//! Two processing paths
//! ─────────────────────
//! 1. `submit_claim` + `process_claim` — user or keeper manually triggers evaluation.
//! 2. `auto_process` — keeper-triggered; evaluates without a prior user submission.
//! This is the primary path for parametric insurance (no claim form needed).
//!
//! Idempotency
//! ────────────
//! Once a policy is Claimed or Expired, further process/auto_process calls
//! return the appropriate ClaimResult without writing again.
#![no_std]
extern crate alloc;
use alloc::string::ToString;
use soroban_sdk::{
contract, contractimpl, contracttype, contracterror, panic_with_error,
Address, BytesN, Env, Vec, Symbol,
};
pub mod types;
pub use types::*;
// ─── Cross-contract client interfaces ────────────────────────────────────────
#[soroban_sdk::contractclient(name = "RiskPoolClient")]
trait IRiskPool {
fn release_for_claim(env: Env, caller: Address, policy_id: u128);
fn release_for_expiry(env: Env, caller: Address, policy_id: u128);
}
#[soroban_sdk::contractclient(name = "PolicyEngineClient")]
trait IPolicyEngine {
fn get_policy(env: Env, policy_id: u128) -> parashield_policy_engine::Policy;
fn pay_claim(env: Env, caller: Address, policy_id: u128);
fn expire_policy(env: Env, caller: Address, policy_id: u128);
}
#[soroban_sdk::contractclient(name = "OracleVerifierClient")]
trait IOracleVerifier {
fn verify_trigger_fresh(
env: Env,
data_type: soroban_sdk::Symbol,
key: soroban_sdk::Symbol,
condition: parashield_oracle_verifier::TriggerCondition,
max_age_seconds: u64,
) -> bool;
}
// ─── Storage TTL ──────────────────────────────────────────────────────────────
/// Extend a persistent entry's TTL once it has fewer than ~30 days of life left
/// (at ~5s/ledger).
// Issue #342: kept in sync by hand across all 5 contracts (governance-dao,
// risk-pool, policy-engine, oracle-verifier, claims-processor) — extracting
// to a shared crate is a real follow-up, not done here to avoid touching
// every contract's Cargo.toml in one pass.
const TTL_THRESHOLD: u32 = 518_400;
/// Extend persistent entries out to ~1 year (at ~5s/ledger) so pending claims
/// survive long enough to be processed.
const TTL_EXTEND_TO: u32 = 6_312_000;
/// Grace period between an admin transfer being fully proposed/approved and the
/// proposed admin being able to `accept_admin` (issue #356). Hand-synced across
/// the 4 contracts that expose admin rotation (policy-engine, risk-pool,
/// oracle-verifier, claims-processor).
const ADMIN_TRANSFER_TIMELOCK: u64 = 48 * 60 * 60;
// ─── Batch processing ─────────────────────────────────────────────────────────
/// Hard ceiling on how many claims a single `batch_auto_process` call may
/// settle.
///
/// Each claim in the batch costs an oracle read plus a cross-contract call into
/// the policy-engine, so an unbounded batch would exhaust Soroban's per
/// transaction instruction budget and fail with an opaque gas error — taking
/// the whole batch down with it. Capping keeps every call within budget;
/// callers with a longer queue simply invoke the function again.
pub const MAX_BATCH_SIZE: u32 = 50;
// ─── Storage keys ─────────────────────────────────────────────────────────────
#[contracttype]
enum StorageKey {
Initialized,
Admin,
PolicyEngine,
RiskPool,
OracleVerifier,
StalenessThreshold, // u64 — max acceptable oracle data age in seconds
Claim(u128),
PolicyClaim(u128), // policy_id → claim_id (one claim per policy)
NextClaimId,
PendingClaims, // Vec<u128>
Keeper(Address), // keeper whitelist: address → bool
Paused, // bool — emergency pause state
/// Proposed next admin awaiting `accept_admin` (issue #356).
PendingAdmin,
/// Ledger timestamp (u64) at which `PendingAdmin` was set, used to enforce
/// `ADMIN_TRANSFER_TIMELOCK` before `accept_admin` succeeds.
PendingAdminSince,
/// A pending admin-transfer proposal awaiting guardian approvals.
PendingAdminChange,
/// Contract version (u32) for storage migration tracking
Version,
/// Guardian addresses authorized to approve critical actions (Vec<Address>).
Guardians,
/// Number of guardian approvals required to execute a critical action
/// (u32). 0 means guardian multisig is disabled (admin acts alone).
GuardianThreshold,
/// A pending, not-yet-executed contract upgrade awaiting guardian approvals.
PendingUpgrade,
/// Seconds a claim may sit Pending before it can be escalated (u64).
EscalationThreshold,
/// Maximum seconds after a policy's `end_time` during which a claim may
/// still be submitted for the triggering event (u64). `0` means a claim
/// can only be filed while the policy is Active (behaves as before).
ClaimDeadline,
/// Configurable delay in seconds between claim approval and payout (u64).
/// 0 = immediate payout (default behavior).
PayoutDelay,
/// Identity attestation requirement: product_id → Symbol (id_type required).
IdentityRequirement(u128),
}
// ─── Errors ───────────────────────────────────────────────────────────────────
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum Error {
AlreadyInitialized = 1,
NotInitialized = 2,
Unauthorized = 3,
ClaimNotFound = 4,
PolicyNotActive = 5,
AlreadyClaimed = 6,
AlreadyProcessed = 7,
InvalidAddress = 8,
Paused = 9,
PolicyExpired = 10,
InvalidVersion = 11,
NotGuardian = 12,
AlreadyApprovedAction = 13,
NoPendingUpgrade = 14,
InvalidThreshold = 15,
AdminTimelockNotExpired = 16,
NotEscalatable = 17,
InvalidThresholdValue = 18,
/// A `submit_claim` arrived after `end_time + claim_deadline` had elapsed,
/// so the window to file a claim for the triggering event has closed.
ClaimDeadlinePassed = 19,
/// Payout delay has not yet elapsed — the claim cannot be settled now.
PayoutDelayNotElapsed = 20,
/// Identity verification required for this claim category but not verified.
IdentityVerificationRequired = 21,
}
/// Approximate Stellar ledger close time in seconds, used to convert
/// wall-clock TTL windows into ledger counts for `extend_ttl`.
const LEDGER_SECONDS: u64 = 5;
/// Claim and PolicyClaim entries must survive from submission until the
/// claim is finally settled (Paid/Rejected) — including disputes, which have
/// no automatic timeout. 365 days comfortably covers policy-engine's longest
/// policy durations plus dispute-resolution time; capped to the network's
/// max TTL at call time so `extend_ttl` never panics.
const CLAIM_RETENTION_SECONDS: u64 = 365 * 24 * 60 * 60;
/// How long a claim may sit Pending before anyone can escalate it, when the
/// admin has not configured a threshold.
///
/// Seven days is long enough that ordinary keeper latency, oracle data still
/// arriving, or a quiet weekend do not trip it, and short enough that a
/// claimant is not left indefinitely without recourse. It is the point past
/// which "still processing" stops being a plausible explanation.
const DEFAULT_ESCALATION_THRESHOLD: u64 = 7 * 24 * 60 * 60;
/// Shortest escalation threshold an admin may configure (1 hour). A near-zero
/// threshold would let every claim be escalated on submission, which turns the
/// signal into noise and defeats the purpose of having one.
const MIN_ESCALATION_THRESHOLD: u64 = 60 * 60;
/// Default window after a policy's `end_time` during which a claim may still be
/// submitted. 30 days is long enough to cover keeper latency, oracle data
/// still arriving, or a claimant simply not noticing the trigger immediately,
/// while still putting a firm upper bound on how long a claim can be filed
/// after the event it relates to (issue #386).
const DEFAULT_CLAIM_DEADLINE: u64 = 30 * 24 * 60 * 60;
// ─── Contract ─────────────────────────────────────────────────────────────────
#[contract]
pub struct ClaimsProcessor;
#[contractimpl]
impl ClaimsProcessor {
// ── Lifecycle ────────────────────────────────────────────────────────────
/// One-time initialisation. Links the contract to `policy_engine`, `risk_pool`, and
/// `oracle_verifier`. `staleness_threshold` is the maximum age in seconds for oracle
/// data to be considered fresh. Panics with `AlreadyInitialized` on a second call.
pub fn initialize(
env: Env,
admin: Address,
policy_engine: Address,
risk_pool: Address,
oracle_verifier: Address,
staleness_threshold: u64,
) {
if env.storage().instance().has(&StorageKey::Initialized) {
panic_with_error!(&env, Error::AlreadyInitialized);
}
admin.require_auth();
Self::validate_stellar_address(&env, &admin);
Self::validate_stellar_address(&env, &policy_engine);
Self::validate_stellar_address(&env, &risk_pool);
Self::validate_stellar_address(&env, &oracle_verifier);
env.storage().instance().set(&StorageKey::Initialized, &true);
env.storage().instance().set(&StorageKey::Admin, &admin);
env.storage().instance().set(&StorageKey::PolicyEngine, &policy_engine);
env.storage().instance().set(&StorageKey::RiskPool, &risk_pool);
env.storage().instance().set(&StorageKey::OracleVerifier, &oracle_verifier);
env.storage().instance().set(&StorageKey::StalenessThreshold, &staleness_threshold);
env.storage().instance().set(&StorageKey::NextClaimId, &1u128);
env.storage().instance().set(&StorageKey::PendingClaims, &Vec::<u128>::new(&env));
env.storage().instance().set(&StorageKey::Paused, &false);
env.storage().instance().set(&StorageKey::ClaimDeadline, &DEFAULT_CLAIM_DEADLINE);
env.events().publish(
(Symbol::new(&env, "initialized"),),
Initialized {
admin: admin.clone(),
policy_engine: policy_engine.clone(),
risk_pool: risk_pool.clone(),
oracle_verifier: oracle_verifier.clone(),
staleness_threshold,
},
);
}
// ── Keeper Registry ──────────────────────────────────────────────────────
/// Admin-only: authorize `keeper` to call process_claim / auto_process /
/// batch_auto_process. Without this, no address can settle claims.
pub fn add_keeper(env: Env, admin: Address, keeper: Address) {
Self::require_admin(&env, &admin);
env.storage().persistent().set(&StorageKey::Keeper(keeper.clone()), &true);
env.storage().persistent().extend_ttl(&StorageKey::Keeper(keeper.clone()), TTL_THRESHOLD, TTL_EXTEND_TO);
env.events().publish(
(Symbol::new(&env, "keeper_added"),),
keeper,
);
}
/// Admin-only: revoke a keeper's settlement authority.
pub fn remove_keeper(env: Env, admin: Address, keeper: Address) {
Self::require_admin(&env, &admin);
env.storage().persistent().remove(&StorageKey::Keeper(keeper.clone()));
env.events().publish(
(Symbol::new(&env, "keeper_removed"),),
keeper,
);
}
/// Whether `keeper` is currently authorized to settle claims.
pub fn is_keeper(env: Env, keeper: Address) -> bool {
env.storage().persistent()
.get(&StorageKey::Keeper(keeper))
.unwrap_or(false)
}
// ── Claim Submission ─────────────────────────────────────────────────────
/// Manually submit a claim for a policy. Returns the new claim ID.
/// Only the policyholder may submit; only one claim per policy.
pub fn submit_claim(env: Env, claimant: Address, policy_id: u128) -> u128 {
claimant.require_auth();
Self::require_not_paused(&env);
// Guard: one claim per policy
if env.storage().persistent().has(&StorageKey::PolicyClaim(policy_id)) {
panic_with_error!(&env, Error::AlreadyClaimed);
}
// Verify policy is Active via Policy Engine
let policy_engine: Address = env.storage().instance()
.get(&StorageKey::PolicyEngine)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let policy = PolicyEngineClient::new(&env, &policy_engine)
.get_policy(&policy_id);
if policy.policyholder != claimant {
panic_with_error!(&env, Error::Unauthorized);
}
if policy.status != parashield_policy_engine::PolicyStatus::Active {
panic_with_error!(&env, Error::PolicyNotActive);
}
// Guard: reject expired policies even if status hasn't been updated yet.
// A direct contract caller could bypass the backend's status check, so
// we verify end_time at the contract level. A claim may still be filed
// for a bounded window after the policy ends (`claim_deadline`); once
// that window closes the triggering event is too old to act on and the
// submission is rejected (issue #386).
let now = env.ledger().timestamp();
if policy.end_time > 0 {
let cutoff = policy.end_time.saturating_add(Self::claim_deadline(&env));
if now > cutoff {
panic_with_error!(&env, Error::ClaimDeadlinePassed);
}
}
let claim_id = Self::next_claim_id(&env);
let claim = Claim {
id: claim_id,
policy_id,
claimant: claimant.clone(),
coverage_amount: policy.coverage_amount,
observed_value: None,
trigger_met: false,
status: ClaimStatus::Pending,
submitted_at: now,
processed_at: None,
dispute_reason: None,
paid_amount: None,
partial_payout_bps: None,
installments: None,
payout_ready_at: None,
};
env.storage().persistent().set(&StorageKey::Claim(claim_id), &claim);
env.storage().persistent().extend_ttl(&StorageKey::Claim(claim_id), TTL_THRESHOLD, TTL_EXTEND_TO);
env.storage().persistent().set(&StorageKey::PolicyClaim(policy_id), &claim_id);
env.storage().persistent().extend_ttl(&StorageKey::PolicyClaim(policy_id), TTL_THRESHOLD, TTL_EXTEND_TO);
let mut pending: Vec<u128> = env.storage().instance()
.get(&StorageKey::PendingClaims).unwrap_or_else(|| Vec::new(&env));
pending.push_back(claim_id);
env.storage().instance().set(&StorageKey::PendingClaims, &pending);
env.events().publish(
(Symbol::new(&env, "claim_submitted"),),
ClaimSubmitted {
claim_id,
policy_id,
claimant,
coverage_amount: policy.coverage_amount,
},
);
claim_id
}
/// Submit multiple claims in a single transaction up to MAX_BATCH_SIZE.
pub fn batch_submit_claims(env: Env, claimant: Address, policy_ids: Vec<u128>) -> Vec<u128> {
claimant.require_auth();
Self::require_not_paused(&env);
let mut claim_ids = Vec::new(&env);
let count = if policy_ids.len() > MAX_BATCH_SIZE {
MAX_BATCH_SIZE
} else {
policy_ids.len()
};
for i in 0..count {
let pid = policy_ids.get_unchecked(i);
let cid = Self::submit_claim(env.clone(), claimant.clone(), pid);
claim_ids.push_back(cid);
}
env.events().publish(
(Symbol::new(&env, "batch_claims_submitted"),),
BatchClaimsSubmitted {
claimant,
count,
},
);
claim_ids
}
/// Process an existing pending claim. Reads oracle data and pays out or rejects.
///
/// `partial_payout_bps` is an optional payout ratio in basis points (0-10000).
/// - `None` or `Some(10000)` → full coverage payment (default behavior).
/// - `Some(bps)` where bps < 10000 → proportional partial payment, e.g. `Some(5000)` pays 50%.
pub fn process_claim(
env: Env,
keeper: Address,
claim_id: u128,
partial_payout_bps: Option<u32>,
) -> ClaimResult {
Self::require_keeper(&env, &keeper);
Self::require_not_paused(&env);
let mut claim: Claim = env.storage().persistent()
.get(&StorageKey::Claim(claim_id))
.unwrap_or_else(|| panic_with_error!(&env, Error::ClaimNotFound));
if claim.status != ClaimStatus::Pending {
return ClaimResult::AlreadyProcessed;
}
let policy_engine: Address = env.storage().instance()
.get(&StorageKey::PolicyEngine)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let policy = PolicyEngineClient::new(&env, &policy_engine)
.get_policy(&claim.policy_id);
Self::evaluate_and_settle(&env, &mut claim, &policy, partial_payout_bps)
}
/// Process multiple existing claims in a single transaction up to MAX_BATCH_SIZE.
pub fn batch_process_claims(
env: Env,
keeper: Address,
claim_ids: Vec<u128>,
partial_payout_bps: Option<u32>,
) -> Vec<(u128, ClaimResult)> {
Self::require_keeper(&env, &keeper);
Self::require_not_paused(&env);
let mut results = Vec::new(&env);
let count = if claim_ids.len() > MAX_BATCH_SIZE {
MAX_BATCH_SIZE
} else {
claim_ids.len()
};
for i in 0..count {
let cid = claim_ids.get_unchecked(i);
let res = Self::process_claim(env.clone(), keeper.clone(), cid, partial_payout_bps);
results.push_back((cid, res));
}
env.events().publish(
(Symbol::new(&env, "batch_claims_processed"),),
BatchClaimsProcessed {
keeper,
count,
},
);
results
}
/// Keeper-triggered automatic processing — no prior `submit_claim` needed.
/// This is the primary flow for parametric insurance.
/// Returns AlreadyClaimed / Expired idempotently if policy is already settled.
///
/// `partial_payout_bps` — see `process_claim` for details.
pub fn auto_process(
env: Env,
keeper: Address,
policy_id: u128,
partial_payout_bps: Option<u32>,
) -> ClaimResult {
Self::require_keeper(&env, &keeper);
Self::require_not_paused(&env);
// ─── IDEMPOTENCY GUARD ───
// Check if an evaluation record already exists for this policy in our storage
if env.storage().persistent().has(&StorageKey::PolicyClaim(policy_id)) {
let existing_claim_id: u128 = env.storage().persistent()
.get(&StorageKey::PolicyClaim(policy_id)).unwrap();
if let Some(existing_claim) = env.storage().persistent().get::<StorageKey, Claim>(&StorageKey::Claim(existing_claim_id)) {
if existing_claim.status != ClaimStatus::Pending {
return ClaimResult::AlreadyProcessed;
}
}
}
let policy_engine: Address = env.storage().instance()
.get(&StorageKey::PolicyEngine)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let policy = PolicyEngineClient::new(&env, &policy_engine)
.get_policy(&policy_id);
// Idempotency: check current policy status from down-stream contract
match policy.status {
parashield_policy_engine::PolicyStatus::Claimed => return ClaimResult::AlreadyClaimed,
parashield_policy_engine::PolicyStatus::Expired => return ClaimResult::Expired,
parashield_policy_engine::PolicyStatus::Cancelled => return ClaimResult::PolicyNotActive,
parashield_policy_engine::PolicyStatus::Active => {}
}
// Check if policy has expired with no trigger
let now = env.ledger().timestamp();
if now > policy.end_time {
let risk_pool: Address = env.storage().instance()
.get(&StorageKey::RiskPool)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
PolicyEngineClient::new(&env, &policy_engine)
.expire_policy(&env.current_contract_address(), &policy_id);
// Atomic lock release, mirroring the payout path: expiring a policy
// and freeing its earmarked capital happen in one transaction, so a
// crash between the two cannot strand liquidity in the pool. If the
// release fails the whole call reverts and the policy stays Active.
RiskPoolClient::new(&env, &risk_pool)
.release_for_expiry(&env.current_contract_address(), &policy_id);
return ClaimResult::Expired;
}
// Create or get the internal claim record
let claim_id = if env.storage().persistent().has(&StorageKey::PolicyClaim(policy_id)) {
env.storage().persistent()
.get(&StorageKey::PolicyClaim(policy_id)).unwrap()
} else {
let cid = Self::next_claim_id(&env);
let claim = Claim {
id: cid,
policy_id,
claimant: policy.policyholder.clone(),
coverage_amount: policy.coverage_amount,
observed_value: None,
trigger_met: false,
status: ClaimStatus::Pending,
submitted_at: now,
processed_at: None,
dispute_reason: None,
paid_amount: None,
partial_payout_bps: None,
installments: None,
payout_ready_at: None,
};
env.storage().persistent().set(&StorageKey::Claim(cid), &claim);
env.storage().persistent().extend_ttl(&StorageKey::Claim(cid), TTL_THRESHOLD, TTL_EXTEND_TO);
env.storage().persistent().set(&StorageKey::PolicyClaim(policy_id), &cid);
env.storage().persistent().extend_ttl(&StorageKey::PolicyClaim(policy_id), TTL_THRESHOLD, TTL_EXTEND_TO);
// Make the new claim visible to batch processors and monitoring.
let mut pending: Vec<u128> = env.storage().instance()
.get(&StorageKey::PendingClaims).unwrap_or_else(|| Vec::new(&env));
pending.push_back(cid);
env.storage().instance().set(&StorageKey::PendingClaims, &pending);
// Emit claim_submitted event for off-chain indexing
env.events().publish(
(Symbol::new(&env, "claim_submitted"),),
ClaimSubmitted {
claim_id: cid,
policy_id,
claimant: policy.policyholder.clone(),
coverage_amount: policy.coverage_amount,
},
);
cid
};
let mut claim: Claim = env.storage().persistent()
.get(&StorageKey::Claim(claim_id)).unwrap();
if claim.status != ClaimStatus::Pending {
return ClaimResult::AlreadyProcessed;
}
Self::evaluate_and_settle(&env, &mut claim, &policy, partial_payout_bps)
}
/// Process up to `limit` pending claims parametrically in one call.
/// Returns a Vec of (claim_id, result) pairs for the processed claims.
/// Skips any claim that is not in Pending status (idempotent).
///
/// `limit` is clamped to [`MAX_BATCH_SIZE`]. Passing a larger value (or
/// `u32::MAX`) is not an error — it simply settles the first
/// `MAX_BATCH_SIZE` pending claims, keeping the transaction inside
/// Soroban's instruction budget. Call again to drain the rest of the queue.
pub fn batch_auto_process(env: Env, caller: Address, limit: u32) -> Vec<(u128, ClaimResult)> {
Self::require_keeper(&env, &caller);
Self::require_not_paused(&env);
let pending: Vec<u128> = env.storage().instance()
.get(&StorageKey::PendingClaims)
.unwrap_or_else(|| Vec::new(&env));
let mut results: Vec<(u128, ClaimResult)> = Vec::new(&env);
let effective_limit = if limit > MAX_BATCH_SIZE { MAX_BATCH_SIZE } else { limit };
let process_count = if pending.len() < effective_limit {
pending.len()
} else {
effective_limit
};
let policy_engine: Address = env.storage().instance()
.get(&StorageKey::PolicyEngine)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
for i in 0..process_count {
let claim_id = pending.get_unchecked(i);
let mut claim: Claim = match env.storage().persistent()
.get(&StorageKey::Claim(claim_id)) {
Some(c) => c,
None => continue,
};
if claim.status != ClaimStatus::Pending { continue; }
if claim.processed_at.is_some() { continue; }
let policy = PolicyEngineClient::new(&env, &policy_engine)
.get_policy(&claim.policy_id);
let result = Self::evaluate_and_settle(&env, &mut claim, &policy, None);
results.push_back((claim_id, result));
}
results
}
// ── Dispute ───────────────────────────────────────────────────────────────
/// Escalate a Pending or Rejected claim to Disputed status.
/// Only the original claimant may dispute. Removes the claim from the pending queue
/// so it is not auto-processed again until an admin resolves the dispute.
pub fn dispute_claim(env: Env, claimant: Address, claim_id: u128, reason: soroban_sdk::Symbol) {
claimant.require_auth();
let mut claim: Claim = env.storage().persistent()
.get(&StorageKey::Claim(claim_id))
.unwrap_or_else(|| panic_with_error!(&env, Error::ClaimNotFound));
if claim.claimant != claimant { panic_with_error!(&env, Error::Unauthorized); }
// Only open (Pending), rejected, or partially-paid claims are disputable.
// Fully Paid claims are already settled (USDC transferred), Disputed
// claims are already open, and Expired claims should not be reopened.
if claim.status != ClaimStatus::Pending
&& claim.status != ClaimStatus::Rejected
&& claim.status != ClaimStatus::PartiallyPaid
{
panic_with_error!(&env, Error::AlreadyProcessed);
}
claim.status = ClaimStatus::Disputed;
claim.dispute_reason = Some(reason.clone());
let claim_key = StorageKey::Claim(claim_id);
env.storage().persistent().set(&claim_key, &claim);
Self::extend_claim_ttl(&env, &claim_key);
// A disputed claim is no longer pending — drop it from the queue so it is
// not re-evaluated and does not grow the queue unboundedly.
Self::remove_from_pending(&env, claim_id);
env.events().publish(
(Symbol::new(&env, "claim_disputed"),),
ClaimDisputed {
claim_id,
claimant,
reason,
},
);
}
/// Admin-only: resolve a disputed claim and re-queue it for processing.
///
/// When a claim is disputed, it is removed from the pending queue and sits in
/// Disputed status indefinitely. This function allows the admin to review the
/// dispute and either:
/// - Clear the dispute and return the claim to Pending for re-evaluation, or
/// - Perform an off-chain investigation and then call this to re-queue the claim.
///
/// The claim transitions from Disputed → Pending and is added back to the pending
/// claims queue for the next keeper to process.
pub fn resolve_dispute(env: Env, admin: Address, claim_id: u128) {
Self::require_admin(&env, &admin);
let mut claim: Claim = env.storage().persistent()
.get(&StorageKey::Claim(claim_id))
.unwrap_or_else(|| panic_with_error!(&env, Error::ClaimNotFound));
// Only Disputed claims can be resolved
if claim.status != ClaimStatus::Disputed {
panic_with_error!(&env, Error::AlreadyProcessed);
}
// Clear dispute and return to Pending status
claim.status = ClaimStatus::Pending;
claim.dispute_reason = None;
let claim_key = StorageKey::Claim(claim_id);
env.storage().persistent().set(&claim_key, &claim);
Self::extend_claim_ttl(&env, &claim_key);
// Re-add the claim to the pending queue for re-processing
let mut pending: Vec<u128> = env.storage().instance()
.get(&StorageKey::PendingClaims)
.unwrap_or_else(|| Vec::new(&env));
pending.push_back(claim_id);
env.storage().instance().set(&StorageKey::PendingClaims, &pending);
env.events().publish(
(Symbol::new(&env, "claim_resolved"),),
ClaimResolved {
claim_id,
resolver: admin,
},
);
}
// ── Queries ───────────────────────────────────────────────────────────────
/// Return the `Claim` record for the given `claim_id`. Panics with `ClaimNotFound` if it does not exist.
pub fn get_claim(env: Env, claim_id: u128) -> Claim {
env.storage().persistent()
.get(&StorageKey::Claim(claim_id))
.unwrap_or_else(|| panic_with_error!(&env, Error::ClaimNotFound))
}
/// Return the claim ID associated with `policy_id`, or `None` if no claim has been filed.
pub fn get_claim_id_for_policy(env: Env, policy_id: u128) -> Option<u128> {
env.storage().persistent()
.get(&StorageKey::PolicyClaim(policy_id))
}
/// Schedule installment payouts for a large claim.
/// This allows claims to be paid out over time rather than as a single lump sum.
///
/// Parameters:
/// - `claim_id`: The claim to schedule installments for
/// - `amount_per_installment`: Amount to pay per installment
/// - `num_installments`: Total number of installments
/// - `interval_seconds`: Seconds between each installment
pub fn schedule_installments(
env: Env,
caller: Address,
claim_id: u128,
amount_per_installment: i128,
num_installments: u32,
interval_seconds: u64,
) {
Self::require_keeper(&env, &caller);
Self::require_not_paused(&env);
let mut claim = Self::get_claim(&env, claim_id);
// Only schedule installments for approved claims
if claim.status != ClaimStatus::Paid && claim.status != ClaimStatus::PartiallyPaid {
panic_with_error!(&env, Error::InvalidInput);
}
// Total installment amount should not exceed coverage
let total_amount = amount_per_installment.saturating_mul(num_installments as i128);
if total_amount > claim.coverage_amount {
panic_with_error!(&env, Error::InvalidInput);
}
let now = env.ledger().timestamp();
let schedule = InstallmentSchedule {
total_amount,
amount_per_installment,
num_installments,
interval_seconds,
first_installment_at: now.saturating_add(interval_seconds),
paid_count: 0,
};
claim.installments = Some(schedule.clone());
env.storage().persistent().set(&StorageKey::Claim(claim_id), &claim);
env.storage().persistent().extend_ttl(&StorageKey::Claim(claim_id), TTL_THRESHOLD, TTL_EXTEND_TO);
env.events().publish(
(Symbol::new(&env, "installment_payout_scheduled"),),
InstallmentPayoutScheduled {
claim_id,
policy_id: claim.policy_id,
claimant: claim.claimant.clone(),
total_amount,
num_installments,
interval_seconds,
first_installment_at: schedule.first_installment_at,
},
);
}
/// Claim the next installment for a scheduled claim.
/// Can be called by the claimant to collect available installments.
pub fn claim_installment(env: Env, claimant: Address, claim_id: u128) -> i128 {
claimant.require_auth();
Self::require_not_paused(&env);
let mut claim = Self::get_claim(&env, claim_id);
if claim.claimant != claimant {
panic_with_error!(&env, Error::Unauthorized);
}
let schedule = claim.installments.as_ref()
.unwrap_or_else(|| panic_with_error!(&env, Error::InvalidInput));
// Check if there are remaining installments
if schedule.paid_count >= schedule.num_installments {
panic_with_error!(&env, Error::InvalidInput);
}
let now = env.ledger().timestamp();
// Calculate which installments are now available
let installments_available = if now >= schedule.first_installment_at {
((now - schedule.first_installment_at) / schedule.interval_seconds).saturating_add(1)
.min(schedule.num_installments as u64) as u32
} else {
0
};
if installments_available <= schedule.paid_count {
panic_with_error!(&env, Error::InvalidInput);
}
// Pay out all available installments
let amount_to_pay = schedule.amount_per_installment
.saturating_mul((installments_available - schedule.paid_count) as i128);
// Transfer funds from risk pool
let risk_pool: Address = env.storage().instance()
.get(&StorageKey::RiskPool)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let pool_client = RiskPoolClient::new(&env, &risk_pool);
pool_client.release_for_claim(&env.current_contract_address(), &claim.policy_id);
// Update installment schedule
if let Some(ref mut sched) = claim.installments {
sched.paid_count = installments_available;
}
env.storage().persistent().set(&StorageKey::Claim(claim_id), &claim);
env.storage().persistent().extend_ttl(&StorageKey::Claim(claim_id), TTL_THRESHOLD, TTL_EXTEND_TO);
env.events().publish(
(Symbol::new(&env, "installment_paid"),),
InstallmentPaid {
claim_id,
claimant,
amount: amount_to_pay,
paid_count: installments_available,
total_installments: schedule.num_installments,
},
);
amount_to_pay
}
/// Return the list of claim IDs that are currently in `Pending` status.
pub fn get_pending_claims(env: Env) -> Vec<u128> {
env.storage().instance()
.get(&StorageKey::PendingClaims)
.unwrap_or_else(|| Vec::new(&env))
}
/// Return the current admin address. Panics with `NotInitialized` if the contract has not been set up.
pub fn get_admin(env: Env) -> Address {
env.storage().instance().get(&StorageKey::Admin)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized))
}
/// Return the current storage schema version (defaults to 1 before any migration).
pub fn get_version(env: Env) -> u32 {
env.storage().instance().get(&StorageKey::Version).unwrap_or(1)
}
/// Admin-only: pause all claim submissions and processing.
pub fn pause(env: Env, admin: Address) {
Self::require_admin(&env, &admin);
env.storage().instance().set(&StorageKey::Paused, &true);
env.events().publish(
(Symbol::new(&env, "paused"),),
admin,
);
}
/// Admin-only: resume claim submissions and processing.
pub fn resume(env: Env, admin: Address) {
Self::require_admin(&env, &admin);
env.storage().instance().set(&StorageKey::Paused, &false);
env.events().publish(
(Symbol::new(&env, "resumed"),),
admin,
);
}
/// Check whether the contract is currently paused.
pub fn is_paused(env: Env) -> bool {
env.storage().instance().get(&StorageKey::Paused).unwrap_or(false)
}
/// Upgrade the contract WASM in-place. Only the admin may call this.
/// Storage is preserved across upgrades; only the execution code changes.
/// Runs storage migrations if the new version requires them.
///
/// If a guardian threshold > 0 is configured (`set_guardians`), this call
/// does not upgrade immediately — it registers the upgrade as pending and
/// requires `threshold` guardians to call `approve_upgrade` before the
/// WASM is actually replaced, guarding this irreversible operation
/// against a single compromised admin key.
pub fn upgrade(env: Env, admin: Address, new_wasm_hash: BytesN<32>, new_version: u32) {
let stored_admin: Address = env.storage().instance().get(&StorageKey::Admin)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
if admin != stored_admin { panic_with_error!(&env, Error::Unauthorized); }
admin.require_auth();
let current_version: u32 = env.storage().instance().get(&StorageKey::Version).unwrap_or(1);
if new_version <= current_version {
panic_with_error!(&env, Error::InvalidVersion);
}
let threshold: u32 = env
.storage()
.instance()
.get(&StorageKey::GuardianThreshold)
.unwrap_or(0);
if threshold == 0 {
Self::run_migrations(&env, current_version, new_version);
env.storage().instance().set(&StorageKey::Version, &new_version);
env.deployer().update_current_contract_wasm(new_wasm_hash);
env.events().publish(
(Symbol::new(&env, "contract_upgraded"),),
ContractUpgraded {
old_version: current_version,
new_version,
},
);
return;
}
let pending = PendingUpgrade {
new_wasm_hash,
new_version,
approvals: Vec::new(&env),
};
env.storage().instance().set(&StorageKey::PendingUpgrade, &pending);
}
/// Configure the guardian set and approval threshold required for
/// critical actions (currently: contract upgrades). Admin-only.
/// `threshold == 0` disables the guardian requirement (default), so the
/// admin alone can act — preserves existing single-admin behavior until
/// guardians are explicitly configured.
pub fn set_guardians(env: Env, admin: Address, guardians: Vec<Address>, threshold: u32) {
let stored_admin: Address = env.storage().instance().get(&StorageKey::Admin)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
if admin != stored_admin { panic_with_error!(&env, Error::Unauthorized); }
admin.require_auth();
if threshold > guardians.len() {
panic_with_error!(&env, Error::InvalidThreshold);
}
env.storage().instance().set(&StorageKey::Guardians, &guardians);
env.storage()
.instance()
.set(&StorageKey::GuardianThreshold, &threshold);
env.events().publish(
(Symbol::new(&env, "guardians_updated"),),
GuardiansUpdated { guardians, threshold },
);
}
/// Return the current guardian set.
pub fn get_guardians(env: Env) -> Vec<Address> {
env.storage()
.instance()
.get(&StorageKey::Guardians)
.unwrap_or_else(|| Vec::new(&env))
}
/// Return the current guardian approval threshold (0 = disabled).
pub fn get_guardian_threshold(env: Env) -> u32 {
env.storage()
.instance()
.get(&StorageKey::GuardianThreshold)
.unwrap_or(0)
}
/// Return the pending upgrade awaiting guardian approvals, if any.
pub fn get_pending_upgrade(env: Env) -> Option<PendingUpgrade> {
env.storage().instance().get(&StorageKey::PendingUpgrade)
}
/// Guardian approval for the pending upgrade. Once enough guardians have
/// approved (>= threshold), the upgrade executes immediately.
pub fn approve_upgrade(env: Env, guardian: Address, new_wasm_hash: BytesN<32>) {
guardian.require_auth();
let guardians: Vec<Address> = env
.storage()
.instance()
.get(&StorageKey::Guardians)
.unwrap_or_else(|| Vec::new(&env));
let mut is_guardian = false;
for g in guardians.iter() {
if g == guardian {
is_guardian = true;
break;
}
}
if !is_guardian {
panic_with_error!(&env, Error::NotGuardian);