Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .claude/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"permissions": {
"allow": [
"Bash(find /home/ljtwp/Desktop/drips/niff -type f -name *.sol -o -name *.rs -o -name *.ts -o -name *.tsx -o -name *.js -o -name *.jsx)",
"Bash(cargo test:*)",
"Bash(cargo fmt:*)",
"Bash(cargo clippy:*)"
]
}
}
257 changes: 256 additions & 1 deletion contracts/niffyinsure/src/claim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,74 @@
// 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, VoteOption},
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 {
Expand All @@ -24,6 +85,78 @@ struct ClaimFiled {
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.
Expand Down Expand Up @@ -156,12 +289,22 @@ pub fn vote_on_claim(
claim.status = ClaimStatus::Rejected;
}

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)
}

Expand Down Expand Up @@ -193,20 +336,40 @@ pub fn finalize_claim(env: &Env, claim_id: u64) -> Result<ClaimStatus, Error> {
ClaimStatus::Rejected
};

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);
}
Expand All @@ -218,6 +381,98 @@ pub fn process_claim(env: &Env, claim_id: u64) -> Result<(), Error> {
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> {
Expand Down
1 change: 1 addition & 0 deletions contracts/niffyinsure/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,7 @@ impl NiffyInsure {
terminated_at_ledger: 0,
termination_reason: TerminationReason::None,
terminated_by_admin: false,
strike_count: 0,
};
env.storage().persistent().set(
&storage::DataKey::Policy(holder.clone(), policy_id),
Expand Down
1 change: 1 addition & 0 deletions contracts/niffyinsure/src/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ pub fn initiate_policy(
terminated_at_ledger: 0,
termination_reason: crate::types::TerminationReason::None,
terminated_by_admin: false,
strike_count: 0,
};

validate::check_policy(&policy).map_err(|_| PolicyError::PolicyValidation)?;
Expand Down
6 changes: 6 additions & 0 deletions contracts/niffyinsure/src/policy_lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ pub fn initiate_policy(
terminated_at_ledger: 0,
termination_reason: TerminationReason::None,
terminated_by_admin: false,
strike_count: 0,
};

validate::check_policy(&policy).map_err(|e| match e {
Expand Down Expand Up @@ -212,5 +213,10 @@ fn termination_reason_tag(reason: TerminationReason) -> u32 {
TerminationReason::FraudOrMisrepresentation => 4,
TerminationReason::RegulatoryAction => 5,
TerminationReason::AdminOverride => 6,
// 7 = ExcessiveRejections: set by the claims engine via on_reject,
// not by the policy-lifecycle termination flow. Included here for
// completeness; PolicyTerminated is not normally emitted for this
// reason — PolicyDeactivated (from claim.rs) is the canonical event.
TerminationReason::ExcessiveRejections => 7,
}
}
Loading
Loading