forked from InsurNiffy/niff-Stellar-shurance
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaim.rs
More file actions
535 lines (469 loc) · 21.2 KB
/
Copy pathclaim.rs
File metadata and controls
535 lines (469 loc) · 21.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
// Claim lifecycle and DAO voting will be implemented here.
//
// Planned public functions:
// file_claim(env, policy_id, amount, details, image_urls)
// vote_on_claim(env, voter, claim_id, vote)
//
// Open claim accounting: `storage::OpenClaimCount(holder, policy_id)` must be
// incremented when a claim enters `Processing` and decremented when it reaches
// a terminal status (`Approved` / `Rejected`), so policy termination can block
// or audit in-flight claims. Until `file_claim` ships, admins may use
// `admin_set_open_claim_count` in tests or break-glass ops only.
//
// ── Rejection side-effects ─────────────────────────────────────────────────────
//
// When a claim reaches `ClaimStatus::Rejected` (via majority vote or deadline
// finalization), `on_reject` is called to apply the following deterministic,
// trustless consequences:
//
// 1. `StrikeIncremented` event — increments the policy's `strike_count`
// and emits the new total so indexers can surface it to holders.
// 2. `PolicyDeactivated` event — emitted if `strike_count` reaches
// `STRIKE_DEACTIVATION_THRESHOLD`. The policy is set `is_active = false`
// and the voter registry is updated in the same ledger.
// 3. `ClaimRejected` event — authoritative rejection signal for indexers.
// Carries vote tallies so the UI can explain the outcome without querying
// separate storage.
//
// ── Guarantee: reject NEVER invokes payout ────────────────────────────────────
//
// `on_reject` performs no token transfers. The only token transfer in this
// module is inside `payout`, which is exclusively called from `process_claim`.
// `process_claim` guards on `claim.status == ClaimStatus::Approved`; a
// `Rejected` claim will receive `Error::ClaimNotApproved` before any transfer
// is attempted.
//
// ── Permanent auditability ────────────────────────────────────────────────────
//
// Rejected claim records are stored in `persistent` storage with TTL
// extensions and remain readable indefinitely via `get_claim`. The `details`
// field holds a brief description (≤ 256 chars); full allegation narratives
// must NOT be stored on-chain — use IPFS/off-chain storage and reference via
// `image_urls` or an off-chain indexer.
//
// ── Appeal window interaction ─────────────────────────────────────────────────
//
// Appeals are not implemented in this version. If added:
// - Auto-deactivation in `on_reject` should be conditional on
// `env.ledger().sequence() > appeal_deadline_ledger`.
// - A new `ClaimStatus::Appealed` would require composing cleanly with
// the existing terminal-state checks (`is_terminal()`).
// - The `PolicyDeactivated` and `StrikeIncremented` events carry enough
// context for an appeal system to reverse their effects off-chain.
//
// ── Governance risk documentation ─────────────────────────────────────────────
//
// Admin override path: the admin can call `admin_terminate_policy` with
// `allow_open_claims = true`, which can terminate a policy while a claim is
// in `Processing`. In that scenario the claim vote can still complete, but
// `on_reject` will find `policy.is_active = false` and skip the deactivation
// branch (policy already inactive). The `StrikeIncremented` and
// `ClaimRejected` events still fire for auditability.
//
// Premium-extraction attack: an attacker cannot extract premiums via the
// rejection path because `process_claim` is gated on `Approved` status. The
// only way to get an `Approved` claim processed is through legitimate majority
// or deadline-plurality approval, which is controlled by the DAO snapshot, not
// the admin. The admin cannot flip a `Rejected` claim to `Approved`.
use crate::{
ledger, storage,
types::{
Claim, ClaimProcessed, ClaimStatus, TerminationReason, VoteOption,
STRIKE_DEACTIVATION_THRESHOLD,
},
validate::Error,
};
use soroban_sdk::{contractevent, Address, Env, String, Vec};
// ── Events ────────────────────────────────────────────────────────────────────
#[contractevent(topics = ["niffyinsure", "claim_filed"])]
#[derive(Clone, Debug, Eq, PartialEq)]
struct ClaimFiled {
#[topic]
pub claim_id: u64,
pub holder: Address,
}
/// Emitted as the authoritative rejection signal. Indexers must consume this
/// event (not poll storage) to drive user-facing messaging. The vote tallies
/// are included so the UI can explain the outcome (e.g., "rejected 4–1").
///
/// Topic layout: ["niffyinsure", "claim_rejected", claim_id]
/// Data: { policy_id, claimant, reject_votes, approve_votes, at_ledger }
///
/// NOTE: This event is NEVER emitted on the approve path. Its presence
/// unambiguously signals rejection.
#[contractevent(topics = ["niffyinsure", "claim_rejected"])]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClaimRejected {
#[topic]
pub claim_id: u64,
pub policy_id: u32,
pub claimant: Address,
pub reject_votes: u32,
pub approve_votes: u32,
/// Ledger at which the claim was finalized as rejected.
pub at_ledger: u32,
}
/// Emitted every time a rejection increments the policy's strike counter.
/// Indexers should use this event to notify holders of accumulating strikes
/// before the threshold triggers deactivation.
///
/// Topic layout: ["niffyinsure", "strike_incremented", holder, policy_id]
/// Data: { claim_id, strike_count }
///
/// `strike_count` is the NEW total after this increment (1-indexed).
#[contractevent(topics = ["niffyinsure", "strike_incremented"])]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StrikeIncremented {
#[topic]
pub holder: Address,
#[topic]
pub policy_id: u32,
pub claim_id: u64,
/// New cumulative strike count for this policy after this rejection.
pub strike_count: u32,
}
/// Emitted when a policy is automatically deactivated because its
/// `strike_count` reached `STRIKE_DEACTIVATION_THRESHOLD`.
///
/// Topic layout: ["niffyinsure", "policy_deactivated", holder, policy_id]
/// Data: { reason_code, at_ledger }
///
/// `reason_code` values:
/// 1 = ExcessiveRejections (strike threshold reached)
///
/// CENTRALIZATION NOTE: This event is emitted by the claims engine
/// deterministically — no admin key is involved. An admin cannot prevent or
/// reverse this deactivation via `process_claim` or any other entrypoint.
/// The only admin avenue is `admin_terminate_policy` (which terminates before
/// the threshold is reached) or a future contract upgrade.
///
/// APPEAL NOTE: If appeals are added, this event should be treated as
/// "pending deactivation" until the appeal window closes, not as an
/// immediate final state.
#[contractevent(topics = ["niffyinsure", "policy_deactivated"])]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PolicyDeactivated {
#[topic]
pub holder: Address,
#[topic]
pub policy_id: u32,
/// 1 = ExcessiveRejections
pub reason_code: u32,
pub at_ledger: u32,
}
// ── file_claim ────────────────────────────────────────────────────────────────
/// File a new claim against an active policy.
///
/// Window checks (all via `ledger` helpers):
/// - Policy must be active: `now` in `[start_ledger, end_ledger)`.
/// - Rate-limit: `now >= last_filed_at + RATE_LIMIT_WINDOW_LEDGERS` (or first claim).
///
/// Returns the new `claim_id`.
pub fn file_claim(
env: &Env,
holder: &Address,
policy_id: u32,
amount: i128,
details: &String,
image_urls: &Vec<String>,
) -> Result<u64, Error> {
// Check pause: claims are blocked if claims_paused is true
storage::assert_claims_not_paused(env);
let policy = storage::get_policy(env, holder, policy_id).ok_or(Error::PolicyNotFound)?;
// Policy active window check using ledger helper.
let now = env.ledger().sequence();
if !ledger::is_within_window(now, policy.start_ledger, policy.end_ledger) {
return if ledger::is_expired(now, policy.end_ledger) {
Err(Error::PolicyExpired)
} else {
Err(Error::PolicyInactive)
};
}
if !policy.is_active {
return Err(Error::PolicyInactive);
}
if storage::has_open_claim(env, holder, policy_id) {
return Err(Error::DuplicateOpenClaim);
}
// Rate-limit check.
if let Some(last) = storage::get_last_claim_ledger(env, holder) {
if !ledger::is_rate_limit_elapsed(now, last, ledger::RATE_LIMIT_WINDOW_LEDGERS) {
return Err(Error::RateLimitExceeded);
}
}
crate::validate::check_claim_fields(env, amount, policy.coverage, details, image_urls)?;
let claim_id = storage::next_claim_id(env);
let claim = Claim {
claim_id,
policy_id,
claimant: holder.clone(),
amount,
details: details.clone(),
image_urls: image_urls.clone(),
status: ClaimStatus::Processing,
voting_deadline_ledger: now.saturating_add(ledger::VOTE_WINDOW_LEDGERS),
approve_votes: 0,
reject_votes: 0,
filed_at: now,
appeal_open_deadline_ledger: 0,
appeals_count: 0,
appeal_deadline_ledger: 0,
appeal_approve_votes: 0,
appeal_reject_votes: 0,
};
storage::set_claim(env, &claim);
storage::set_open_claim(env, holder, policy_id, true);
storage::snapshot_claim_voters(env, claim_id);
storage::set_last_claim_ledger(env, holder, now);
ClaimFiled {
claim_id,
holder: holder.clone(),
}
.publish(env);
Ok(claim_id)
}
// ── vote_on_claim ─────────────────────────────────────────────────────────────
/// Cast a vote on a pending claim.
///
/// Window check: `now < filed_at + VOTE_WINDOW_LEDGERS` (via `ledger::is_vote_open`).
/// Returns the updated `ClaimStatus` after tallying.
pub fn vote_on_claim(
env: &Env,
voter: &Address,
claim_id: u64,
vote: &VoteOption,
) -> Result<ClaimStatus, Error> {
// Check pause: voting is blocked if claims_paused is true
storage::assert_claims_not_paused(env);
let mut claim = storage::get_claim(env, claim_id).ok_or(Error::ClaimNotFound)?;
if claim.status.is_terminal() {
return Err(Error::ClaimAlreadyTerminal);
}
// Voting window check.
let now = env.ledger().sequence();
if !ledger::is_vote_open(now, claim.filed_at, ledger::VOTE_WINDOW_LEDGERS) {
return Err(Error::VotingWindowClosed);
}
// Voter must be in the claim's snapshot electorate.
let snapshot = storage::get_claim_voters(env, claim_id);
let eligible = snapshot.iter().any(|v| v == *voter);
if !eligible {
return Err(Error::NotEligibleVoter);
}
// Duplicate vote check.
if storage::get_vote(env, claim_id, voter).is_some() {
return Err(Error::DuplicateVote);
}
storage::set_vote(env, claim_id, voter, vote);
match vote {
VoteOption::Approve => claim.approve_votes += 1,
VoteOption::Reject => claim.reject_votes += 1,
}
// Auto-finalize on majority.
let total = snapshot.len();
let majority = total / 2 + 1;
let newly_rejected;
if claim.approve_votes >= majority {
claim.status = ClaimStatus::Approved;
newly_rejected = false;
} else if claim.reject_votes >= majority {
claim.status = ClaimStatus::Rejected;
claim.appeal_open_deadline_ledger = now.saturating_add(ledger::APPEAL_OPEN_WINDOW_LEDGERS);
newly_rejected = true;
} else {
newly_rejected = false;
}
let newly_rejected = claim.status == ClaimStatus::Rejected;
if claim.status.is_terminal() {
storage::set_open_claim(env, &claim.claimant, claim.policy_id, false);
}
let status = claim.status.clone();
storage::set_claim(env, &claim);
// Apply rejection side-effects after the claim record is persisted.
// on_reject emits ClaimRejected, StrikeIncremented, and (if threshold
// reached) PolicyDeactivated. It never transfers tokens.
if newly_rejected {
on_reject(env, &claim);
}
Ok(status)
}
// ── finalize_claim ────────────────────────────────────────────────────────────
/// Finalize a claim after the voting deadline has passed.
///
/// Window check: `now >= filed_at + VOTE_WINDOW_LEDGERS` (via `ledger::is_vote_deadline_passed`).
/// Plurality wins; tie resolves to Rejected.
pub fn finalize_claim(env: &Env, claim_id: u64) -> Result<ClaimStatus, Error> {
// Check pause: finalization is blocked if claims_paused is true
storage::assert_claims_not_paused(env);
let mut claim = storage::get_claim(env, claim_id).ok_or(Error::ClaimNotFound)?;
if claim.status.is_terminal() {
return Err(Error::ClaimAlreadyTerminal);
}
let now = env.ledger().sequence();
if !ledger::is_vote_deadline_passed(now, claim.filed_at, ledger::VOTE_WINDOW_LEDGERS) {
return Err(Error::VotingWindowStillOpen);
}
let newly_rejected;
if claim.approve_votes > claim.reject_votes {
claim.status = ClaimStatus::Approved;
newly_rejected = false;
} else {
// Tie or reject plurality → Rejected (insurer wins tie).
claim.status = ClaimStatus::Rejected;
claim.appeal_open_deadline_ledger = now.saturating_add(ledger::APPEAL_OPEN_WINDOW_LEDGERS);
newly_rejected = true;
}
let newly_rejected = claim.status == ClaimStatus::Rejected;
storage::set_open_claim(env, &claim.claimant, claim.policy_id, false);
let status = claim.status.clone();
storage::set_claim(env, &claim);
// Apply rejection side-effects after the claim record is persisted.
if newly_rejected {
on_reject(env, &claim);
}
Ok(status)
}
// ── process_claim (admin payout trigger) ─────────────────────────────────────
/// Trigger the payout for an approved claim.
///
/// INVARIANT: This function is the ONLY code path that transfers payout
/// tokens. It is unconditionally gated on `claim.status == Approved`.
/// A `Rejected` claim will never reach `payout()` — the guard below returns
/// `Error::ClaimNotApproved` before any transfer is attempted.
///
/// This invariant is enforced structurally: `on_reject` does not call
/// `payout`, and there is no entrypoint that transitions a `Rejected` claim
/// to `Approved`.
pub fn process_claim(env: &Env, claim_id: u64) -> Result<(), Error> {
let mut claim = storage::get_claim(env, claim_id).ok_or(Error::ClaimNotFound)?;
if claim.status == ClaimStatus::Paid {
return Err(Error::AlreadyPaid);
}
// SAFETY: Rejected and Processing claims are explicitly blocked here.
// No path can circumvent this guard to reach payout().
if claim.status != ClaimStatus::Approved {
return Err(Error::ClaimNotApproved);
}
payout(env, &claim)?;
claim.status = ClaimStatus::Paid;
storage::set_open_claim(env, &claim.claimant, claim.policy_id, false);
storage::set_claim(env, &claim);
Ok(())
}
// ── on_reject (centralized rejection side-effects) ────────────────────────────
/// Apply all side-effects that must occur when a claim is rejected.
///
/// Called by both `vote_on_claim` (majority auto-finalize) and
/// `finalize_claim` (deadline resolution). Must be called AFTER the claim
/// record has been persisted with `ClaimStatus::Rejected`.
///
/// Side-effects (in emission order):
/// 1. `ClaimRejected` — indexer signal; always emitted.
/// 2. `StrikeIncremented` — policy strike counter incremented; always
/// emitted even if the policy is already inactive (auditability).
/// 3. `PolicyDeactivated` — emitted only when `strike_count` reaches
/// `STRIKE_DEACTIVATION_THRESHOLD` AND the policy is currently active.
///
/// NO TOKEN TRANSFERS occur in this function.
///
/// If the policy record cannot be found (e.g., it was manually terminated and
/// subsequently evicted from storage), `ClaimRejected` is still emitted and
/// the function returns without error. Strike and deactivation events require
/// the policy record.
fn on_reject(env: &Env, claim: &Claim) {
let now = env.ledger().sequence();
// ── 1. ClaimRejected ─────────────────────────────────────────────────────
//
// Emit first so indexers always see a ClaimRejected before any policy
// side-effect events, establishing a clear causal ordering.
ClaimRejected {
claim_id: claim.claim_id,
policy_id: claim.policy_id,
claimant: claim.claimant.clone(),
reject_votes: claim.reject_votes,
approve_votes: claim.approve_votes,
at_ledger: now,
}
.publish(env);
// ── 2. StrikeIncremented + (optional) PolicyDeactivated ──────────────────
//
// Best-effort: if the policy record is missing (manual termination + TTL
// eviction), skip strike and deactivation. ClaimRejected has already fired.
let Some(mut policy) = storage::get_policy(env, &claim.claimant, claim.policy_id) else {
return;
};
policy.strike_count = policy.strike_count.saturating_add(1);
StrikeIncremented {
holder: claim.claimant.clone(),
policy_id: claim.policy_id,
claim_id: claim.claim_id,
strike_count: policy.strike_count,
}
.publish(env);
// ── 3. PolicyDeactivated ─────────────────────────────────────────────────
//
// Deactivate only if the policy is currently active AND the strike count
// has reached the threshold. A policy already deactivated (e.g., by the
// admin or a prior threshold breach) is not touched again — no double
// deactivation.
if policy.strike_count >= STRIKE_DEACTIVATION_THRESHOLD && policy.is_active {
policy.is_active = false;
policy.terminated_at_ledger = now;
policy.termination_reason = TerminationReason::ExcessiveRejections;
policy.terminated_by_admin = false;
// Persist policy state change before emitting the event so any
// re-entrant read sees the correct state.
storage::set_policy(env, &claim.claimant, claim.policy_id, &policy);
// Update voter registry: decrement active count and remove from the
// live voter list if this was the holder's last active policy.
storage::decrement_holder_active_policies(env, &claim.claimant);
if storage::get_holder_active_policy_count(env, &claim.claimant) == 0 {
storage::voters_remove_holder(env, &claim.claimant);
}
PolicyDeactivated {
holder: claim.claimant.clone(),
policy_id: claim.policy_id,
reason_code: 1, // 1 = ExcessiveRejections
at_ledger: now,
}
.publish(env);
} else {
// Strike did not trigger deactivation — persist the incremented count.
storage::set_policy(env, &claim.claimant, claim.policy_id, &policy);
}
}
// ── Internal helpers ──────────────────────────────────────────────────────────
fn payout(env: &Env, claim: &Claim) -> Result<(), Error> {
let policy =
storage::get_policy(env, &claim.claimant, claim.policy_id).ok_or(Error::PolicyNotFound)?;
if !storage::is_allowed_asset(env, &policy.asset) {
return Err(Error::InvalidAsset);
}
if !crate::token::check_balance(env, &policy.asset, claim.amount) {
return Err(Error::InsufficientTreasury);
}
crate::token::transfer(
env,
&policy.asset,
&env.current_contract_address(),
&claim.claimant,
claim.amount,
);
ClaimProcessed {
claim_id: claim.claim_id,
recipient: claim.claimant.clone(),
amount: claim.amount,
}
.publish(env);
Ok(())
}
// ── Public read helpers ───────────────────────────────────────────────────────
pub fn get_claim(env: &Env, claim_id: u64) -> Result<Claim, Error> {
storage::get_claim(env, claim_id).ok_or(Error::ClaimNotFound)
}
pub fn is_allowed_asset(env: &Env, asset: &Address) -> bool {
storage::is_allowed_asset(env, asset)
}
pub fn set_allowed_asset(env: &Env, asset: &Address, allowed: bool) {
storage::set_allowed_asset(env, asset, allowed);
}