forked from ApexChainx/ApexChainx-Contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
2713 lines (2419 loc) · 106 KB
/
Copy pathlib.rs
File metadata and controls
2713 lines (2419 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![no_std]
extern crate alloc;
use soroban_sdk::{
contract, contracterror, contractimpl, contracttype, symbol_short, Address, Env, Map, String, Symbol, Vec,
};
#[contract]
pub struct SLACalculatorContract;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod fuzz_tests;
#[cfg(test)]
mod schema_migration_tests;
pub mod audit_state;
pub mod config;
pub mod config_bundle;
pub mod config_freeze;
pub mod config_metadata;
pub mod coordination_harness;
pub mod cross_contract_safety;
pub mod calculation;
pub mod error_responses;
pub mod event_correlation;
mod event_schema;
pub mod governance;
pub mod history;
pub mod history_snapshot;
pub mod metadata;
pub mod version_negotiation;
use crate::audit_state::AuditState;
use crate::config_bundle::ConfigBundle;
// -----------------------------------------------------------------------
// Storage Keys
// -----------------------------------------------------------------------
//
// These constants define all on-chain storage keys used by the contract.
// Each key maps to a specific semantic domain. Keys must be:
// - Unique (no duplicate semantic domains)
// - Stable across contract upgrades (new versions add new keys)
// - Within the 9-character Symbol limit for Soroban
//
// References: Issue numbers track the original feature requirements.
/// Admin address — set during initialize, governs config and roles.
pub(crate) const ADMIN_KEY: Symbol = symbol_short!("ADMIN");
/// Operator address — authorized to call calculate_sla. (#28)
pub(crate) const OPERATOR_KEY: Symbol = symbol_short!("OPERATOR");
/// Pending admin for two-step transfer. (#63)
pub(crate) const PENDING_ADMIN_KEY: Symbol = symbol_short!("PADMIN");
/// Pending operator for two-step handoff. (#64)
pub(crate) const PENDING_OP_KEY: Symbol = symbol_short!("POP");
/// Map of severity -> SLAConfig for all configured severity levels.
pub(crate) const CONFIG_KEY: Symbol = symbol_short!("CONFIG");
/// Map of severity -> SLAConfig for admin-defined custom severity levels,
/// distinct from the four canonical entries (critical/high/medium/low). (#93)
pub(crate) const CUSTOM_CONFIG_KEY: Symbol = symbol_short!("CUSTCFG");
/// Boolean flag: true when contract is paused. (#27)
pub(crate) const PAUSED_KEY: Symbol = symbol_short!("PAUSED");
/// Pause metadata (reason, timestamp, caller). (#66)
pub(crate) const PAUSE_INFO_KEY: Symbol = symbol_short!("PAUSEINF");
/// Maximum length (in bytes) for the pause reason string. (#68)
pub(crate) const MAX_REASON_LEN: usize = 256;
/// Cumulative SLA statistics (SLAStats struct). (#29)
pub(crate) const STATS_KEY: Symbol = symbol_short!("STATS");
/// Per-severity weekly calculation counters for telemetry. (#101)
pub(crate) const SEVERITY_CALC_COUNTS_KEY: Symbol = symbol_short!("CALCCNT");
/// Per-severity weekly violation counters for telemetry. (#101)
pub(crate) const SEVERITY_VIOL_COUNTS_KEY: Symbol = symbol_short!("VIOLCNT");
/// Per-severity last calculation ledger snapshot for weekly windowing. (#101)
pub(crate) const LAST_CALCULATION_LEDGER_KEY: Symbol = symbol_short!("CALCLDG");
/// Per-severity last violation ledger snapshot for weekly windowing. (#101)
pub(crate) const LAST_VIOLATION_LEDGER_KEY: Symbol = symbol_short!("VIOLLDG");
/// Ordered list of historical SLAResult entries.
pub(crate) const HISTORY_KEY: Symbol = symbol_short!("HIST");
/// Current on-chain storage schema version number.
pub(crate) const STORAGE_VERSION_KEY: Symbol = symbol_short!("VER");
/// The storage schema version this contract binary expects.
/// Incremented when breaking state changes are introduced.
pub(crate) const STORAGE_VERSION: u32 = 1;
/// Version of the SLAResult schema exposed via get_result_schema().
/// Incremented when result encoding changes in a breaking way.
pub(crate) const RESULT_SCHEMA_VERSION: u32 = 1;
/// Number of named fields in `SLAResult`.
///
/// This constant is the migration guardrail for `get_result_schema()`.
/// It must be updated in the same commit that adds or removes a field from
/// `SLAResult`. The companion test `test_result_schema_field_count_sentinel`
/// in `schema_migration_tests.rs` will fail CI if the struct layout changes
/// without a corresponding update to this constant and `RESULT_SCHEMA_VERSION`.
///
/// **How to update when adding a field:**
/// 1. Add the field to `SLAResult`.
/// 2. Increment this constant.
/// 3. Increment `RESULT_SCHEMA_VERSION` (breaking change).
/// 4. Update `get_result_schema()` if a new symbol descriptor is needed.
/// 5. Add a CHANGELOG entry under `[Unreleased]` → `Changed`.
/// 6. See `docs/result-schema-migration-guard.md` for the full process.
pub(crate) const RESULT_SCHEMA_FIELD_COUNT: u32 = 9;
/// Hard upper bound on retained history entries. (SC-062)
/// Configurable down to 1 via set_retention_limit().
pub(crate) const MAX_HISTORY_SIZE: u32 = 1000;
/// Anti-spam cap on how many retained history entries a single `outage_id` may
/// occupy.
///
/// `calculate_sla` is idempotent while the config hash is unchanged, so the only
/// way one outage can accumulate entries is a config change between submissions
/// (each change opens a new "generation" for that outage). Left uncapped, an
/// operator that resubmits the same outage after every config update can evict
/// every other outage from the retained window, so this bounds a single outage's
/// share of it.
///
/// Counted from the history scan `calculate_sla` already performs: no extra
/// storage key, no migration, and no dependency on call ordering. Admin pruning
/// (`prune_history` / `prune_history_by_age`) frees headroom again.
pub(crate) const MAX_RECALCS_PER_OUTAGE: u32 = 16;
/// Optional configurable retention limit override. (SC-013)
/// When set, overrides MAX_HISTORY_SIZE for history trimming.
pub(crate) const RETENTION_LIMIT_KEY: Symbol = symbol_short!("RETLIM");
/// On-chain key storing the ledger sequence of the last config update. Re-exported
/// here so the storage-key namespace regression test catches any future collisions.
pub use crate::config_metadata::LAST_CFG_UPDATE_KEY;
// -----------------------------------------------------------------------
// Event Constants
// -----------------------------------------------------------------------
//
// All events use a standardised 3-topic layout:
// topic[0] = event name (Symbol constant below)
// topic[1] = event version ("v1")
// topic[2] = event-specific context (severity, caller address, etc.)
//
// Payload field ordering and types are defined below per event variant.
// Breaking changes must increment the version symbol (v2, v3, ...).
// Additive fields (appended to the end) are NOT considered breaking.
//
// Full schema documentation: event_schema.rs
//
// ===== Event Payload Schemas =====
//
// sla_calc → (outage_id: Symbol, status: Symbol, payment_type: Symbol,
// rating: Symbol, mttr_minutes: u32, threshold_minutes: u32,
// amount: i128)
// context: severity Symbol
//
// cfg_upd → (threshold_minutes: u32, penalty_per_minute: i128,
// reward_base: i128)
// context: severity Symbol
//
// paused → (true,)
// context: caller Address
//
// unpause → (false,)
// context: caller Address
//
// op_set → (new_operator: Address,)
// context: caller Address
//
// pruned → (removed_count: u32, kept_count: u32)
// context: caller Address
//
// pruned_a → (removed_count: u32, kept_count: u32)
// context: caller Address
//
// adm_prop → (new_admin: Address,)
// context: caller Address
//
// adm_acc → ()
// context: caller Address
//
// adm_can → ()
// context: caller Address
//
// adm_ren → ()
// context: caller Address
//
// op_prop → (new_operator: Address,)
// context: caller Address
//
// op_acc → ()
// context: caller Address
//
// op_can → ()
// context: caller Address
//
// set_int → (outage_id: Symbol, status: Symbol, payment_type: Symbol,
// amount: i128, config_version_hash: u64, recorded_at: u64)
// context: severity Symbol
//
// stats_sat → (field: Symbol, previous_value: i128, attempted_increment: i128)
// context: counter_name Symbol
// -----------------------------------------------------------------------
/// Emitted on successful SLA calculation. Primary event for backend consumers.
pub(crate) const EVENT_SLA_CALC: Symbol = symbol_short!("sla_calc");
/// Emitted alongside sla_calc for settlement intent reconciliation.
pub(crate) const EVENT_SETTLE_INTENT: Symbol = symbol_short!("set_int");
/// Emitted when configuration is updated via set_config.
pub(crate) const EVENT_CONFIG_UPD: Symbol = symbol_short!("cfg_upd");
/// Emitted when the contract is paused by admin. (#27)
pub(crate) const EVENT_PAUSED: Symbol = symbol_short!("paused");
/// Emitted when the contract is unpaused by admin. (#27)
pub(crate) const EVENT_UNPAUSED: Symbol = symbol_short!("unpause");
/// Emitted when the operator address is changed. (#28)
pub(crate) const EVENT_OP_SET: Symbol = symbol_short!("op_set");
/// Emitted after a prune_history call removes entries.
pub(crate) const EVENT_PRUNED: Symbol = symbol_short!("pruned");
/// Emitted after a prune_history_by_age call removes entries. (SC-063)
pub(crate) const EVENT_PRUNED_AGE: Symbol = symbol_short!("pruned_a");
/// Emitted when a new admin is proposed. (#63)
pub(crate) const EVENT_ADMIN_PROP: Symbol = symbol_short!("adm_prop");
/// Emitted when a pending admin proposal is accepted. (#63)
pub(crate) const EVENT_ADMIN_ACC: Symbol = symbol_short!("adm_acc");
/// Emitted when a pending admin proposal is cancelled. (SC-024)
pub(crate) const EVENT_ADMIN_CAN: Symbol = symbol_short!("adm_can");
/// Emitted when the admin permanently renounces their role. (#65)
pub(crate) const EVENT_ADMIN_REN: Symbol = symbol_short!("adm_ren");
/// Emitted when a new operator is proposed. (#64)
pub(crate) const EVENT_OP_PROP: Symbol = symbol_short!("op_prop");
/// Emitted when a pending operator proposal is accepted. (#64)
pub(crate) const EVENT_OP_ACC: Symbol = symbol_short!("op_acc");
/// Emitted when a pending operator proposal is cancelled. (SC-024)
pub(crate) const EVENT_OP_CAN: Symbol = symbol_short!("op_can");
/// Emitted when the configuration is frozen by admin.
pub(crate) const EVENT_CONFIG_FREEZE: Symbol = symbol_short!("cfg_frz");
/// Emitted when the configuration is unfrozen by admin.
pub(crate) const EVENT_CONFIG_UNFREEZE: Symbol = symbol_short!("cfg_unfrz");
/// Emitted when a running-stats counter saturates during increment_stats.
/// Signals backend indexers that the on-chain total capped and now
/// under-reports true economic exposure. (SC-W5-047)
pub(crate) const EVENT_STATS_SAT: Symbol = symbol_short!("stats_sat");
/// Canonical event version symbol used by all events.
pub(crate) const EVENT_VERSION: Symbol = symbol_short!("v1");
// -----------------------------------------------------------------------
// Error Codes
// -----------------------------------------------------------------------
//
// All contract errors are represented as a u32 discriminant in the SLAError
// enum. Backend consumers can retrieve the full catalogue via
// `get_failure_schema()` which maps each code to a machine-readable label
// and human-readable description.
//
// Error codes are stable: once assigned, a code is never reused.
// New codes are appended to the end of the enum.
// -----------------------------------------------------------------------
/// Contract has already been initialized — cannot initialize twice.
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(u32)]
pub enum SLAError {
/// initialize() was already called.
AlreadyInitialized = 1,
/// Contract has not been initialized yet.
NotInitialized = 2,
/// Caller lacks the required role (admin or operator).
Unauthorized = 3,
/// No configuration found for the given severity.
ConfigNotFound = 4,
/// On-chain storage version does not match binary expectation.
VersionMismatch = 5,
/// Contract is paused — state-changing operations are blocked. (#27)
ContractPaused = 6,
/// No pending transfer exists to accept or cancel. (#63, #64)
NoPendingTransfer = 7,
/// Threshold minutes outside valid range or severity-specific limit. (#70)
InvalidThreshold = 8,
/// Penalty per minute outside valid range or severity-specific limit. (#70)
InvalidPenalty = 9,
/// Reward base outside valid range. (#70)
InvalidReward = 10,
/// Severity not in supported list. (#70)
InvalidSeverity = 11,
/// Retention limit must be between 1 and MAX_HISTORY_SIZE. (SC-013)
RetentionLimitOutOfRange = 12,
/// Duplicate `outage_id` with conflicting inputs detected. (SC-W5-046)
///
/// # Semantics
///
/// `calculate_sla` enforces a deterministic duplicate-detection policy on
/// every call:
///
/// | Condition | Behaviour |
/// |---|---|
/// | `outage_id` is **new** (never seen before) | Calculation proceeds normally; result appended to history |
/// | `outage_id` exists **and** the config version hash is **unchanged** **and** the inputs (`mttr_minutes`, `threshold_minutes`) **match** the previous entry exactly | **Idempotent** — returns the previously stored `SLAResult` without mutating state or emitting events |
/// | `outage_id` exists **and** the config version hash is **unchanged** **but** the inputs **differ** | **DuplicateOutageInput** error — the caller submitted contradictory data for the same outage under the same config |
/// | `outage_id` exists **and** the config version hash **changed** | Treated as a **fresh calculation** — the config update invalidates the previous entry, so the new result is appended to history |
///
/// # Consumer guidance
///
/// Backend callers that receive this error should:
/// 1. Check whether the submitted `mttr_minutes` or severity level was
/// entered incorrectly (typo, stale measurement).
/// 2. If the previous calculation was incorrect, the admin must call
/// `prune_history` to remove the conflicting entry before
/// re-submitting with corrected values — or wait for a config
/// update (which changes the version hash and allows a fresh entry).
/// 3. If the intent is genuinely to re-evaluate the same outage under
/// the same config with different MTTR, the outage must receive a
/// new unique `outage_id`.
DuplicateOutageInput = 13,
/// Computed penalty amount is invalid (e.g., overflowed to zero). (SC-W5-046)
InvalidPenaltyAmount = 14,
/// Computed reward amount is invalid (e.g., zero or negative). (SC-W5-046)
InvalidRewardAmount = 15,
/// Configuration is frozen — config changes are blocked.
ConfigFrozen = 16,
/// Input parameter violates documented constraints (e.g., reason too long). (#68)
InvalidInput = 17,
/// Custom severity referenced but not registered. (#93)
SeverityNotInSet = 18,
/// Outage already occupies MAX_RECALCS_PER_OUTAGE retained history entries.
OutageRecalcLimit = 19,
}
// -----------------------------------------------------------------------
// Core Data Types
// -----------------------------------------------------------------------
//
// These types form the contract's public API surface. They are serialised
// and deserialised by the Soroban SDK and exposed to backend consumers
// through read-only views and event payloads.
//
// All types derive Clone, Debug, and PartialEq for testability.
// Types marked #[contracttype] are Soroban-contract-compatible.
// -----------------------------------------------------------------------
/// Configuration parameters for a single severity level.
/// Each severity (critical, high, medium, low) has its own SLAConfig.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SLAConfig {
/// Maximum allowed repair time in minutes before SLA is violated.
pub threshold_minutes: u32,
/// Penalty amount charged per minute of overtime (positive integer).
pub penalty_per_minute: i128,
/// Base reward amount for meeting SLA targets (positive integer).
pub reward_base: i128,
}
/// Complete result of an SLA calculation, returned by calculate_sla
/// and calculate_sla_view.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SLAResult {
/// Unique identifier for the outage event.
pub outage_id: Symbol,
/// SLA outcome: "met" (achieved) or "viol" (violated).
pub status: Symbol,
/// Measured time to repair in minutes.
pub mttr_minutes: u32,
/// Threshold that was applied for this severity.
pub threshold_minutes: u32,
/// Financial outcome: negative = penalty, positive = reward.
pub amount: i128,
/// Payment classification: "rew" (reward) or "pen" (penalty).
pub payment_type: Symbol,
/// Performance rating: "top" | "excel" | "good" | "poor".
pub rating: Symbol,
/// Deterministic hash of the config used for this evaluation.
pub config_version_hash: u64,
/// Ledger timestamp at calculation time. (SC-063)
pub recorded_at: u64,
}
/// A single severity-to-config mapping entry in a config snapshot.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SLAConfigEntry {
/// Severity level (critical, high, medium, low).
pub severity: Symbol,
/// Configuration parameters for this severity.
pub config: SLAConfig,
}
/// Ordered snapshot of all severity configurations, suitable for backend
/// consumption. Entries are in canonical severity order.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SLAConfigSnapshot {
/// Schema version label (e.g., "v1").
pub version: Symbol,
/// Config entries in canonical severity order.
pub entries: Vec<SLAConfigEntry>,
}
/// Describes the result encoding schema for backend consumers.
/// Backends use this to interpret SLA result symbols without
/// hard-coding symbol values.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SLAResultSchema {
/// Schema version label.
pub version: Symbol,
/// Numeric schema version (incremented on breaking changes).
pub schema_version: u32,
/// Number of named fields in `SLAResult` at this schema version.
/// Backends can compare this against their own deserialization code to
/// detect layout drift without parsing the full field list.
pub result_field_count: u32,
/// Symbol for SLA met status.
pub status_met: Symbol,
/// Symbol for SLA violated status.
pub status_violated: Symbol,
/// Symbol for reward payment type.
pub payment_reward: Symbol,
/// Symbol for penalty payment type.
pub payment_penalty: Symbol,
/// Symbol for exceptional rating.
pub rating_exceptional: Symbol,
/// Symbol for excellent rating.
pub rating_excellent: Symbol,
/// Symbol for good rating.
pub rating_good: Symbol,
/// Symbol for poor rating.
pub rating_poor: Symbol,
/// Whether the SLAResult includes config_version_hash.
pub includes_config_version_hash: bool,
/// Deprecated symbols that are still emitted for backward compatibility.
/// Each entry is (deprecated_symbol, replacement_symbol, deprecated_at_schema_version).
pub deprecated_symbols: Vec<DeprecatedSymbol>,
}
/// A deprecated symbol mapping that is still emitted for backward compatibility.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DeprecatedSymbol {
/// The deprecated symbol still present in events.
pub old_symbol: Symbol,
/// The replacement symbol that supersedes it.
pub new_symbol: Symbol,
/// The schema version at which this deprecation was introduced.
pub deprecated_at: u32,
/// The schema version at which the old symbol will be removed (None = not yet determined).
pub removal_version: Option<u32>,
}
/// #60 – Single introspection call for backend clients.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ContractMetadata {
pub contract_name: Symbol,
pub storage_version: u32,
pub result_schema_version: u32,
pub supported_severities: Vec<Symbol>,
pub features: Vec<Symbol>,
}
/// #29 – Cumulative on-chain SLA performance metrics.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SLAStats {
pub total_calculations: u64,
pub total_violations: u64,
pub total_rewards: i128, // sum of all reward amounts paid out
pub total_penalties: i128, // sum of all penalty amounts (stored positive)
}
/// #96 – Per-severity economic exposure for a single SLA event.
///
/// `max_reward` is the top-tier reward (`reward_base * 200 / 100`) — the most
/// a single perfectly-resolved event of this severity can pay out.
///
/// `penalty_per_minute` is the configured per-minute penalty rate — the
/// marginal cost of each overtime minute for a single violated event.
/// The total penalty for one event grows linearly: `overtime_minutes *
/// penalty_per_minute`. There is no contract-level cap on overtime, so the
/// dashboard must apply its own horizon when projecting worst-case exposure.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SeverityExposure {
/// Severity level (critical, high, medium, low).
pub severity: Symbol,
/// Maximum reward for a single top-tier event of this severity.
pub max_reward: i128,
/// Per-overtime-minute penalty rate for a single violated event.
pub penalty_per_minute: i128,
}
/// #96 – Aggregate economic exposure view for backend dashboarding.
///
/// Summarises the maximum potential reward and the per-minute penalty rate
/// across all configured severities. This is a pure view — it reads only
/// the current severity configs and performs no state mutation.
///
/// `total_max_reward` is the sum of `max_reward` across all severities —
/// the total that would be paid out if one top-tier event occurred per
/// severity simultaneously.
///
/// `total_penalty_per_minute` is the sum of `penalty_per_minute` across all
/// severities — the aggregate cost rate if every severity had one ongoing
/// violation simultaneously.
///
/// `breakdown` contains one entry per canonical severity in canonical order
/// (critical → high → medium → low).
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EconomicExposure {
/// Sum of `max_reward` across all severities.
pub total_max_reward: i128,
/// Sum of `penalty_per_minute` across all severities.
pub total_penalty_per_minute: i128,
/// Per-severity breakdown in canonical order.
pub breakdown: Vec<SeverityExposure>,
}
/// #101 – Per-severity weekly violation-rate telemetry snapshot.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SeverityTelemetry {
pub severity: Symbol,
pub calculations: u32,
pub violations: u32,
pub violation_rate: u32,
}
/// #66 – Pause metadata stored when the contract is paused.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PauseInfo {
pub reason: String,
pub paused_at: u64, // ledger timestamp (seconds)
pub paused_by: Address,
}
/// #4 – Metadata about the most recent configuration update.
///
/// Wrapping the ledger sequence in a contract type (rather than exposing it
/// directly as `Option<u32>`) preserves the `Some`/`None` distinction when
/// the value crosses the Soroban contract client boundary — primitives
/// wrapped in `Option` are otherwise flattened and lose the null case.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ConfigUpdateInfo {
/// Ledger sequence at which the most recent `set_config` succeeded.
pub sequence: u32,
}
/// SC-021 – Storage version and migration posture for off-chain consumers.
///
/// Backend consumers should call `get_migration_state` after any contract upgrade
/// to confirm the storage version matches expectations before resuming operations.
/// If `needs_migration` is true, the admin must call `migrate` before the contract
/// will accept versioned calls.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StorageVersionInfo {
/// The version currently stamped in storage.
pub stored_version: u32,
/// The version this contract binary expects.
pub expected_version: u32,
/// True when stored_version != expected_version (migration required).
pub needs_migration: bool,
}
/// SC-W5-046 – Typed failure code mapping entry for backend bridge consumption.
///
/// Each `FailureCode` maps a numeric error code to a machine-readable Symbol
/// label and a short human-readable description. Backends call
/// `get_failure_schema` to obtain the full catalogue at startup.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FailureCode {
/// The numeric error code matching the SLAError discriminant.
pub code: u32,
/// A machine-readable Symbol label (e.g. "AlreadyInitialized").
pub label: Symbol,
/// A short description of the failure condition.
pub description: Symbol,
}
/// SC-W5-046 – Full catalogue of typed failure codes for backend bridge.
///
/// Backend consumers can call `get_failure_schema` once at startup to
/// pre-load all possible failure codes the contract may return. The schema
/// is versioned to allow backwards-compatible additions.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FailureSchema {
/// Schema version for the failure code catalogue.
pub version: Symbol,
/// All known failure codes in ascending order.
pub codes: Vec<FailureCode>,
}
/// #218 – Read-only healthcheck result for backend startup readiness.
///
/// Backend consumers call `healthcheck` before any other operation to confirm
/// the contract is in a safe state. Unlike `get_version_info` which also
/// bypasses `check_version`, this endpoint returns a single boolean outcome
/// for simple load-balancer probes.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HealthcheckResult {
/// True when the contract is initialised and on the current storage version.
pub ready: bool,
/// Human-readable contract name for log correlation.
pub contract_name: Symbol,
/// Human-readable status label: "ok", "not_initialized", "needs_migration".
pub status: Symbol,
}
/// SC-W5-029 – Combined version negotiation response for backend startup handshake.
///
/// Backend consumers call `get_version_info` once at startup (or after an upgrade)
/// to determine whether the contract is safe to use. All version-relevant fields
/// are returned in a single read to minimise round-trips.
///
/// Decision logic for backends:
/// - `needs_migration == true` → block operations, alert admin to call `migrate`
/// - `is_paused == true` → surface pause reason, retry after `unpause`
/// - `storage_version != result_schema_version` (unexpected) → log and alert
/// - otherwise → contract is ready; proceed normally
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VersionInfo {
/// Storage schema version stamped in contract storage.
pub storage_version: u32,
/// Result schema version for SLAResult field layout.
pub result_schema_version: u32,
/// True when stored storage version differs from the binary's expected version.
pub needs_migration: bool,
/// True when the contract is currently paused.
pub is_paused: bool,
/// Human-readable contract name for log correlation.
pub contract_name: Symbol,
}
// -----------------------------------------------------------------------
// Contract implementation
// -----------------------------------------------------------------------
#[contractimpl]
impl SLACalculatorContract {
// -------------------------------------------------------------------
// Initialisation
// -------------------------------------------------------------------
/// Deploy the contract.
/// `admin` – may update config, pause/unpause, and assign the operator.
/// `operator` – may call `calculate_sla`.
pub fn initialize(env: Env, admin: Address, operator: Address) -> Result<(), SLAError> {
if env.storage().instance().has(&ADMIN_KEY) {
return Err(SLAError::AlreadyInitialized);
}
admin.require_auth();
operator.require_auth();
env.storage().instance().set(&ADMIN_KEY, &admin);
env.storage().instance().set(&OPERATOR_KEY, &operator); // #28
env.storage().instance().set(&PAUSED_KEY, &false); // #27
// #29 – initialise zeroed stats
env.storage().instance().set(
&STATS_KEY,
&SLAStats {
total_calculations: 0,
total_violations: 0,
total_rewards: 0,
total_penalties: 0,
},
);
env.storage().instance().set(&SEVERITY_CALC_COUNTS_KEY, &0u128);
env.storage().instance().set(&SEVERITY_VIOL_COUNTS_KEY, &0u128);
env.storage().instance().set(&LAST_CALCULATION_LEDGER_KEY, &0u128);
env.storage().instance().set(&LAST_VIOLATION_LEDGER_KEY, &0u128);
env.storage()
.instance()
.set(&HISTORY_KEY, &Vec::<SLAResult>::new(&env));
let mut configs = Map::<Symbol, SLAConfig>::new(&env);
configs.set(
symbol_short!("critical"),
SLAConfig {
threshold_minutes: 15,
penalty_per_minute: 100,
reward_base: 750,
},
);
configs.set(
symbol_short!("high"),
SLAConfig {
threshold_minutes: 30,
penalty_per_minute: 50,
reward_base: 750,
},
);
configs.set(
symbol_short!("medium"),
SLAConfig {
threshold_minutes: 60,
penalty_per_minute: 25,
reward_base: 750,
},
);
configs.set(
symbol_short!("low"),
SLAConfig {
threshold_minutes: 120,
penalty_per_minute: 10,
reward_base: 600,
},
);
env.storage().instance().set(&CONFIG_KEY, &configs);
Self::write_version(&env);
Ok(())
}
// Initialise any storage keys that may be missing from older schema
// versions. This is intentionally conservative: only set a value when
// the key is absent so migration is idempotent and does not overwrite
// existing state.
fn init_missing_storage_defaults(env: &Env) {
let inst = env.storage().instance();
if !inst.has(&PAUSED_KEY) {
inst.set(&PAUSED_KEY, &false);
}
if !inst.has(&STATS_KEY) {
inst.set(
&STATS_KEY,
&SLAStats {
total_calculations: 0,
total_violations: 0,
total_rewards: 0,
total_penalties: 0,
},
);
}
if !inst.has(&SEVERITY_CALC_COUNTS_KEY) {
inst.set(&SEVERITY_CALC_COUNTS_KEY, &0u128);
}
if !inst.has(&SEVERITY_VIOL_COUNTS_KEY) {
inst.set(&SEVERITY_VIOL_COUNTS_KEY, &0u128);
}
if !inst.has(&LAST_CALCULATION_LEDGER_KEY) {
inst.set(&LAST_CALCULATION_LEDGER_KEY, &0u128);
}
if !inst.has(&LAST_VIOLATION_LEDGER_KEY) {
inst.set(&LAST_VIOLATION_LEDGER_KEY, &0u128);
}
if !inst.has(&HISTORY_KEY) {
inst.set(&HISTORY_KEY, &Vec::<SLAResult>::new(env));
}
if !inst.has(&CONFIG_KEY) {
let mut configs = Map::<Symbol, SLAConfig>::new(env);
configs.set(
symbol_short!("critical"),
SLAConfig {
threshold_minutes: 15,
penalty_per_minute: 100,
reward_base: 750,
},
);
configs.set(
symbol_short!("high"),
SLAConfig {
threshold_minutes: 30,
penalty_per_minute: 50,
reward_base: 750,
},
);
configs.set(
symbol_short!("medium"),
SLAConfig {
threshold_minutes: 60,
penalty_per_minute: 25,
reward_base: 750,
},
);
configs.set(
symbol_short!("low"),
SLAConfig {
threshold_minutes: 120,
penalty_per_minute: 10,
reward_base: 600,
},
);
inst.set(&CONFIG_KEY, &configs);
}
if !inst.has(&CUSTOM_CONFIG_KEY) {
inst.set(&CUSTOM_CONFIG_KEY, &Map::<Symbol, SLAConfig>::new(env));
}
}
// -------------------------------------------------------------------
// #61 – Storage migration harness
// -------------------------------------------------------------------
/// Migrate storage from a previous version to the current one.
///
/// Must be called by admin after a contract upgrade that bumps STORAGE_VERSION.
/// The harness applies each step in sequence (v0→v1, v1→v2, …) so a contract
/// that is multiple versions behind is brought fully up to date in one call.
/// Re-invoking when already current is a safe no-op (idempotent).
/// If an unknown stored version is encountered the call returns
/// `VersionMismatch` without mutating any state.
pub fn migrate(env: Env, caller: Address) -> Result<(), SLAError> {
// Require admin without going through check_version (state may be unversioned)
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&ADMIN_KEY)
.ok_or(SLAError::NotInitialized)?;
if caller != admin {
return Err(SLAError::Unauthorized);
}
let stored: u32 = env.storage().instance().get(&STORAGE_VERSION_KEY).unwrap_or(0);
// Already current – idempotent no-op
if stored == STORAGE_VERSION {
return Ok(());
}
// Reject versions newer than what this binary knows about
if stored > STORAGE_VERSION {
return Err(SLAError::VersionMismatch);
}
// Apply each step in sequence. Each arm must be a pure, atomic
// transformation: read old state → write new state → bump version.
// A future version bump adds a new arm here; existing arms are never
// modified so older migration paths remain auditable.
let mut current = stored;
// v0 → v1: stamp the version; all other fields were set by initialize
if current == 0 {
// Ensure any storage keys that might be missing from older
// deployments are initialised to deterministic defaults before
// we mark the storage version as migrated. This codifies the
// contract: migration arms must initialise newly-added keys.
Self::init_missing_storage_defaults(&env);
env.storage().instance().set(&STORAGE_VERSION_KEY, &1u32);
current = 1;
}
// v1 → v2 (placeholder for the next breaking state change):
// if current == 1 {
// // … transform state …
// env.storage().instance().set(&STORAGE_VERSION_KEY, &2u32);
// current = 2;
// }
// Sanity: after all steps we must be at STORAGE_VERSION
if current != STORAGE_VERSION {
return Err(SLAError::VersionMismatch);
}
env.events().publish(
(
soroban_sdk::Symbol::new(&env, event_schema::EVENT_MIGRATE_DONE),
event_schema::EVENT_VERSION,
caller,
),
(stored, current),
);
Ok(())
}
// -------------------------------------------------------------------
// Role queries
// -------------------------------------------------------------------
pub fn get_admin(env: Env) -> Result<Address, SLAError> {
Self::check_version(&env)?;
env.storage()
.instance()
.get(&ADMIN_KEY)
.ok_or(SLAError::NotInitialized)
}
/// #28 – Returns the current operator address.
pub fn get_operator(env: Env) -> Result<Address, SLAError> {
Self::check_version(&env)?;
env.storage()
.instance()
.get(&OPERATOR_KEY)
.ok_or(SLAError::NotInitialized)
}
// -------------------------------------------------------------------
// #28 – Operator management (admin only)
// -------------------------------------------------------------------
/// Replace the operator address (admin only).
/// Emits an `op_set` event.
pub fn set_operator(env: Env, caller: Address, new_operator: Address) -> Result<(), SLAError> {
Self::check_version(&env)?;
Self::require_admin(&env, &caller)?;
env.storage().instance().set(&OPERATOR_KEY, &new_operator);
env.events()
.publish((EVENT_OP_SET, EVENT_VERSION, caller), (new_operator.clone(),));
Ok(())
}
// -------------------------------------------------------------------
// #63 – Two-step admin transfer
// -------------------------------------------------------------------
/// Propose a new admin. The current admin initiates; the new admin must call `accept_admin`.
pub fn propose_admin(env: Env, caller: Address, new_admin: Address) -> Result<(), SLAError> {
Self::check_version(&env)?;
Self::require_admin(&env, &caller)?;
env.storage().instance().set(&PENDING_ADMIN_KEY, &new_admin);
env.events()
.publish((EVENT_ADMIN_PROP, EVENT_VERSION, caller), (new_admin,));
Ok(())
}
/// Accept a pending admin transfer. Must be called by the proposed new admin.
/// On success the caller becomes admin and the pending proposal is cleared.
pub fn accept_admin(env: Env, caller: Address) -> Result<(), SLAError> {
Self::check_version(&env)?;
caller.require_auth();
let pending: Address = env
.storage()
.instance()
.get(&PENDING_ADMIN_KEY)
.ok_or(SLAError::NoPendingTransfer)?;
if caller != pending {
return Err(SLAError::Unauthorized);
}
env.storage().instance().set(&ADMIN_KEY, &caller);
env.storage().instance().remove(&PENDING_ADMIN_KEY);
env.events().publish((EVENT_ADMIN_ACC, EVENT_VERSION, caller), ());
Ok(())
}
/// Cancel a pending admin transfer. Only the current admin may cancel.
/// Clears the pending proposal without changing the active admin.
/// Returns `NoPendingTransfer` if there is nothing to cancel.
pub fn cancel_admin_proposal(env: Env, caller: Address) -> Result<(), SLAError> {
Self::check_version(&env)?;
Self::require_admin(&env, &caller)?;
if !env.storage().instance().has(&PENDING_ADMIN_KEY) {
return Err(SLAError::NoPendingTransfer);
}