diff --git a/contracts/split/src/contract_state_validation.rs b/contracts/split/src/contract_state_validation.rs new file mode 100644 index 0000000..55dee2e --- /dev/null +++ b/contracts/split/src/contract_state_validation.rs @@ -0,0 +1,340 @@ +//! Contract state validation (issue #1220), first slice. +//! +//! Pure helpers that validate invoice state transitions, check structural +//! invariants, prevent invalid states, and record a bounded state-change +//! log. Not wired to contract storage or entrypoints; the authoritative +//! status lives in [`crate::types`] and would be projected into +//! [`ContractState`] before validation. + +#![allow(dead_code)] + +/// Maximum entries retained in the state-change log. +pub const MAX_LOG_ENTRIES: usize = 64; + +/// Normalised contract state mirroring the invoice lifecycle. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ContractState { + /// Created but not yet open for payment. + Draft, + /// Open for contributions, not yet fully funded. + Pending, + /// Fully funded, not yet released. + Funded, + /// Partially released (milestone/instalment). + PartiallyReleased, + /// All recipients paid out; terminal. + Released, + /// Payers refunded; terminal. + Refunded, + /// Deadline passed unfunded; terminal. + Expired, + /// Creator-cancelled; terminal. + Cancelled, + /// Under dispute. + Disputed, + /// Moved to cold storage; terminal. + Archived, +} + +/// Errors returned by the validators. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ValidationError { + /// The requested `from -> to` transition is not allowed. + InvalidTransition, + /// A structural invariant of the snapshot does not hold. + InvariantViolated, + /// `funded` exceeds `total_due`. + OverFunded, + /// A non-draft invoice must have at least one recipient. + NoRecipients, + /// A `Released`/`Funded` invoice must be fully funded. + NotFullyFunded, + /// `total_due` must be non-negative for a payable invoice. + InvalidAmount, + /// The state-change log is at capacity. + LogFull, +} + +/// A point-in-time view of an invoice used for invariant checking. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ContractSnapshot { + pub invoice_id: u64, + pub state: ContractState, + pub total_due: i128, + pub funded: i128, + pub recipient_count: u32, + pub deadline_ts: u64, +} + +/// One recorded state transition. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StateChange { + pub invoice_id: u64, + pub from: ContractState, + pub to: ContractState, + pub ledger: u32, + pub timestamp: u64, +} + +/// Bounded append-only log of state changes. +pub struct StateChangeLog { + entries: [StateChange; MAX_LOG_ENTRIES], + len: usize, +} + +impl Default for StateChangeLog { + fn default() -> Self { + Self { + entries: [StateChange { + invoice_id: 0, + from: ContractState::Draft, + to: ContractState::Draft, + ledger: 0, + timestamp: 0, + }; MAX_LOG_ENTRIES], + len: 0, + } + } +} + +impl StateChangeLog { + pub fn new() -> Self { + Self::default() + } + pub fn len(&self) -> usize { + self.len + } + pub fn is_empty(&self) -> bool { + self.len == 0 + } + pub fn entries(&self) -> &[StateChange] { + &self.entries[..self.len] + } + + /// Append a recorded transition. Returns [`ValidationError::LogFull`] at + /// capacity. + pub fn record(&mut self, c: StateChange) -> Result<(), ValidationError> { + if self.len >= MAX_LOG_ENTRIES { + return Err(ValidationError::LogFull); + } + self.entries[self.len] = c; + self.len += 1; + Ok(()) + } +} + +/// Allowed transitions. A transition must change the state; terminal states +/// (`Archived`) allow nothing out. +pub fn is_valid_transition(from: ContractState, to: ContractState) -> bool { + use ContractState::*; + if from == to { + return false; + } + matches!( + (from, to), + (Draft, Pending) + | (Pending, Funded) + | (Pending, PartiallyReleased) + | (Pending, Cancelled) + | (Pending, Expired) + | (Pending, Disputed) + | (Funded, Released) + | (Funded, Disputed) + | (PartiallyReleased, Released) + | (PartiallyReleased, Disputed) + | (Disputed, Pending) + | (Disputed, Released) + | (Disputed, Refunded) + | (Released, Archived) + | (Refunded, Archived) + | (Expired, Archived) + | (Cancelled, Archived) + ) +} + +/// Validate that a single `from -> to` transition is allowed. +pub fn validate_transition(from: ContractState, to: ContractState) -> Result<(), ValidationError> { + if is_valid_transition(from, to) { + Ok(()) + } else { + Err(ValidationError::InvalidTransition) + } +} + +/// Check the structural invariants of a snapshot. Returns the first violated +/// invariant, or `Ok(())` if the snapshot is consistent. +pub fn check_invariants(s: &ContractSnapshot) -> Result<(), ValidationError> { + use ContractState::*; + if s.total_due < 0 { + return Err(ValidationError::InvalidAmount); + } + if s.funded < 0 || s.funded > s.total_due { + return Err(ValidationError::OverFunded); + } + if s.state != Draft && s.recipient_count == 0 { + return Err(ValidationError::NoRecipients); + } + if s.state != Draft && s.deadline_ts == 0 { + return Err(ValidationError::InvariantViolated); + } + match s.state { + Funded | Released if s.funded != s.total_due => Err(ValidationError::NotFullyFunded), + PartiallyReleased if s.funded == 0 || s.funded >= s.total_due => { + Err(ValidationError::InvariantViolated) + } + _ => Ok(()), + } +} + +/// Convenience: a snapshot satisfies all invariants. +pub fn is_valid_state(s: &ContractSnapshot) -> bool { + check_invariants(s).is_ok() +} + +/// Validate a transition, check the prospective snapshot's invariants, and +/// record the change. The state is only committed once both validation and +/// logging succeed, so a full log leaves the snapshot untouched. +pub fn apply_transition( + s: &mut ContractSnapshot, + log: &mut StateChangeLog, + to: ContractState, + ledger: u32, + timestamp: u64, +) -> Result<(), ValidationError> { + validate_transition(s.state, to)?; + let prev = s.state; + let mut next = *s; + next.state = to; + check_invariants(&next)?; + log.record(StateChange { + invoice_id: s.invoice_id, + from: prev, + to, + ledger, + timestamp, + })?; + *s = next; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn snap( + id: u64, + state: ContractState, + total: i128, + funded: i128, + rc: u32, + dl: u64, + ) -> ContractSnapshot { + ContractSnapshot { + invoice_id: id, + state, + total_due: total, + funded, + recipient_count: rc, + deadline_ts: dl, + } + } + + #[test] + fn valid_transitions_allowed() { + use ContractState::*; + assert!(is_valid_transition(Draft, Pending)); + assert!(is_valid_transition(Pending, Funded)); + assert!(is_valid_transition(Funded, Released)); + assert!(is_valid_transition(Released, Archived)); + assert!(is_valid_transition(Pending, Disputed)); + assert!(is_valid_transition(Disputed, Released)); + } + + #[test] + fn invalid_transitions_rejected() { + use ContractState::*; + assert!(!is_valid_transition(Released, Pending)); // no going back + assert!(!is_valid_transition(Archived, Pending)); // terminal + assert!(!is_valid_transition(Draft, Released)); // skips steps + assert!(!is_valid_transition(Pending, Pending)); // no-op + assert_eq!( + validate_transition(Released, Pending), + Err(ValidationError::InvalidTransition) + ); + } + + #[test] + fn invariants_pass_for_valid_snapshot() { + let s = snap(1, ContractState::Funded, 1000, 1000, 2, 1000); + assert!(is_valid_state(&s)); + assert_eq!(check_invariants(&s), Ok(())); + } + + #[test] + fn invariants_detect_violations() { + // over-funded + assert_eq!( + check_invariants(&snap(1, ContractState::Pending, 1000, 1200, 2, 1000)), + Err(ValidationError::OverFunded) + ); + // released but not fully funded + assert_eq!( + check_invariants(&snap(1, ContractState::Released, 1000, 500, 2, 1000)), + Err(ValidationError::NotFullyFunded) + ); + // no recipients on a payable invoice + assert_eq!( + check_invariants(&snap(1, ContractState::Pending, 1000, 0, 0, 1000)), + Err(ValidationError::NoRecipients) + ); + // negative total + assert_eq!( + check_invariants(&snap(1, ContractState::Pending, -1, 0, 1, 1000)), + Err(ValidationError::InvalidAmount) + ); + } + + #[test] + fn state_change_log_records_in_order() { + let mut log = StateChangeLog::new(); + assert!(log.is_empty()); + log.record(StateChange { + invoice_id: 1, + from: ContractState::Draft, + to: ContractState::Pending, + ledger: 1, + timestamp: 10, + }) + .unwrap(); + log.record(StateChange { + invoice_id: 1, + from: ContractState::Pending, + to: ContractState::Funded, + ledger: 2, + timestamp: 20, + }) + .unwrap(); + assert_eq!(log.len(), 2); + assert_eq!(log.entries()[0].to, ContractState::Pending); + assert_eq!(log.entries()[1].to, ContractState::Funded); + } + + #[test] + fn apply_transition_validates_and_logs() { + let mut s = snap(1, ContractState::Pending, 1000, 1000, 2, 1000); + let mut log = StateChangeLog::new(); + // Valid: Pending -> Funded (already fully funded). + assert!(apply_transition(&mut s, &mut log, ContractState::Funded, 5, 50).is_ok()); + assert_eq!(s.state, ContractState::Funded); + assert_eq!(log.len(), 1); + assert_eq!(log.entries()[0].from, ContractState::Pending); + assert_eq!(log.entries()[0].to, ContractState::Funded); + // Invalid: Funded -> Pending is rejected; state and log unchanged. + assert_eq!( + apply_transition(&mut s, &mut log, ContractState::Pending, 6, 60), + Err(ValidationError::InvalidTransition) + ); + assert_eq!(s.state, ContractState::Funded); + assert_eq!(log.len(), 1); + } +} diff --git a/contracts/split/src/invoice_event_filtering.rs b/contracts/split/src/invoice_event_filtering.rs new file mode 100644 index 0000000..7edae9e --- /dev/null +++ b/contracts/split/src/invoice_event_filtering.rs @@ -0,0 +1,395 @@ +//! Invoice event filtering and querying (issue #1219), first slice. +//! +//! Pure helpers that filter a bounded in-memory log of normalised invoice +//! events by event type, date range, and arbitrary predicate combinations +//! (complex queries), with `offset`/`limit` pagination and early-exit for +//! query performance. Not wired to contract storage or entrypoints; the +//! on-chain event stream is emitted by [`crate::events`] and would be +//! projected into [`InvoiceEvent`] by an indexer before being queried here. + +#![allow(dead_code)] + +/// Maximum events retained in one log. +pub const MAX_EVENTS: usize = 64; +/// Maximum results returned from a single query. +pub const MAX_RESULTS: usize = 64; + +/// Normalised invoice event type, mirroring the `split` action topics emitted +/// by [`crate::events`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum InvoiceEventType { + Created, + Paid, + Released, + Refunded, + Expired, + Cancelled, + Disputed, + PartiallyReleased, + Archived, + Rated, + Paused, + Resumed, + Other, +} + +/// A single normalised invoice event. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InvoiceEvent { + pub invoice_id: u64, + pub event_type: InvoiceEventType, + /// Unix timestamp of the event (ledger timestamp). + pub timestamp: u64, + pub ledger: u32, + /// Per-invoice sequence number for stable ordering. + pub seq: u64, +} + +impl Default for InvoiceEvent { + fn default() -> Self { + Self { + invoice_id: 0, + event_type: InvoiceEventType::Other, + timestamp: 0, + ledger: 0, + seq: 0, + } + } +} + +/// Errors returned by the log and query helpers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FilterError { + /// Log is at capacity and cannot accept another event. + LogFull, + /// Date range is inverted (`from > to`). + InvalidRange, +} + +/// A composite query: every set field is AND-ed together, so combining a +/// type, invoice id and date range yields a complex filter. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct EventFilter { + pub event_type: Option, + pub invoice_id: Option, + /// Inclusive lower timestamp bound. + pub from_ts: Option, + /// Inclusive upper timestamp bound. + pub to_ts: Option, + /// Skip the first `offset` matching events (pagination). + pub offset: u32, + /// Stop after collecting `limit` matches; `None` means no cap. + pub limit: Option, +} + +impl EventFilter { + /// Convenience: filter by a single event type. + pub fn by_type(t: InvoiceEventType) -> Self { + Self { + event_type: Some(t), + ..Default::default() + } + } + + /// Convenience: filter by an inclusive date range. Returns + /// [`FilterError::InvalidRange`] if `from > to`. + pub fn by_date_range(from_ts: u64, to_ts: u64) -> Result { + if from_ts > to_ts { + return Err(FilterError::InvalidRange); + } + Ok(Self { + from_ts: Some(from_ts), + to_ts: Some(to_ts), + ..Default::default() + }) + } + + /// Merge another filter's set fields into this one (logical AND of the + /// combined predicates), taking the larger `offset`. + pub fn and(mut self, other: &EventFilter) -> Self { + if self.event_type.is_none() { + self.event_type = other.event_type; + } + if self.invoice_id.is_none() { + self.invoice_id = other.invoice_id; + } + if self.from_ts.is_none() { + self.from_ts = other.from_ts; + } + if self.to_ts.is_none() { + self.to_ts = other.to_ts; + } + if self.limit.is_none() { + self.limit = other.limit; + } + self.offset = self.offset.max(other.offset); + self + } +} + +/// Bounded result set returned from a query. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FilterResult { + items: [InvoiceEvent; MAX_RESULTS], + len: usize, +} + +impl FilterResult { + pub fn empty() -> Self { + Self { + items: [InvoiceEvent::default(); MAX_RESULTS], + len: 0, + } + } + /// The matched events, in log order. + pub fn matched(&self) -> &[InvoiceEvent] { + &self.items[..self.len] + } + pub fn len(&self) -> usize { + self.len + } + pub fn is_empty(&self) -> bool { + self.len == 0 + } +} + +/// Bounded in-memory log of normalised invoice events. +pub struct InvoiceEventLog { + items: [InvoiceEvent; MAX_EVENTS], + len: usize, +} + +impl Default for InvoiceEventLog { + fn default() -> Self { + Self { + items: [InvoiceEvent::default(); MAX_EVENTS], + len: 0, + } + } +} + +impl InvoiceEventLog { + pub fn new() -> Self { + Self::default() + } + + pub fn len(&self) -> usize { + self.len + } + pub fn is_empty(&self) -> bool { + self.len == 0 + } + pub fn all(&self) -> &[InvoiceEvent] { + &self.items[..self.len] + } + + /// Append an event. Returns [`FilterError::LogFull`] at capacity. + pub fn push(&mut self, e: InvoiceEvent) -> Result<(), FilterError> { + if self.len >= MAX_EVENTS { + return Err(FilterError::LogFull); + } + self.items[self.len] = e; + self.len += 1; + Ok(()) + } + + /// Does `e` satisfy every set field of `f`? + pub fn matches(e: &InvoiceEvent, f: &EventFilter) -> bool { + if let Some(t) = f.event_type { + if e.event_type != t { + return false; + } + } + if let Some(id) = f.invoice_id { + if e.invoice_id != id { + return false; + } + } + if let Some(from) = f.from_ts { + if e.timestamp < from { + return false; + } + } + if let Some(to) = f.to_ts { + if e.timestamp > to { + return false; + } + } + true + } + + /// Count matching events without materialising them. + pub fn count(&self, f: &EventFilter) -> u32 { + let mut c = 0u32; + for e in self.all() { + if Self::matches(e, f) { + c += 1; + } + } + c + } + + /// Collect matching events, applying `offset`/`limit` with early exit + /// once the limit is reached, so a small `limit` over a large log does not + /// scan the whole buffer. + pub fn query(&self, f: &EventFilter) -> FilterResult { + let mut res = FilterResult::empty(); + let cap = f.limit.map(|l| l as usize).unwrap_or(MAX_RESULTS); + let cap = core::cmp::min(cap, MAX_RESULTS); + let mut skipped = 0u32; + for e in self.all() { + if Self::matches(e, f) { + if skipped < f.offset { + skipped += 1; + continue; + } + if res.len >= cap { + break; + } + res.items[res.len] = *e; + res.len += 1; + } + } + res + } + + /// Shorthand: events of a single type. + pub fn filter_by_type(&self, t: InvoiceEventType) -> FilterResult { + self.query(&EventFilter::by_type(t)) + } + + /// Shorthand: events within an inclusive date range. + pub fn filter_by_date_range( + &self, + from_ts: u64, + to_ts: u64, + ) -> Result { + Ok(self.query(&EventFilter::by_date_range(from_ts, to_ts)?)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ev(id: u64, t: InvoiceEventType, ts: u64) -> InvoiceEvent { + InvoiceEvent { + invoice_id: id, + event_type: t, + timestamp: ts, + ledger: (ts / 5) as u32, + seq: ts, + } + } + + #[test] + fn push_and_iterate() { + let mut log = InvoiceEventLog::new(); + assert!(log.is_empty()); + assert!(log.push(ev(1, InvoiceEventType::Created, 100)).is_ok()); + assert!(log.push(ev(1, InvoiceEventType::Paid, 200)).is_ok()); + assert_eq!(log.len(), 2); + assert_eq!(log.all().len(), 2); + assert_eq!(log.all()[0].event_type, InvoiceEventType::Created); + } + + #[test] + fn filter_by_type_works() { + let mut log = InvoiceEventLog::new(); + log.push(ev(1, InvoiceEventType::Created, 100)).unwrap(); + log.push(ev(1, InvoiceEventType::Paid, 110)).unwrap(); + log.push(ev(2, InvoiceEventType::Paid, 120)).unwrap(); + log.push(ev(1, InvoiceEventType::Released, 130)).unwrap(); + let paid = log.filter_by_type(InvoiceEventType::Paid); + assert_eq!(paid.len(), 2); + assert!(paid + .matched() + .iter() + .all(|e| e.event_type == InvoiceEventType::Paid)); + } + + #[test] + fn filter_by_date_range_works() { + let mut log = InvoiceEventLog::new(); + log.push(ev(1, InvoiceEventType::Paid, 100)).unwrap(); + log.push(ev(1, InvoiceEventType::Paid, 150)).unwrap(); + log.push(ev(1, InvoiceEventType::Paid, 200)).unwrap(); + log.push(ev(1, InvoiceEventType::Paid, 250)).unwrap(); + let mid = log.filter_by_date_range(150, 200).unwrap(); + assert_eq!(mid.len(), 2); + assert_eq!(mid.matched()[0].timestamp, 150); + assert_eq!(mid.matched()[1].timestamp, 200); + // Inverted range is rejected. + assert_eq!( + log.filter_by_date_range(200, 100), + Err(FilterError::InvalidRange) + ); + } + + #[test] + fn complex_query_combines_predicates() { + let mut log = InvoiceEventLog::new(); + log.push(ev(1, InvoiceEventType::Paid, 100)).unwrap(); + log.push(ev(2, InvoiceEventType::Paid, 110)).unwrap(); // other invoice + log.push(ev(1, InvoiceEventType::Paid, 90)).unwrap(); // before range + log.push(ev(1, InvoiceEventType::Refunded, 120)).unwrap(); // other type + let f = EventFilter { + event_type: Some(InvoiceEventType::Paid), + invoice_id: Some(1), + from_ts: Some(95), + to_ts: Some(200), + ..Default::default() + }; + let r = log.query(&f); + assert_eq!(r.len(), 1); + assert_eq!(r.matched()[0].invoice_id, 1); + assert_eq!(r.matched()[0].event_type, InvoiceEventType::Paid); + assert_eq!(r.matched()[0].timestamp, 100); + // count-only agrees with the materialised query. + assert_eq!(log.count(&f), 1); + } + + #[test] + fn offset_and_limit_paginate() { + let mut log = InvoiceEventLog::new(); + for i in 0..10u64 { + log.push(ev(1, InvoiceEventType::Paid, 100 + i)).unwrap(); + } + let page = log.query(&EventFilter { + event_type: Some(InvoiceEventType::Paid), + offset: 2, + limit: Some(3), + ..Default::default() + }); + assert_eq!(page.len(), 3); + assert_eq!(page.matched()[0].timestamp, 102); + assert_eq!(page.matched()[2].timestamp, 104); + assert_eq!(log.count(&EventFilter::by_type(InvoiceEventType::Paid)), 10); + } + + #[test] + fn limit_stops_early() { + let mut log = InvoiceEventLog::new(); + for _ in 0..MAX_EVENTS { + log.push(ev(1, InvoiceEventType::Paid, 100)).unwrap(); + } + let r = log.query(&EventFilter { + event_type: Some(InvoiceEventType::Paid), + limit: Some(3), + ..Default::default() + }); + assert_eq!(r.len(), 3); + } + + #[test] + fn log_full_is_rejected() { + let mut log = InvoiceEventLog::new(); + for _ in 0..MAX_EVENTS { + log.push(ev(1, InvoiceEventType::Paid, 100)).unwrap(); + } + assert_eq!( + log.push(ev(1, InvoiceEventType::Paid, 100)), + Err(FilterError::LogFull) + ); + } +} diff --git a/contracts/split/src/lib.rs b/contracts/split/src/lib.rs index 888d6f6..bca3337 100644 --- a/contracts/split/src/lib.rs +++ b/contracts/split/src/lib.rs @@ -77,6 +77,10 @@ const DEFAULT_INVOICE_STORAGE_QUOTA: u64 = 65_536; mod constants; mod error; mod payment_schedule_optimizer; +// Issue #1219: Event filtering and query capabilities for invoice events. +mod invoice_event_filtering; +// Issue #1220: Comprehensive contract state validation. +mod contract_state_validation; mod events; pub mod types; mod validation; diff --git a/docs/ISSUE_1219_INVOICE_EVENT_FILTERING.md b/docs/ISSUE_1219_INVOICE_EVENT_FILTERING.md new file mode 100644 index 0000000..fdc3a95 --- /dev/null +++ b/docs/ISSUE_1219_INVOICE_EVENT_FILTERING.md @@ -0,0 +1,26 @@ +# Issue #1219: invoice event filtering and querying + +`contracts/split/src/invoice_event_filtering.rs` is a first slice of pure +helpers for filtering a bounded in-memory log of normalised invoice events. + +Implemented: + +- `InvoiceEvent` / `InvoiceEventType` — normalised view of the events emitted + by `events.rs` (type mirrors the `split` action topics). +- `InvoiceEventLog` — bounded append-only log (`MAX_EVENTS`), rejects when + full. +- `EventFilter` — composite query; every set field is AND-ed (event type, + invoice id, inclusive date range, `offset`/`limit`). +- `query` — collects matches with `offset`/`limit` and early-exits once the + limit is reached; `count` counts without materialising. +- `filter_by_type` / `filter_by_date_range` shorthands (inverted range + rejected). + +Remaining gaps against the issue: + +- Not wired to contract storage or entrypoints; events are projected in by an + indexer, not read from the on-chain event stream. +- No persisted log across transactions (in-memory only). +- No sort/binary-search optimisation for range queries (linear scan with + early-exit). +- No integration with `contribute`/`release` to populate the log live. diff --git a/docs/ISSUE_1220_CONTRACT_STATE_VALIDATION.md b/docs/ISSUE_1220_CONTRACT_STATE_VALIDATION.md new file mode 100644 index 0000000..3dfb70a --- /dev/null +++ b/docs/ISSUE_1220_CONTRACT_STATE_VALIDATION.md @@ -0,0 +1,32 @@ +# Issue #1220: contract state validation + +`contracts/split/src/contract_state_validation.rs` is a first slice of pure +helpers for validating invoice state transitions, checking invariants, +preventing invalid states, and logging state changes. + +Implemented: + +- `ContractState` — normalised invoice lifecycle states (Draft, Pending, + Funded, PartiallyReleased, Released, Refunded, Expired, Cancelled, Disputed, + Archived). +- `is_valid_transition` / `validate_transition` — explicit allowed edges; a + transition must change state, `Archived` is terminal. +- `check_invariants` / `is_valid_state` — non-negative total, `funded` within + `[0, total_due]`, recipients and deadline required off-draft, and + funding-consistency per state (`Funded`/`Released` fully funded, + `PartiallyReleased` strictly partial). +- `StateChangeLog` — bounded append-only log (`MAX_LOG_ENTRIES`), rejects when + full. +- `apply_transition` — validates the edge, checks the prospective snapshot's + invariants, records the change, and commits the state only once logging + succeeds (atomic; a full log leaves the snapshot untouched). + +Remaining gaps against the issue: + +- Not wired to contract storage or entrypoints; the authoritative status in + `types.rs` is projected in, not read live. +- No persisted log across transactions (in-memory only). +- Invariants cover amount/funding/recipient/deadline consistency, not the full + invoice option surface. +- No integration with `contribute`/`release`/`refund` to enforce transitions on + the real stored invoice.