forked from Predictify-org/predictify-contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherr.rs
More file actions
2169 lines (2032 loc) · 83.7 KB
/
Copy patherr.rs
File metadata and controls
2169 lines (2032 loc) · 83.7 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
#![allow(dead_code)]
use alloc::format;
use alloc::string::{String as StdString, ToString};
use soroban_sdk::{contracterror, contracttype, Address, Env, Map, String, Symbol, Vec};
/// Comprehensive error codes for the Predictify Hybrid prediction market contract.
///
/// This enum defines all possible error conditions that can occur during contract operations.
/// Each variant has a unique numeric code (100-504) for efficient error handling and diagnostics.
///
/// # Error Categories
///
/// - **User Operation Errors (100-112)**: Errors related to user actions like voting,
/// betting, or claiming winnings.
/// - **Oracle Errors (200-208)**: Errors related to external data source integration and
/// resolution.
/// - **Validation Errors (300-304)**: Input validation failures.
/// - **General Errors (400-418)**: System state and configuration issues.
/// - **Circuit Breaker Errors (500-504)**: Safety mechanism activation and management.
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum Error {
// ===== USER OPERATION ERRORS (100-112) =====
/// User is not authorized to perform the requested action. Typically returned when
/// a non-admin attempts to call admin-only functions.
Unauthorized = 100,
/// The referenced market does not exist. Market ID may be incorrect or market may
/// have been removed.
MarketNotFound = 101,
/// The market is closed and cannot accept new bets or operations. Market has
/// passed its deadline.
MarketClosed = 102,
/// The market has already been resolved with a final outcome. No further betting is allowed.
MarketResolved = 103,
/// The market outcome has not yet been determined. Oracle resolution is still pending.
MarketNotResolved = 104,
/// The user has no winnings to claim from the market.
NothingToClaim = 105,
/// The user has already claimed their winnings. Duplicate claims are not allowed.
AlreadyClaimed = 106,
/// The stake amount is below the minimum required threshold for the market.
InsufficientStake = 107,
/// The selected outcome is invalid for this market. Check available outcomes.
InvalidOutcome = 108,
/// The user has already voted in this market. Only one vote per user is permitted.
AlreadyVoted = 109,
/// The user has already placed a bet on this market. Duplicate bets are not allowed.
AlreadyBet = 110,
/// Bets have already been placed on this market. The market cannot be updated.
BetsAlreadyPlaced = 111,
/// The user's balance is insufficient for the requested operation.
InsufficientBalance = 112,
// ===== ORACLE ERRORS =====
/// The oracle service is unavailable. External data source may be temporarily
/// down or unreachable.
OracleUnavailable = 200,
/// The oracle configuration is invalid. Check oracle address, asset code, and other parameters.
InvalidOracleConfig = 201,
/// Oracle data is stale and exceeds the freshness threshold. Market resolution is delayed.
OracleStale = 202,
/// Oracle consensus could not be achieved among multiple oracle instances.
OracleNoConsensus = 203,
/// Oracle result has already been verified and confirmed. No further verification is needed.
OracleVerified = 204,
/// Market is not ready for oracle verification. Check market state and deadlines.
MarketNotReady = 205,
/// The fallback oracle is unavailable or in an unhealthy state. Cannot proceed with resolution.
FallbackOracleUnavailable = 206,
/// Resolution timeout has been reached. Market cannot be resolved within the allowed timeframe.
ResolutionTimeoutReached = 207,
/// Oracle confidence interval is too wide. Accuracy threshold not met for reliable resolution.
OracleConfidenceTooWide = 208,
/// Invalid oracle feed ID
InvalidOracleFeed = 209,
/// Oracle callback authentication failed. Signature verification or authorization check failed.
OracleCallbackAuthFailed = 210,
/// Oracle callback not authorized. Caller is not in the authorized oracle whitelist.
OracleCallbackUnauthorized = 211,
/// Oracle callback signature is invalid or malformed.
OracleCallbackInvalidSignature = 212,
/// Oracle callback replay detected. Nonce or timestamp already used.
OracleCallbackReplayDetected = 213,
/// Oracle callback timeout. Response time exceeded maximum allowed duration.
OracleCallbackTimeout = 214,
// ===== VALIDATION ERRORS =====
/// Market question is empty or invalid. Question must be non-empty and descriptive.
InvalidQuestion = 300,
/// Invalid outcomes provided. Must have 2+ outcomes, all non-empty, with no duplicates.
InvalidOutcomes = 301,
/// Market duration is invalid. Duration must be between 1 and 365 days.
InvalidDuration = 302,
/// Threshold value is invalid or out of acceptable range.
InvalidThreshold = 303,
/// Comparison operator is invalid or not supported.
InvalidComparison = 304,
// ===== GENERAL ERRORS =====
/// Contract is in an invalid or unexpected state. Manual intervention may be required.
InvalidState = 400,
/// General input validation failed. Check parameters and try again.
InvalidInput = 401,
/// Platform fee configuration is invalid. Fee must be between 0% and 10%.
InvalidFeeConfig = 402,
/// Required configuration not found. Market or system configuration is missing.
ConfigNotFound = 403,
/// Market has already been disputed. Only one dispute per market is allowed.
AlreadyDisputed = 404,
/// The dispute voting period has expired. No further votes can be cast.
DisputeVoteExpired = 405,
/// Dispute voting is not allowed at this time. Check market state.
DisputeVoteDenied = 406,
/// User has already voted in this dispute. Duplicate votes are not allowed.
DisputeAlreadyVoted = 407,
/// Dispute resolution conditions are not met. Requirements may not be satisfied.
DisputeCondNotMet = 408,
/// Fee distribution for dispute resolution failed. Check balances and permissions.
DisputeFeeFailed = 409,
/// Generic dispute subsystem error. Check dispute state and configuration.
DisputeError = 410,
/// Unclaimed winnings have already been swept for this market. Repeat sweeps are not allowed.
SweepAlreadyDone = 411,
/// Fee arithmetic overflowed during checked platform-fee calculation.
FeeArithmeticOverflow = 412,
/// Platform fee has already been collected from this market.
FeeAlreadyCollected = 413,
/// No fees are available to collect from this market.
NoFeesToCollect = 414,
/// Extension days value is invalid. Must be between 1 and max allowed days.
InvalidExtensionDays = 415,
/// Market extension is not allowed or would exceed maximum extension limit.
ExtensionDenied = 416,
/// Gas budget cap has been exceeded for the operation.
GasBudgetExceeded = 417,
/// Admin address has not been set. Contract initialization is incomplete.
AdminNotSet = 418,
// ===== METADATA LENGTH LIMIT ERRORS (420-434) =====
/// Market question exceeds maximum allowed length.
QuestionTooLong = 420,
/// Outcome label exceeds maximum allowed length.
OutcomeTooLong = 421,
/// Too many outcomes specified for the market.
TooManyOutcomes = 422,
/// Oracle feed ID exceeds maximum allowed length.
FeedIdTooLong = 423,
/// Comparison operator exceeds maximum allowed length.
ComparisonTooLong = 424,
/// Category string exceeds maximum allowed length.
CategoryTooLong = 425,
/// Tag string exceeds maximum allowed length.
TagTooLong = 426,
/// Too many tags specified for the market.
TooManyTags = 427,
/// Extension reason exceeds maximum allowed length.
ExtensionReasonTooLong = 428,
/// Source identifier exceeds maximum allowed length.
SourceTooLong = 429,
/// Error message exceeds maximum allowed length.
ErrorMessageTooLong = 430,
/// Signature string exceeds maximum allowed length.
SignatureTooLong = 431,
/// Too many extension history entries.
TooManyExtensions = 432,
/// Too many oracle results in multi-oracle aggregation.
TooManyOracleResults = 433,
/// Too many winning outcomes specified.
TooManyWinningOutcomes = 434,
/// The event archive has reached its maximum capacity. Prune old entries before archiving more.
ArchiveFull = 435,
/// Category string is shorter than the minimum allowed length (when a category is set).
CategoryTooShort = 436,
/// Tag string is shorter than the minimum allowed length (non-empty tags only).
TagTooShort = 437,
// ===== CIRCUIT BREAKER ERRORS ====="
/// Circuit breaker has not been initialized. Initialize before use.
CBNotInitialized = 500,
/// Circuit breaker is already open (active). Cannot open again.
CBAlreadyOpen = 501,
/// Circuit breaker is not in open state. Cannot perform recovery.
CBNotOpen = 502,
/// Circuit breaker is open and blocking operations. Emergency halt is active.
CBOpen = 503,
/// Generic circuit breaker subsystem error. Check configuration and state.
CBError = 504,
/// Rate limit exceeded. Too many requests in the time window.
RateLimitExceeded = 505,
}
// ===== ERROR CATEGORIZATION AND RECOVERY SYSTEM =====
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ErrorSeverity {
Low,
Medium,
High,
Critical,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ErrorCategory {
UserOperation,
Oracle,
Validation,
System,
Dispute,
Financial,
Market,
Authentication,
Unknown,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RecoveryStrategy {
Retry,
RetryWithDelay,
AlternativeMethod,
Skip,
Abort,
ManualIntervention,
NoRecovery,
}
/// Runtime context captured at the point of an error.
///
/// This structure captures the relevant state and metadata at the time an error occurs,
/// enabling better diagnostics, recovery strategies, and debugging. All fields except
/// `operation` are optional, allowing flexible context capture.
///
/// # Fields
///
/// * `operation` - The name of the operation that failed (required)
/// * `user_address` - The user performing the operation (if applicable)
/// * `market_id` - The market involved in the error (if applicable)
/// * `context_data` - Additional key-value data for debugging
/// * `timestamp` - Unix timestamp when the error occurred
/// * `call_chain` - Optional stack trace or call chain for debugging
#[contracttype]
#[derive(Clone, Debug)]
pub struct ErrorContext {
/// The operation that failed (required).
pub operation: String,
/// The user address involved in the operation (optional).
pub user_address: Option<Address>,
/// The market ID involved in the operation (optional).
pub market_id: Option<Symbol>,
/// Additional contextual data for debugging (optional).
pub context_data: Map<String, String>,
/// Unix timestamp when the error occurred.
pub timestamp: u64,
/// Optional call chain or stack trace; None when not available.
pub call_chain: Option<Vec<String>>,
}
/// A fully categorized and classified error with recovery information.
///
/// This structure extends a basic error with severity, category, recovery strategy,
/// and helpful messages for both end users and developers. It is produced by
/// `ErrorHandler::categorize_error()`.
///
/// # Fields
///
/// * `error` - The error code (numeric)
/// * `severity` - How critical the error is (Low/Medium/High/Critical)
/// * `category` - The category of error (UserOperation/Oracle/Validation/System/etc.)
/// * `recovery_strategy` - Recommended recovery approach
/// * `context` - Runtime context when the error occurred
/// * `detailed_message` - User-friendly error description
/// * `user_action` - Suggested action for the user
/// * `technical_details` - Technical information for debugging
#[derive(Clone, Debug)]
pub struct DetailedError {
/// The core error code.
pub error: Error,
/// How critical this error is.
pub severity: ErrorSeverity,
/// The category of error.
pub category: ErrorCategory,
/// Recommended recovery strategy for this error.
pub recovery_strategy: RecoveryStrategy,
/// Runtime context captured when the error occurred.
pub context: ErrorContext,
/// User-friendly explanation of the error.
pub detailed_message: String,
/// Recommended action for the user to resolve the error.
pub user_action: String,
/// Technical details for debugging (error code, function, timestamp).
pub technical_details: String,
}
/// Analytics and statistics about contract errors.
///
/// This structure aggregates error metrics for monitoring and diagnostics.
/// Currently a placeholder; full tracking requires persistent storage infrastructure.
///
/// # Fields
///
/// * `total_errors` - Total number of errors recorded
/// * `errors_by_category` - Error count broken down by category
/// * `errors_by_severity` - Error count broken down by severity level
/// * `most_common_errors` - List of most frequently occurring errors
/// * `recovery_success_rate` - Percentage of successful error recoveries (0-10000)
/// * `avg_resolution_time` - Average time to resolve errors (seconds)
#[contracttype]
#[derive(Clone, Debug)]
pub struct ErrorAnalytics {
/// Total number of errors encountered.
pub total_errors: u32,
/// Errors grouped by category.
pub errors_by_category: Map<ErrorCategory, u32>,
/// Errors grouped by severity level.
pub errors_by_severity: Map<ErrorSeverity, u32>,
/// The most frequently occurring error codes.
pub most_common_errors: Vec<String>,
/// Success rate of error recovery (0-10000, where 10000 = 100%).
pub recovery_success_rate: i128,
/// Average time in seconds to resolve errors.
pub avg_resolution_time: u64,
}
// ===== ERROR RECOVERY =====
/// Records an error recovery attempt with full lifecycle information.
///
/// This structure tracks the complete recovery process for an error, including
/// attempts, status, timing, and outcomes. Used for diagnostics and monitoring.
///
/// # Fields
///
/// * `original_error_code` - The numeric code of the original error
/// * `recovery_strategy` - The strategy used ("retry", "fallback", etc.)
/// * `recovery_timestamp` - When recovery was initiated
/// * `recovery_status` - Current status ("pending", "success", "failed")
/// * `recovery_context` - Context from the original error
/// * `recovery_attempts` - Number of recovery attempts made so far
/// * `max_recovery_attempts` - Maximum allowed recovery attempts
/// * `recovery_success_timestamp` - When recovery succeeded (if applicable)
/// * `recovery_failure_reason` - Why recovery failed (if applicable)
#[contracttype]
#[derive(Clone, Debug)]
pub struct ErrorRecovery {
/// The original error code being recovered from.
pub original_error_code: u32,
/// The recovery strategy being employed.
pub recovery_strategy: String,
/// When recovery was initiated (Unix timestamp).
pub recovery_timestamp: u64,
/// Current status of the recovery (pending/success/failed).
pub recovery_status: String,
/// Context from the original error.
pub recovery_context: ErrorContext,
/// Number of recovery attempts made.
pub recovery_attempts: u32,
/// Maximum allowed recovery attempts.
pub max_recovery_attempts: u32,
/// Timestamp of successful recovery (if applicable).
pub recovery_success_timestamp: Option<u64>,
/// Reason for recovery failure (if applicable).
pub recovery_failure_reason: Option<String>,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RecoveryStatus {
Pending,
InProgress,
Success,
Failed,
Exhausted,
Cancelled,
}
/// Result of a recovery attempt.
///
/// # Fields
///
/// * `success` - Whether the recovery succeeded
/// * `recovery_method` - The method/strategy used
/// * `recovery_duration` - Time taken to recover (seconds)
/// * `recovery_data` - Additional data about the recovery
/// * `validation_result` - Whether the recovery result passed validation
#[derive(Clone, Debug)]
pub struct RecoveryResult {
/// Whether recovery was successful.
pub success: bool,
/// The recovery method that was used.
pub recovery_method: String,
/// Time spent on recovery in seconds.
pub recovery_duration: u64,
/// Additional recovery metadata.
pub recovery_data: Map<String, String>,
/// Whether the recovery result passed validation.
pub validation_result: bool,
}
#[contracttype]
#[derive(Clone, Debug)]
pub struct ResiliencePattern {
pub pattern_name: String,
pub pattern_type: ResiliencePatternType,
pub pattern_config: Map<String, String>,
pub enabled: bool,
pub priority: u32,
pub last_used: Option<u64>,
pub success_rate: i128,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ResiliencePatternType {
RetryWithBackoff,
CircuitBreaker,
Bulkhead,
Timeout,
Fallback,
HealthCheck,
RateLimit,
}
/// Status summary of error recovery operations.
///
/// # Fields
///
/// * `total_attempts` - Total recovery attempts made
/// * `successful_recoveries` - Number of successful recoveries
/// * `failed_recoveries` - Number of failed recovery attempts
/// * `active_recoveries` - Number of in-progress recovery operations
/// * `success_rate` - Overall success rate as percentage (0-10000)
/// * `avg_recovery_time` - Average recovery duration in seconds
/// * `last_recovery_timestamp` - When the last recovery occurred
#[contracttype]
#[derive(Clone, Debug)]
pub struct ErrorRecoveryStatus {
/// Total recovery attempts made.
pub total_attempts: u32,
/// Number of successful recoveries.
pub successful_recoveries: u32,
/// Number of failed recovery attempts.
pub failed_recoveries: u32,
/// Number of active/in-progress recovery operations.
pub active_recoveries: u32,
/// Success rate as percentage (0-10000, where 10000 = 100%).
pub success_rate: i128,
/// Average time to resolve errors in seconds.
pub avg_recovery_time: u64,
/// Timestamp of the last recovery operation.
pub last_recovery_timestamp: Option<u64>,
}
// ===== MAIN ERROR HANDLER =====
pub struct ErrorHandler;
impl ErrorHandler {
fn soroban_string_to_host_string(value: &String) -> StdString {
let mut bytes = alloc::vec![0u8; value.len() as usize];
value.copy_into_slice(&mut bytes);
StdString::from_utf8(bytes).unwrap_or_else(|_| StdString::from("invalid_utf8"))
}
// ===== PUBLIC API =====
/// Categorizes an error with full classification, severity, recovery strategy, and messages.
///
/// This is the primary entry point for error handling in the contract. It takes a raw error
/// and context, and produces a fully elaborated `DetailedError` with:
/// - Severity classification (Low/Medium/High/Critical)
/// - Error category (UserOperation/Oracle/Validation/System/etc.)
/// - Recommended recovery strategy
/// - User-friendly error message
/// - Suggested action for the user
/// - Technical details for debugging
///
/// # Parameters
///
/// * `env` - The Soroban environment
/// * `error` - The error code to categorize
/// * `context` - Runtime context when the error occurred
///
/// # Returns
///
/// A fully categorized `DetailedError` with all classification and messaging information.
///
/// # Example
///
/// ```rust,ignore
/// let context = ErrorContext {
/// operation: String::from_str(&env, "place_bet"),
/// user_address: Some(user),
/// market_id: Some(market_id),
/// context_data: Map::new(&env),
/// timestamp: env.ledger().timestamp(),
/// call_chain: None,
/// };
/// let detailed = ErrorHandler::categorize_error(&env, Error::InsufficientBalance, context);
/// ```
pub fn categorize_error(env: &Env, error: Error, context: ErrorContext) -> DetailedError {
let (severity, category, recovery_strategy) = Self::get_error_classification(&error);
let detailed_message = Self::generate_detailed_error_message(env, &error, &context);
let user_action = Self::get_user_action(env, &error, &category);
let technical_details = Self::get_technical_details(env, &error, &context);
DetailedError {
error,
severity,
category,
recovery_strategy,
context,
detailed_message,
user_action,
technical_details,
}
}
/// Generates a detailed, context-aware error message for the end user.
///
/// Produces human-readable error explanations that explain what went wrong
/// and provide guidance. Messages vary by error type and context.
///
/// # Parameters
///
/// * `env` - The Soroban environment
/// * `error` - The error code to generate a message for
/// * `_context` - Runtime context (for future enhancement)
///
/// # Returns
///
/// A `String` containing a user-friendly error message.
pub fn generate_detailed_error_message(
env: &Env,
error: &Error,
_context: &ErrorContext,
) -> String {
let msg = match error {
Error::Unauthorized => {
"Authorization failed. User does not have the required permissions."
}
Error::MarketNotFound => {
"Market not found. The ID may be incorrect or the market has been removed."
}
Error::MarketClosed => "Market is closed and cannot accept new operations.",
Error::OracleUnavailable => {
"Oracle service is unavailable. The external data source may be down."
}
Error::InsufficientStake => {
"Insufficient stake. Please increase the amount to meet the minimum requirement."
}
Error::AlreadyVoted => {
"User has already voted in this market. Only one vote per user is allowed."
}
Error::InvalidInput => "Invalid input. Please check your parameters and try again.",
Error::InvalidState => {
"Invalid system state. The contract may be in an unexpected condition."
}
_ => "An error occurred. Please verify your parameters and try again.",
};
String::from_str(env, msg)
}
/// Attempts error recovery and determines whether the operation may proceed.
///
/// Based on the error type and its recovery strategy, determines if the operation
/// can be retried, skipped, or should be aborted. Implements delay logic for
/// rate-limited recovery scenarios.
///
/// # Parameters
///
/// * `env` - The Soroban environment
/// * `error` - The error to attempt recovery for
/// * `context` - Runtime context from the error occurrence
///
/// # Returns
///
/// * `Ok(true)` - Operation may proceed (recovery succeeded or skip strategy)
/// * `Ok(false)` - Operation must be aborted (permanent failure)
/// * `Err(error)` - Recovery is impossible or requires manual intervention
pub fn handle_error_recovery(
env: &Env,
error: &Error,
context: &ErrorContext,
) -> Result<bool, Error> {
match Self::get_error_recovery_strategy(error) {
RecoveryStrategy::Retry => Ok(true),
RecoveryStrategy::RetryWithDelay => {
let delay_required: u64 = 60;
let current_time = env.ledger().timestamp();
if current_time.saturating_sub(context.timestamp) >= delay_required {
Ok(true)
} else {
Err(Error::InvalidState)
}
}
RecoveryStrategy::AlternativeMethod => match error {
Error::OracleUnavailable => Ok(true),
Error::MarketNotFound => Ok(false),
_ => Ok(false),
},
RecoveryStrategy::Skip => Ok(true),
RecoveryStrategy::Abort => Ok(false),
RecoveryStrategy::ManualIntervention => Err(Error::InvalidState),
RecoveryStrategy::NoRecovery => Ok(false),
}
}
/// Emits an error event for external monitoring and analytics.
///
/// Records the error in the contract's event log, enabling:
/// - External monitoring systems to track errors
/// - Analytics dashboards to visualize error trends
/// - Alerting systems to detect anomalies
///
/// # Parameters
///
/// * `env` - The Soroban environment
/// * `detailed_error` - The fully categorized error to emit
pub fn emit_error_event(env: &Env, detailed_error: &DetailedError) {
use crate::events::EventEmitter;
EventEmitter::emit_error_logged(
env,
detailed_error.error as u32,
&detailed_error.detailed_message,
&detailed_error.technical_details,
detailed_error.context.user_address.clone(),
detailed_error.context.market_id.clone(),
);
}
/// Logs full error details for diagnostics and monitoring.
///
/// Convenience method that emits the error event plus logs technical details.
/// Equivalent to calling `emit_error_event`.
///
/// # Parameters
///
/// * `env` - The Soroban environment
/// * `detailed_error` - The fully categorized error to log
pub fn log_error_details(env: &Env, detailed_error: &DetailedError) {
Self::emit_error_event(env, detailed_error);
}
/// Maps each error variant to its recommended recovery strategy.
///
/// Provides a lookup table from error codes to recovery strategies,
/// enabling automatic recovery logic without duplicating error classification.
///
/// # Error-to-Strategy Mapping
///
/// | Error | Strategy |
/// |-------|----------|
/// | OracleUnavailable | RetryWithDelay |
/// | InvalidInput | Retry |
/// | Unauthorized, MarketClosed | Abort |
/// | AlreadyVoted, AlreadyBet | Skip |
/// | Other | Abort (default) |
///
/// # Parameters
///
/// * `error` - The error code to get recovery strategy for
///
/// # Returns
///
/// The recommended `RecoveryStrategy` for this error.
pub fn get_error_recovery_strategy(error: &Error) -> RecoveryStrategy {
match error {
Error::OracleUnavailable => RecoveryStrategy::RetryWithDelay,
Error::InvalidInput => RecoveryStrategy::Retry,
Error::OracleConfidenceTooWide => RecoveryStrategy::NoRecovery,
Error::MarketNotFound => RecoveryStrategy::AlternativeMethod,
Error::ConfigNotFound => RecoveryStrategy::AlternativeMethod,
Error::AlreadyVoted
| Error::AlreadyBet
| Error::AlreadyClaimed
| Error::FeeAlreadyCollected => RecoveryStrategy::Skip,
Error::Unauthorized | Error::MarketClosed | Error::MarketResolved => {
RecoveryStrategy::Abort
}
Error::AdminNotSet | Error::DisputeFeeFailed => RecoveryStrategy::ManualIntervention,
Error::InvalidState | Error::InvalidOracleConfig => RecoveryStrategy::NoRecovery,
_ => RecoveryStrategy::Abort,
}
}
/// Validates an `ErrorContext` for structural integrity.
///
/// Checks that required fields are present and have valid values.
/// Only the `operation` field is mandatory; all others are optional.
///
/// # Requirements
///
/// * `operation` must be non-empty
/// * All other fields are optional (can be absent)
///
/// # Parameters
///
/// * `context` - The context to validate
///
/// # Returns
///
/// * `Ok(())` - Context is valid
/// * `Err(InvalidInput)` - Context has validation errors
pub fn validate_error_context(context: &ErrorContext) -> Result<(), Error> {
if context.operation.is_empty() {
return Err(Error::InvalidInput);
}
Ok(())
}
/// Gets error analytics and statistics.
///
/// Returns aggregated error metrics for monitoring and diagnostics.
/// Currently returns a zero-state placeholder; full tracking requires
/// persistent storage infrastructure (e.g., storage-backed counters per category).
///
/// # Parameters
///
/// * `env` - The Soroban environment
///
/// # Returns
///
/// An `ErrorAnalytics` structure with current error statistics.
///
/// # Note
///
/// To enable full error tracking, implement persistent counters
/// in contract storage for each error category and severity level.
pub fn get_error_analytics(env: &Env) -> Result<ErrorAnalytics, Error> {
let mut errors_by_category = Map::new(env);
errors_by_category.set(ErrorCategory::UserOperation, 0u32);
errors_by_category.set(ErrorCategory::Oracle, 0u32);
errors_by_category.set(ErrorCategory::Validation, 0u32);
errors_by_category.set(ErrorCategory::System, 0u32);
let mut errors_by_severity = Map::new(env);
errors_by_severity.set(ErrorSeverity::Low, 0u32);
errors_by_severity.set(ErrorSeverity::Medium, 0u32);
errors_by_severity.set(ErrorSeverity::High, 0u32);
errors_by_severity.set(ErrorSeverity::Critical, 0u32);
Ok(ErrorAnalytics {
total_errors: 0,
errors_by_category,
errors_by_severity,
most_common_errors: Vec::new(env),
recovery_success_rate: 0,
avg_resolution_time: 0,
})
}
// ===== RECOVERY LIFECYCLE =====
/// Runs the complete error recovery lifecycle from start to finish.
///
/// Orchestrates the entire recovery process:
/// 1. Validates the error context
/// 2. Determines the appropriate recovery strategy
/// 3. Executes the recovery strategy
/// 4. Records the recovery outcome
/// 5. Emits recovery events for monitoring
///
/// # Parameters
///
/// * `env` - The Soroban environment
/// * `error` - The error to recover from
/// * `context` - Runtime context from the error occurrence
///
/// # Returns
///
/// * `Ok(recovery)` - Recovery record with final status
/// * `Err(error)` - Recovery lifecycle itself failed (validation error)
///
/// # Example
///
/// ```rust,ignore
/// let context = ErrorContext {
/// operation: String::from_str(&env, "resolve_market"),
/// user_address: Some(admin),
/// market_id: Some(market_id),
/// context_data: Map::new(&env),
/// timestamp: env.ledger().timestamp(),
/// call_chain: None,
/// };
/// let recovery = ErrorHandler::recover_from_error(&env, Error::OracleUnavailable, context)?;
/// ```
pub fn recover_from_error(
env: &Env,
error: Error,
context: ErrorContext,
) -> Result<ErrorRecovery, Error> {
Self::validate_error_context(&context)?;
// IMPROVEMENT: strategy string is derived from the same source-of-truth
// enum rather than a parallel match.
let strategy_str =
Self::recovery_strategy_to_str(env, &Self::get_error_recovery_strategy(&error));
let max_attempts = Self::get_max_recovery_attempts(&error);
let mut recovery = ErrorRecovery {
original_error_code: error as u32,
recovery_strategy: strategy_str,
recovery_timestamp: env.ledger().timestamp(),
recovery_status: String::from_str(env, "in_progress"),
recovery_context: context,
recovery_attempts: 1,
max_recovery_attempts: max_attempts,
recovery_success_timestamp: None,
recovery_failure_reason: None,
};
let result = Self::execute_recovery_strategy(env, &recovery)?;
if result.success {
recovery.recovery_status = String::from_str(env, "success");
recovery.recovery_success_timestamp = Some(env.ledger().timestamp());
} else {
recovery.recovery_status = String::from_str(env, "failed");
recovery.recovery_failure_reason =
Some(String::from_str(env, "Recovery strategy did not succeed"));
}
Self::store_recovery_record(env, &recovery)?;
Self::emit_error_recovery_event(env, &recovery);
Ok(recovery)
}
/// Validates a recovery record for internal consistency.
///
/// Checks that:
/// - The recovery context is valid (operation is non-empty)
/// - Recovery attempts do not exceed the maximum allowed
/// - Recovery timestamp is not in the future
///
/// # Parameters
///
/// * `env` - The Soroban environment
/// * `recovery` - The recovery record to validate
///
/// # Returns
///
/// * `Ok(true)` - Recovery record is valid
/// * `Err(InvalidState)` - Recovery record has validation errors
pub fn validate_error_recovery(env: &Env, recovery: &ErrorRecovery) -> Result<bool, Error> {
Self::validate_error_context(&recovery.recovery_context)?;
if recovery.recovery_attempts > recovery.max_recovery_attempts {
return Err(Error::InvalidState);
}
let current_time = env.ledger().timestamp();
if recovery.recovery_timestamp > current_time {
return Err(Error::InvalidState);
}
Ok(true)
}
/// Gets the current status of error recovery operations.
///
/// Returns aggregated statistics about recovery attempts, successes, and failures.
/// Currently returns a zero-state placeholder; full tracking requires persistent storage.
///
/// # Parameters
///
/// * `_env` - The Soroban environment
///
/// # Returns
///
/// An `ErrorRecoveryStatus` with current recovery statistics.
pub fn get_error_recovery_status(_env: &Env) -> Result<ErrorRecoveryStatus, Error> {
Ok(ErrorRecoveryStatus {
total_attempts: 0,
successful_recoveries: 0,
failed_recoveries: 0,
active_recoveries: 0,
success_rate: 0,
avg_recovery_time: 0,
last_recovery_timestamp: None,
})
}
/// Emits an error recovery event for monitoring and analytics.
///
/// Records recovery progress and outcomes in the contract event log.
///
/// # Parameters
///
/// * `env` - The Soroban environment
/// * `recovery` - The recovery record to emit
pub fn emit_error_recovery_event(env: &Env, recovery: &ErrorRecovery) {
use crate::events::EventEmitter;
EventEmitter::emit_error_recovery_event(
env,
recovery.original_error_code,
&recovery.recovery_strategy,
recovery.recovery_status.clone(),
recovery.recovery_attempts,
recovery.recovery_context.user_address.clone(),
recovery.recovery_context.market_id.clone(),
);
}
/// Validates resilience patterns for correctness.
///
/// Checks that resilience patterns are properly configured:
/// - Pattern names are non-empty
/// - Pattern configurations are non-empty
/// - Priority values are between 1-100
/// - Success rates are between 0-10000 (0-100%)
///
/// # Parameters
///
/// * `_env` - The Soroban environment
/// * `patterns` - Vector of resilience patterns to validate
///
/// # Returns
///
/// * `Ok(true)` - All patterns are valid
/// * `Err(InvalidInput)` - One or more patterns have validation errors
pub fn validate_resilience_patterns(
_env: &Env,
patterns: &Vec<ResiliencePattern>,
) -> Result<bool, Error> {
for pattern in patterns.iter() {
if pattern.pattern_name.is_empty() {
return Err(Error::InvalidInput);
}
if pattern.pattern_config.is_empty() {
return Err(Error::InvalidInput);
}
// priority must be 1–100
if pattern.priority == 0 || pattern.priority > 100 {
return Err(Error::InvalidInput);
}
// success_rate is stored as percentage * 100 (0–10 000)
if pattern.success_rate < 0 || pattern.success_rate > 10_000 {
return Err(Error::InvalidInput);
}
}
Ok(true)
}
/// Documents the error recovery procedures for each error type.
///
/// Returns a map of recovery procedure descriptions, useful for:
/// - User documentation
/// - Support team reference
/// - Automated system responses
///
/// # Parameters
///
/// * `env` - The Soroban environment
///
/// # Returns
///
/// A map of recovery procedure names to their descriptions.
pub fn document_error_recovery_procedures(env: &Env) -> Result<Map<String, String>, Error> {
let mut procedures = Map::new(env);
procedures.set(
String::from_str(env, "retry_procedure"),
String::from_str(
env,
"For retryable errors, use exponential backoff (max 3 attempts).",
),
);
procedures.set(
String::from_str(env, "oracle_recovery"),
String::from_str(
env,
"For oracle errors, try fallback oracle or cached data.",
),
);
procedures.set(
String::from_str(env, "validation_recovery"),
String::from_str(
env,
"For validation errors, surface clear messages and prompt retry.",
),
);
procedures.set(
String::from_str(env, "system_recovery"),
String::from_str(
env,
"For critical system errors, require manual intervention.",
),