forked from Predictify-org/predictify-contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation.rs
More file actions
5669 lines (5271 loc) · 190 KB
/
Copy pathvalidation.rs
File metadata and controls
5669 lines (5271 loc) · 190 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(unused_variables)]
extern crate alloc;
use crate::{
config,
errors::Error,
types::{BetLimits, Market, OracleConfig, OracleProvider},
};
use alloc::{string::String as StdString, vec::Vec as AllocVec};
use soroban_sdk::{contracttype, vec, Address, Env, Map, String, Symbol, Vec};
// ===== VALIDATION ERROR TYPES =====
/// Comprehensive validation error types for prediction market operations.
///
/// This enum defines all possible validation failures that can occur within
/// the Predictify Hybrid smart contract. Each error type corresponds to a
/// specific validation domain and provides detailed error categorization
/// for debugging and user feedback.
///
/// # Error Categories
///
/// **Input Validation Errors:**
/// - `InvalidInput`: General input validation failures
/// - `InvalidAddress`: Address format or permission errors
/// - `InvalidString`: String length, format, or content errors
/// - `InvalidNumber`: Numeric range or format errors
/// - `InvalidTimestamp`: Time-related validation errors
/// - `InvalidDuration`: Duration range or format errors
///
/// **Market Validation Errors:**
/// - `InvalidMarket`: Market state or configuration errors
/// - `InvalidOutcome`: Market outcome validation errors
/// - `InvalidStake`: Stake amount or permission errors
/// - `InvalidThreshold`: Threshold value errors
///
/// **System Validation Errors:**
/// - `InvalidOracle`: Oracle configuration or data errors
/// - `InvalidFee`: Fee structure or amount errors
/// - `InvalidVote`: Voting permission or state errors
/// - `InvalidDispute`: Dispute creation or state errors
/// - `InvalidConfig`: Configuration parameter errors
///
/// # Example Usage
///
/// ```rust
/// # use soroban_sdk::{Env, Address, String};
/// # use predictify_hybrid::validation::{ValidationError, InputValidator};
/// # let env = Env::default();
///
/// // Handle address validation error
/// let user_address = Address::generate(&env);
/// match InputValidator::validate_address(&env, &user_address) {
/// Ok(()) => println!("Address is valid"),
/// Err(ValidationError::InvalidAddress) => {
/// println!("Address validation failed");
/// // Handle address error
/// }
/// Err(other_error) => {
/// println!("Unexpected validation error: {:?}", other_error);
/// }
/// }
///
/// // Handle string validation error
/// let market_question = String::from_str(&env, ""); // Empty string
/// match InputValidator::validate_string(&env, &market_question, 10, 500) {
/// Ok(()) => println!("Question is valid"),
/// Err(ValidationError::InvalidString) => {
/// println!("Question validation failed - too short or too long");
/// // Handle string length error
/// }
/// Err(other_error) => {
/// println!("Unexpected validation error: {:?}", other_error);
/// }
/// }
///
/// // Handle number validation error
/// let stake_amount = -1000i128; // Negative stake
/// match InputValidator::validate_positive_number(&stake_amount) {
/// Ok(()) => println!("Stake amount is valid"),
/// Err(ValidationError::InvalidNumber) => {
/// println!("Stake must be positive");
/// // Handle negative number error
/// }
/// Err(other_error) => {
/// println!("Unexpected validation error: {:?}", other_error);
/// }
/// }
/// ```
///
/// # Error Conversion
///
/// Convert validation errors to contract errors:
/// ```rust
/// # use predictify_hybrid::validation::ValidationError;
/// # use predictify_hybrid::errors::Error;
///
/// // Convert validation error to contract error
/// let validation_error = ValidationError::InvalidStake;
/// let contract_error = validation_error.to_contract_error();
///
/// match contract_error {
/// Error::InsufficientStake => {
/// println!("Converted to insufficient stake error");
/// // Handle insufficient stake
/// }
/// _ => {
/// println!("Unexpected contract error conversion");
/// }
/// }
///
/// // Handle multiple validation errors
/// let validation_errors = vec![
/// ValidationError::InvalidAddress,
/// ValidationError::InvalidString,
/// ValidationError::InvalidNumber,
/// ];
///
/// for error in validation_errors {
/// let contract_error = error.to_contract_error();
/// println!("Validation error {:?} -> Contract error {:?}", error, contract_error);
/// }
/// ```
///
/// # Error Handling Patterns
///
/// Common error handling patterns:
/// ```rust
/// # use soroban_sdk::{Env, Address, String};
/// # use predictify_hybrid::validation::{ValidationError, MarketValidator};
/// # use predictify_hybrid::types::{OracleConfig, OracleProvider};
/// # let env = Env::default();
///
/// // Pattern 1: Early return on validation error
/// fn validate_market_creation_params(
/// env: &Env,
/// admin: &Address,
/// question: &String,
/// ) -> Result<(), ValidationError> {
/// // Validate admin address
/// if let Err(e) = InputValidator::validate_address(env, admin) {
/// return Err(e);
/// }
///
/// // Validate question string
/// if let Err(e) = InputValidator::validate_string(env, question, 10, 500) {
/// return Err(e);
/// }
///
/// Ok(())
/// }
///
/// // Pattern 2: Collect all validation errors
/// fn validate_all_market_params(
/// env: &Env,
/// admin: &Address,
/// question: &String,
/// duration: &u32,
/// ) -> Vec<ValidationError> {
/// let mut errors = Vec::new();
///
/// if InputValidator::validate_address(env, admin).is_err() {
/// errors.push(ValidationError::InvalidAddress);
/// }
///
/// if InputValidator::validate_string(env, question, 10, 500).is_err() {
/// errors.push(ValidationError::InvalidString);
/// }
///
/// if InputValidator::validate_duration(duration).is_err() {
/// errors.push(ValidationError::InvalidDuration);
/// }
///
/// errors
/// }
///
/// // Pattern 3: Convert and propagate errors
/// fn create_market_with_validation(
/// env: &Env,
/// admin: &Address,
/// question: &String,
/// ) -> Result<(), Error> {
/// match validate_market_creation_params(env, admin, question) {
/// Ok(()) => {
/// // Proceed with market creation
/// println!("All validations passed, creating market");
/// Ok(())
/// }
/// Err(validation_error) => {
/// // Convert validation error to contract error
/// Err(validation_error.to_contract_error())
/// }
/// }
/// }
/// ```
///
/// # Integration Points
///
/// ValidationError integrates with:
/// - **Contract Error System**: Convert to contract errors for user feedback
/// - **Input Validation**: Categorize input validation failures
/// - **Market Validation**: Handle market-specific validation errors
/// - **Oracle Validation**: Manage oracle configuration errors
/// - **Fee Validation**: Handle fee structure validation errors
/// - **Event System**: Log validation errors for debugging
/// - **Admin System**: Validate administrative operations
///
/// # Error Recovery
///
/// Strategies for error recovery:
/// - **Input Sanitization**: Clean and retry with sanitized input
/// - **Default Values**: Use safe defaults for optional parameters
/// - **User Guidance**: Provide specific error messages for correction
/// - **Graceful Degradation**: Continue with reduced functionality
/// - **Retry Logic**: Implement retry mechanisms for transient errors
#[contracttype]
#[derive(Debug, Clone, PartialEq)]
pub enum ValidationError {
InvalidInput,
InvalidMarket,
InvalidOracle,
InvalidFee,
InvalidVote,
InvalidDispute,
InvalidAddress,
InvalidString,
InvalidNumber,
InvalidTimestamp,
InvalidDuration,
InvalidOutcome,
InvalidStake,
InvalidThreshold,
InvalidConfig,
StringTooLong,
StringTooShort,
NumberOutOfRange,
InvalidAddressFormat,
TimestampOutOfBounds,
ArrayTooLarge,
ArrayTooSmall,
InvalidQuestionFormat,
InvalidOutcomeFormat,
/// Outcome is a duplicate of another outcome (case-insensitive)
DuplicateOutcome,
/// Outcome is ambiguous or too similar to another outcome
AmbiguousOutcome,
/// Outcome normalization failed
OutcomeNormalizationFailed,
}
impl ValidationError {
/// Convert validation error to contract error
pub fn to_contract_error(&self) -> Error {
match self {
ValidationError::InvalidInput => Error::InvalidInput,
ValidationError::InvalidMarket => Error::MarketNotFound,
ValidationError::InvalidOracle => Error::InvalidOracleConfig,
ValidationError::InvalidFee => Error::InvalidFeeConfig,
ValidationError::InvalidVote => Error::AlreadyVoted,
ValidationError::InvalidDispute => Error::AlreadyDisputed,
ValidationError::InvalidAddress => Error::Unauthorized,
ValidationError::InvalidString => Error::InvalidQuestion,
ValidationError::InvalidNumber => Error::InvalidThreshold,
ValidationError::InvalidTimestamp => Error::InvalidDuration,
ValidationError::InvalidDuration => Error::InvalidDuration,
ValidationError::InvalidOutcome => Error::InvalidOutcome,
ValidationError::InvalidStake => Error::InsufficientStake,
ValidationError::InvalidThreshold => Error::InvalidThreshold,
ValidationError::InvalidConfig => Error::InvalidOracleConfig,
ValidationError::StringTooLong => Error::InvalidQuestion,
ValidationError::StringTooShort => Error::InvalidQuestion,
ValidationError::NumberOutOfRange => Error::InvalidThreshold,
ValidationError::InvalidAddressFormat => Error::Unauthorized,
ValidationError::TimestampOutOfBounds => Error::InvalidDuration,
ValidationError::ArrayTooLarge => Error::InvalidOutcomes,
ValidationError::ArrayTooSmall => Error::InvalidOutcomes,
ValidationError::InvalidQuestionFormat => Error::InvalidQuestion,
ValidationError::InvalidOutcomeFormat => Error::InvalidOutcome,
ValidationError::DuplicateOutcome => Error::InvalidOutcomes,
ValidationError::AmbiguousOutcome => Error::InvalidOutcomes,
ValidationError::OutcomeNormalizationFailed => Error::InvalidOutcomes,
}
}
}
// ===== VALIDATION RESULT TYPES =====
/// Comprehensive validation result with detailed information and metrics.
///
/// This structure provides detailed information about validation operations,
/// including success/failure status, error counts, warnings, and recommendations.
/// It enables comprehensive validation reporting and helps developers understand
/// validation outcomes in detail.
///
/// # Core Fields
///
/// **Status Information:**
/// - `is_valid`: Overall validation success status
/// - `error_count`: Number of validation errors encountered
/// - `warning_count`: Number of validation warnings generated
/// - `recommendation_count`: Number of improvement recommendations
///
/// # Example Usage
///
/// ```rust
/// # use predictify_hybrid::validation::ValidationResult;
///
/// // Create a valid result
/// let mut result = ValidationResult::valid();
/// assert!(result.is_valid);
/// assert_eq!(result.error_count, 0);
/// assert_eq!(result.warning_count, 0);
///
/// // Add warnings and recommendations
/// result.add_warning();
/// result.add_recommendation();
///
/// assert!(result.is_valid); // Still valid with warnings
/// assert_eq!(result.warning_count, 1);
/// assert_eq!(result.recommendation_count, 1);
///
/// // Add an error
/// result.add_error();
/// assert!(!result.is_valid); // Now invalid
/// assert_eq!(result.error_count, 1);
/// assert!(result.has_errors());
/// assert!(result.has_warnings());
/// ```
///
/// # Validation Workflow
///
/// Typical validation workflow using ValidationResult:
/// ```rust
/// # use soroban_sdk::{Env, Address, String, Vec};
/// # use predictify_hybrid::validation::{ValidationResult, InputValidator};
/// # let env = Env::default();
///
/// // Start with valid result
/// let mut validation_result = ValidationResult::valid();
///
/// // Validate multiple parameters
/// let admin = Address::generate(&env);
/// let question = String::from_str(&env, "Will BTC reach $100k?");
/// let duration = 30u32;
///
/// // Validate admin address
/// if InputValidator::validate_address(&env, &admin).is_err() {
/// validation_result.add_error();
/// println!("Admin address validation failed");
/// }
///
/// // Validate question length
/// if InputValidator::validate_string(&env, &question, 10, 500).is_err() {
/// validation_result.add_error();
/// println!("Question validation failed");
/// } else if question.len() < 20 {
/// validation_result.add_warning();
/// println!("Question is quite short, consider adding more detail");
/// }
///
/// // Validate duration
/// if InputValidator::validate_duration(&duration).is_err() {
/// validation_result.add_error();
/// println!("Duration validation failed");
/// } else if duration < 7 {
/// validation_result.add_recommendation();
/// println!("Consider longer duration for better market participation");
/// }
///
/// // Check final result
/// if validation_result.is_valid {
/// println!("✓ All validations passed");
/// if validation_result.has_warnings() {
/// println!("⚠ {} warnings generated", validation_result.warning_count);
/// }
/// if validation_result.recommendation_count > 0 {
/// println!("💡 {} recommendations available", validation_result.recommendation_count);
/// }
/// } else {
/// println!("✗ Validation failed with {} errors", validation_result.error_count);
/// }
/// ```
///
/// # Batch Validation
///
/// Handle multiple validation operations:
/// ```rust
/// # use soroban_sdk::{Env, Address, String, Vec};
/// # use predictify_hybrid::validation::{ValidationResult, InputValidator};
/// # let env = Env::default();
///
/// // Validate multiple market parameters
/// fn validate_market_batch(
/// env: &Env,
/// admins: &Vec<Address>,
/// questions: &Vec<String>,
/// durations: &Vec<u32>,
/// ) -> ValidationResult {
/// let mut result = ValidationResult::valid();
///
/// // Validate all admins
/// for (i, admin) in admins.iter().enumerate() {
/// if InputValidator::validate_address(env, admin).is_err() {
/// result.add_error();
/// println!("Admin {} validation failed", i + 1);
/// }
/// }
///
/// // Validate all questions
/// for (i, question) in questions.iter().enumerate() {
/// if InputValidator::validate_string(env, question, 10, 500).is_err() {
/// result.add_error();
/// println!("Question {} validation failed", i + 1);
/// } else if question.len() < 20 {
/// result.add_warning();
/// println!("Question {} is quite short", i + 1);
/// }
/// }
///
/// // Validate all durations
/// for (i, duration) in durations.iter().enumerate() {
/// if InputValidator::validate_duration(duration).is_err() {
/// result.add_error();
/// println!("Duration {} validation failed", i + 1);
/// } else if *duration < 7 {
/// result.add_recommendation();
/// println!("Duration {} could be longer", i + 1);
/// }
/// }
///
/// result
/// }
///
/// // Use batch validation
/// let admins = vec![
/// Address::generate(&env),
/// Address::generate(&env),
/// ];
/// let questions = vec![
/// String::from_str(&env, "Will BTC reach $100k?"),
/// String::from_str(&env, "Will ETH reach $5k?"),
/// ];
/// let durations = vec![30u32, 60u32];
///
/// let batch_result = validate_market_batch(&env, &admins, &questions, &durations);
///
/// println!("Batch validation completed:");
/// println!(" Valid: {}", batch_result.is_valid);
/// println!(" Errors: {}", batch_result.error_count);
/// println!(" Warnings: {}", batch_result.warning_count);
/// println!(" Recommendations: {}", batch_result.recommendation_count);
/// ```
///
/// # Validation Reporting
///
/// Generate detailed validation reports:
/// ```rust
/// # use predictify_hybrid::validation::ValidationResult;
///
/// // Generate validation summary
/// fn generate_validation_report(result: &ValidationResult) -> String {
/// let mut report = String::new();
///
/// if result.is_valid {
/// report.push_str("✓ VALIDATION PASSED\n");
/// } else {
/// report.push_str("✗ VALIDATION FAILED\n");
/// }
///
/// if result.error_count > 0 {
/// report.push_str(&format!("Errors: {}\n", result.error_count));
/// }
///
/// if result.warning_count > 0 {
/// report.push_str(&format!("Warnings: {}\n", result.warning_count));
/// }
///
/// if result.recommendation_count > 0 {
/// report.push_str(&format!("Recommendations: {}\n", result.recommendation_count));
/// }
///
/// report
/// }
///
/// // Example usage
/// let mut result = ValidationResult::valid();
/// result.add_warning();
/// result.add_recommendation();
///
/// let report = generate_validation_report(&result);
/// println!("{}", report);
/// // Output:
/// // ✓ VALIDATION PASSED
/// // Warnings: 1
/// // Recommendations: 1
/// ```
///
/// # Integration Points
///
/// ValidationResult integrates with:
/// - **Input Validation**: Aggregate input validation results
/// - **Market Validation**: Collect market validation outcomes
/// - **Oracle Validation**: Track oracle validation status
/// - **Fee Validation**: Monitor fee validation results
/// - **Admin System**: Validate administrative operations
/// - **Event System**: Log validation outcomes
/// - **User Interface**: Provide detailed validation feedback
///
/// # Best Practices
///
/// Recommendations for using ValidationResult:
/// - **Comprehensive Checking**: Always check both errors and warnings
/// - **User Feedback**: Provide specific feedback based on validation results
/// - **Logging**: Log validation results for debugging and monitoring
/// - **Recovery**: Implement recovery strategies for validation failures
/// - **Performance**: Use batch validation for multiple operations
/// - **Documentation**: Document validation rules and expected outcomes
#[contracttype]
#[derive(Debug, Clone)]
pub struct ValidationResult {
pub is_valid: bool,
pub error_count: u32,
pub warning_count: u32,
pub recommendation_count: u32,
}
impl ValidationResult {
/// Create a valid validation result
pub fn valid() -> Self {
Self {
is_valid: true,
error_count: 0,
warning_count: 0,
recommendation_count: 0,
}
}
/// Create an invalid validation result
pub fn invalid() -> Self {
Self {
is_valid: false,
error_count: 1,
warning_count: 0,
recommendation_count: 0,
}
}
/// Add an error to the validation result
pub fn add_error(&mut self) {
self.is_valid = false;
self.error_count += 1;
}
/// Add a warning to the validation result
pub fn add_warning(&mut self) {
self.warning_count += 1;
}
/// Add a recommendation to the validation result
pub fn add_recommendation(&mut self) {
self.recommendation_count += 1;
}
/// Check if validation result has errors
pub fn has_errors(&self) -> bool {
self.error_count > 0
}
/// Check if validation result has warnings
pub fn has_warnings(&self) -> bool {
self.warning_count > 0
}
}
// ===== COMPREHENSIVE INPUT VALIDATION =====
/// Comprehensive input validation utilities
/// Comprehensive input validation utilities for prediction market operations.
///
/// This utility class provides essential input validation operations for prediction markets,
/// including address validation, string validation, numeric validation, timestamp validation,
/// and duration validation. All validation functions return detailed error information
/// and are optimized for blockchain execution.
///
/// # Core Functionality
///
/// **Address Validation:**
/// - Validate address format and structure
/// - Check address permissions and accessibility
/// - Handle Soroban SDK address constraints
///
/// **String Validation:**
/// - Validate string length within specified bounds
/// - Check string content for validity
/// - Handle Unicode and special character constraints
///
/// **Numeric Validation:**
/// - Validate number ranges and bounds
/// - Check for positive numbers
/// - Handle integer overflow and underflow
///
/// **Timestamp Validation:**
/// - Validate future timestamps for market deadlines
/// - Check timestamp format and range
/// - Handle blockchain time constraints
///
/// **Duration Validation:**
/// - Validate duration ranges for markets
/// - Check minimum and maximum duration limits
/// - Handle duration format and conversion
///
/// # Example Usage
///
/// ```rust
/// # use soroban_sdk::{Env, Address, String};
/// # use predictify_hybrid::validation::{InputValidator, ValidationError};
/// # let env = Env::default();
///
/// // Validate address
/// let user_address = Address::generate(&env);
/// match InputValidator::validate_address(&env, &user_address) {
/// Ok(()) => println!("Address is valid"),
/// Err(ValidationError::InvalidAddress) => {
/// println!("Invalid address format");
/// }
/// Err(e) => println!("Validation error: {:?}", e),
/// }
///
/// // Validate string length
/// let market_question = String::from_str(&env, "Will Bitcoin reach $100,000?");
/// match InputValidator::validate_string(&env, &market_question, 10, 500) {
/// Ok(()) => println!("Question length is valid"),
/// Err(ValidationError::InvalidString) => {
/// println!("Question is too short or too long");
/// }
/// Err(e) => println!("Validation error: {:?}", e),
/// }
///
/// // Validate positive number
/// let stake_amount = 1000000i128; // 1 XLM in stroops
/// match InputValidator::validate_positive_number(&stake_amount) {
/// Ok(()) => println!("Stake amount is positive"),
/// Err(ValidationError::InvalidNumber) => {
/// println!("Stake amount must be positive");
/// }
/// Err(e) => println!("Validation error: {:?}", e),
/// }
///
/// // Validate number range
/// let threshold = 50000000i128; // $50 threshold
/// let min_threshold = 1000000i128; // $1 minimum
/// let max_threshold = 1000000000i128; // $1000 maximum
/// match InputValidator::validate_number_range(&threshold, &min_threshold, &max_threshold) {
/// Ok(()) => println!("Threshold is within valid range"),
/// Err(ValidationError::InvalidNumber) => {
/// println!("Threshold is outside valid range");
/// }
/// Err(e) => println!("Validation error: {:?}", e),
/// }
///
/// // Validate future timestamp
/// let market_deadline = env.ledger().timestamp() + 86400; // 1 day from now
/// match InputValidator::validate_future_timestamp(&env, &market_deadline) {
/// Ok(()) => println!("Deadline is in the future"),
/// Err(ValidationError::InvalidTimestamp) => {
/// println!("Deadline must be in the future");
/// }
/// Err(e) => println!("Validation error: {:?}", e),
/// }
///
/// // Validate duration
/// let market_duration = 30u32; // 30 days
/// match InputValidator::validate_duration(&market_duration) {
/// Ok(()) => println!("Duration is valid"),
/// Err(ValidationError::InvalidDuration) => {
/// println!("Duration is outside valid range");
/// }
/// Err(e) => println!("Validation error: {:?}", e),
/// }
/// ```
///
/// # Address Validation
///
/// Validate addresses for various use cases:
/// ```rust
/// # use soroban_sdk::{Env, Address};
/// # use predictify_hybrid::validation::{InputValidator, ValidationError};
/// # let env = Env::default();
///
/// // Validate market admin address
/// let admin_address = Address::generate(&env);
/// match InputValidator::validate_address(&env, &admin_address) {
/// Ok(()) => {
/// println!("Admin address is valid: {}", admin_address);
/// // Proceed with admin operations
/// }
/// Err(ValidationError::InvalidAddress) => {
/// println!("Invalid admin address format");
/// // Handle invalid address
/// }
/// Err(e) => {
/// println!("Unexpected validation error: {:?}", e);
/// }
/// }
///
/// // Validate multiple participant addresses
/// let participants = vec![
/// Address::generate(&env),
/// Address::generate(&env),
/// Address::generate(&env),
/// ];
///
/// let mut valid_participants = Vec::new();
/// let mut invalid_count = 0;
///
/// for (i, participant) in participants.iter().enumerate() {
/// match InputValidator::validate_address(&env, participant) {
/// Ok(()) => {
/// valid_participants.push(participant.clone());
/// println!("Participant {} is valid", i + 1);
/// }
/// Err(_) => {
/// invalid_count += 1;
/// println!("Participant {} is invalid", i + 1);
/// }
/// }
/// }
///
/// println!("Valid participants: {}", valid_participants.len());
/// println!("Invalid participants: {}", invalid_count);
///
/// // Validate oracle provider address
/// let oracle_address = Address::generate(&env);
/// if InputValidator::validate_address(&env, &oracle_address).is_ok() {
/// println!("Oracle address is valid for price feeds");
/// } else {
/// println!("Oracle address validation failed");
/// }
/// ```
///
/// # String Validation
///
/// Validate strings with length and content constraints:
/// ```rust
/// # use soroban_sdk::{Env, String};
/// # use predictify_hybrid::validation::{InputValidator, ValidationError};
/// # let env = Env::default();
///
/// // Validate market questions
/// let questions = vec![
/// String::from_str(&env, "Will Bitcoin reach $100,000 by the end of 2024?"),
/// String::from_str(&env, "Short?"), // Too short
/// String::from_str(&env, &"A".repeat(600)), // Too long
/// String::from_str(&env, "Will Ethereum reach $5,000 this year?"),
/// ];
///
/// for (i, question) in questions.iter().enumerate() {
/// match InputValidator::validate_string(&env, question, 10, 500) {
/// Ok(()) => {
/// println!("Question {}: ✓ Valid (length: {})", i + 1, question.len());
/// }
/// Err(ValidationError::InvalidString) => {
/// println!("Question {}: ✗ Invalid length ({})", i + 1, question.len());
/// }
/// Err(e) => {
/// println!("Question {}: ✗ Validation error: {:?}", i + 1, e);
/// }
/// }
/// }
///
/// // Validate market descriptions
/// let descriptions = vec![
/// String::from_str(&env, "Detailed market description with comprehensive information about the prediction criteria."),
/// String::from_str(&env, ""), // Empty description
/// String::from_str(&env, "OK"), // Too short
/// ];
///
/// for (i, description) in descriptions.iter().enumerate() {
/// match InputValidator::validate_string(&env, description, 20, 1000) {
/// Ok(()) => {
/// println!("Description {}: ✓ Valid", i + 1);
/// }
/// Err(ValidationError::InvalidString) => {
/// println!("Description {}: ✗ Length must be 20-1000 characters", i + 1);
/// }
/// Err(e) => {
/// println!("Description {}: ✗ Error: {:?}", i + 1, e);
/// }
/// }
/// }
///
/// // Validate oracle feed IDs
/// let feed_ids = vec![
/// String::from_str(&env, "BTC/USD"),
/// String::from_str(&env, "ETH/USD"),
/// String::from_str(&env, "XLM/USD"),
/// String::from_str(&env, "A"), // Too short
/// ];
///
/// for (i, feed_id) in feed_ids.iter().enumerate() {
/// match InputValidator::validate_string(&env, feed_id, 3, 50) {
/// Ok(()) => {
/// println!("Feed ID {}: ✓ Valid ({})", i + 1, feed_id);
/// }
/// Err(ValidationError::InvalidString) => {
/// println!("Feed ID {}: ✗ Invalid format", i + 1);
/// }
/// Err(e) => {
/// println!("Feed ID {}: ✗ Error: {:?}", i + 1, e);
/// }
/// }
/// }
/// ```
///
/// # Numeric Validation
///
/// Validate numbers with range and positivity constraints:
/// ```rust
/// # use predictify_hybrid::validation::{InputValidator, ValidationError};
///
/// // Validate stake amounts
/// let stake_amounts = vec![
/// 1000000i128, // 1 XLM - valid
/// -500000i128, // Negative - invalid
/// 0i128, // Zero - invalid for stakes
/// 100000000i128, // 100 XLM - valid
/// ];
///
/// for (i, stake) in stake_amounts.iter().enumerate() {
/// match InputValidator::validate_positive_number(stake) {
/// Ok(()) => {
/// println!("Stake {}: ✓ Valid ({} stroops)", i + 1, stake);
/// }
/// Err(ValidationError::InvalidNumber) => {
/// println!("Stake {}: ✗ Must be positive ({} stroops)", i + 1, stake);
/// }
/// Err(e) => {
/// println!("Stake {}: ✗ Error: {:?}", i + 1, e);
/// }
/// }
/// }
///
/// // Validate threshold ranges
/// let thresholds = vec![
/// (50000000i128, 1000000i128, 100000000i128), // $50, valid range $1-$100
/// (500000i128, 1000000i128, 100000000i128), // $0.50, below minimum
/// (150000000i128, 1000000i128, 100000000i128), // $150, above maximum
/// (25000000i128, 1000000i128, 100000000i128), // $25, valid
/// ];
///
/// for (i, (threshold, min, max)) in thresholds.iter().enumerate() {
/// match InputValidator::validate_number_range(threshold, min, max) {
/// Ok(()) => {
/// println!("Threshold {}: ✓ Valid (${:.2})", i + 1, *threshold as f64 / 1_000_000.0);
/// }
/// Err(ValidationError::InvalidNumber) => {
/// println!("Threshold {}: ✗ Outside range ${:.2}-${:.2} (${:.2})",
/// i + 1,
/// *min as f64 / 1_000_000.0,
/// *max as f64 / 1_000_000.0,
/// *threshold as f64 / 1_000_000.0
/// );
/// }
/// Err(e) => {
/// println!("Threshold {}: ✗ Error: {:?}", i + 1, e);
/// }
/// }
/// }
///
/// // Validate fee percentages
/// let fee_percentages = vec![
/// 250i128, // 2.5% - valid
/// -100i128, // Negative - invalid
/// 0i128, // 0% - valid
/// 10000i128, // 100% - might be too high
/// 15000i128, // 150% - definitely too high
/// ];
///
/// let min_fee = 0i128;
/// let max_fee = 1000i128; // 10% maximum
///
/// for (i, fee) in fee_percentages.iter().enumerate() {
/// match InputValidator::validate_number_range(fee, &min_fee, &max_fee) {
/// Ok(()) => {
/// println!("Fee {}: ✓ Valid ({:.2}%)", i + 1, *fee as f64 / 100.0);
/// }
/// Err(ValidationError::InvalidNumber) => {
/// println!("Fee {}: ✗ Must be 0-10% ({:.2}%)", i + 1, *fee as f64 / 100.0);
/// }
/// Err(e) => {
/// println!("Fee {}: ✗ Error: {:?}", i + 1, e);
/// }
/// }
/// }
/// ```
///
/// # Timestamp and Duration Validation
///
/// Validate timestamps and durations for market operations:
/// ```rust
/// # use soroban_sdk::{Env};
/// # use predictify_hybrid::validation::{InputValidator, ValidationError};
/// # let env = Env::default();
///
/// // Get current timestamp
/// let current_time = env.ledger().timestamp();
///
/// // Validate future timestamps
/// let timestamps = vec![
/// current_time - 3600, // 1 hour ago - invalid
/// current_time, // Now - invalid
/// current_time + 3600, // 1 hour from now - valid
/// current_time + 86400, // 1 day from now - valid
/// current_time + 2592000, // 30 days from now - valid
/// ];
///
/// for (i, timestamp) in timestamps.iter().enumerate() {
/// match InputValidator::validate_future_timestamp(&env, timestamp) {
/// Ok(()) => {
/// let hours_from_now = (*timestamp as i64 - current_time as i64) / 3600;
/// println!("Timestamp {}: ✓ Valid ({} hours from now)", i + 1, hours_from_now);
/// }
/// Err(ValidationError::InvalidTimestamp) => {
/// let hours_from_now = (*timestamp as i64 - current_time as i64) / 3600;
/// println!("Timestamp {}: ✗ Must be in future ({} hours from now)", i + 1, hours_from_now);
/// }
/// Err(e) => {
/// println!("Timestamp {}: ✗ Error: {:?}", i + 1, e);
/// }
/// }
/// }
///
/// // Validate market durations
/// let durations = vec![
/// 0u32, // 0 days - invalid
/// 1u32, // 1 day - valid
/// 7u32, // 1 week - valid
/// 30u32, // 1 month - valid
/// 90u32, // 3 months - valid
/// 365u32, // 1 year - valid
/// 400u32, // Over 1 year - might be invalid
/// ];
///
/// for (i, duration) in durations.iter().enumerate() {
/// match InputValidator::validate_duration(duration) {
/// Ok(()) => {
/// println!("Duration {}: ✓ Valid ({} days)", i + 1, duration);
/// }
/// Err(ValidationError::InvalidDuration) => {
/// println!("Duration {}: ✗ Invalid ({} days)", i + 1, duration);
/// }
/// Err(e) => {
/// println!("Duration {}: ✗ Error: {:?}", i + 1, e);
/// }
/// }
/// }
///
/// // Convert durations to timestamps and validate
/// let base_time = current_time;
/// for (i, duration) in durations.iter().enumerate() {
/// let deadline = base_time + (*duration as u64 * 86400); // Convert days to seconds
///
/// match InputValidator::validate_future_timestamp(&env, &deadline) {
/// Ok(()) => {
/// println!("Deadline for duration {}: ✓ Valid", i + 1);
/// }
/// Err(_) => {
/// println!("Deadline for duration {}: ✗ Invalid", i + 1);
/// }
/// }
/// }
/// ```
///
/// # Integration Points
///
/// InputValidator integrates with:
/// - **Market Creation**: Validate all market creation parameters
/// - **User Input**: Validate user-provided data before processing
/// - **Oracle Configuration**: Validate oracle setup parameters
/// - **Fee Configuration**: Validate fee amounts and percentages
/// - **Admin Operations**: Validate administrative parameters
/// - **Voting System**: Validate voting parameters and constraints
/// - **Dispute System**: Validate dispute creation parameters
///
/// # Validation Rules
///
/// Current validation rules and constraints:
/// - **Addresses**: Must be valid Soroban SDK addresses
/// - **Strings**: Length constraints vary by use case (10-500 chars typical)
/// - **Numbers**: Must be positive for stakes, within ranges for thresholds
/// - **Timestamps**: Must be in the future for deadlines
/// - **Durations**: Typically 1-365 days for market duration
///
/// # Performance Considerations
///
/// Input validation is optimized for blockchain execution:
/// - **Fast Validation**: Simple checks with minimal computation
/// - **Early Exit**: Return immediately on first validation failure
/// - **Minimal Memory**: Avoid unnecessary allocations