forked from Predictify-org/predictify-contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
7082 lines (6598 loc) · 249 KB
/
Copy pathlib.rs
File metadata and controls
7082 lines (6598 loc) · 249 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]
#![allow(unused_variables)]
#![allow(unused_assignments)]
#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(unused_mut)]
#![allow(deprecated)]
#![allow(clippy::empty_line_after_doc_comments)]
#![allow(clippy::empty_line_after_outer_attr)]
#![allow(clippy::enum_variant_names)]
#![allow(clippy::all)]
extern crate alloc;
#[cfg(not(test))]
extern crate wee_alloc;
#[cfg(not(test))]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
// Module declarations - all modules enabled
mod admin;
#[cfg(test)]
mod admin_auth_audit_tests;
pub mod audit_trail;
mod balances;
mod batch_operations;
mod bets;
mod circuit_breaker;
mod config;
mod disputes;
mod edge_cases;
mod err;
mod event_archive;
mod events;
mod extensions;
mod fees;
mod gas;
mod governance;
mod graceful_degradation;
mod market_analytics;
mod market_id_generator;
mod markets;
mod metadata_limits;
#[cfg(test)]
mod metadata_limits_tests;
mod monitoring;
#[cfg(test)]
mod multi_admin_multisig_tests;
mod oracles;
mod performance_benchmarks;
mod queries;
mod rate_limiter;
mod recovery;
mod reentrancy_guard;
#[cfg(test)]
mod require_auth_coverage_tests;
mod resolution;
mod statistics;
mod storage;
#[cfg(test)]
mod storage_layout_tests;
pub mod tokens;
mod types;
mod upgrade_manager;
mod utils;
mod validation;
// mod validation_tests; // disabled - API drift
mod versioning;
mod voting;
#[cfg(test)]
mod override_audit_tests;
#[cfg(any())]
mod test_audit_trail;
// #[cfg(any())]
// mod utils_tests;
// THis is the band protocol wasm std_reference.wasm
mod bandprotocol {
soroban_sdk::contractimport!(file = "./std_reference.wasm");
}
#[cfg(any())]
mod circuit_breaker_tests;
// #[cfg(test)]
// mod oracle_fallback_timeout_tests;
// #[cfg(any())]
// mod batch_operations_tests;
// #[cfg(any())]
// mod integration_test;
// #[cfg(any())]
// mod recovery_tests;
// property_based_tests disabled: broader API drift; see dispute_outcome_tally_property_tests
// #[cfg(any())]
// mod upgrade_manager_tests;
#[cfg(test)]
mod upgrade_manager_tests;
// #[cfg(any())]
// mod query_tests;
// #[cfg(test)]
// mod bet_cancellation_tests;
// #[cfg(any())]
// mod bet_tests;
// #[cfg(any())]
// mod gas_test;
// #[cfg(any())]
// mod gas_test;
// #[cfg(any())]
// mod gas_tracking_tests;
// #[cfg(any())]
// mod claim_idempotency_tests;
// All test modules disabled due to API drift - re-enable after fixing
// #[cfg(test)]
// mod balance_tests;
// #[cfg(test)]
// mod event_management_tests;
// #[cfg(test)]
// mod governance_tests;
#[cfg(any())]
mod category_tags_tests;
#[cfg(test)]
mod tie_resolution_tests;
// #[cfg(any())]
// mod statistics_tests;
// #[cfg(any())]
// mod resolution_delay_dispute_window_tests;
#[cfg(test)]
mod property_based_tests;
// dispute_stake_tests.rs extended for #553; enable when legacy setup is updated:
// #[cfg(test)]
// #[path = "tests/dispute_stake_tests.rs"]
// mod dispute_stake_tests;
// #[cfg(test)]
// mod event_creation_tests;
// Re-export commonly used items
use admin::{
AdminAnalyticsResult, AdminInitializer, AdminManager, AdminPermission, AdminRole,
AdminSystemIntegration,
};
pub use err::Error;
// Backwards-compatible re-export for existing module paths.
pub mod errors {
pub use crate::err::*;
}
// pub use queries::QueryManager;
pub use audit_trail::{AuditAction, AuditRecord, AuditTrailHead, AuditTrailManager};
pub use types::*;
use crate::circuit_breaker::CircuitBreaker;
use crate::config::{
ConfigManager, DEFAULT_PLATFORM_FEE_PERCENTAGE, MAX_PLATFORM_FEE_PERCENTAGE,
MIN_PLATFORM_FEE_PERCENTAGE,
};
use crate::events::EventEmitter;
use crate::gas::GasTracker;
use crate::graceful_degradation::{OracleBackup, OracleHealth};
use crate::market_id_generator::MarketIdGenerator;
use alloc::format;
use soroban_sdk::{
contract, contractimpl, panic_with_error, symbol_short, Address, Env, Map, String, Symbol, Vec,
};
impl From<crate::rate_limiter::RateLimiterError> for Error {
fn from(err: crate::rate_limiter::RateLimiterError) -> Self {
match err {
crate::rate_limiter::RateLimiterError::RateLimitExceeded => Error::RateLimitExceeded,
crate::rate_limiter::RateLimiterError::ConfigNotFound => Error::ConfigNotFound,
crate::rate_limiter::RateLimiterError::Unauthorized => Error::Unauthorized,
_ => Error::RateLimitExceeded,
}
}
}
#[contract]
pub struct PredictifyHybrid;
const PERCENTAGE_DENOMINATOR: i128 = 10000;
const ORACLE_FAILURE_PRIMARY_THEN_FALLBACK_REASON: &str =
"Primary oracle failed, fallback also failed";
const ORACLE_FAILURE_PRIMARY_ONLY_REASON: &str = "Primary oracle failed and no fallback configured";
fn resolution_timeout_reached(env: &Env, market: &Market) -> bool {
let current_time = env.ledger().timestamp();
current_time >= market.end_time.saturating_add(market.resolution_timeout)
}
fn automatic_oracle_result_unavailable(env: &Env, config: &OracleConfig) -> Result<String, Error> {
if !config.is_active() {
return Err(Error::OracleUnavailable);
}
Ok(String::from_str(env, "pending"))
}
#[contractimpl]
impl PredictifyHybrid {
// Recovery methods appended later in file after existing functions to maintain readability.
/// Initializes the Predictify Hybrid smart contract with administrator and platform configuration.
///
/// This function must be called once after contract deployment to set up the initial
/// administrative configuration and platform fee structure. It establishes the contract admin who
/// will have privileges to create markets and perform administrative functions, and configures
/// the platform fee percentage for market operations. The call also stores the default
/// development-oriented contract configuration so creation validators have deterministic
/// bounds immediately after deployment.
///
/// # Parameters
///
/// * `env` - The Soroban environment for blockchain operations
/// * `admin` - The address that will be granted administrative privileges
/// * `platform_fee_percentage` - Optional platform fee percentage (0-10%). If `None`, defaults to 2%
/// * `allowed_assets` - Optional list of allowed asset contract addresses. If `None`, defaults are used
///
/// # Errors
///
/// Returns [`Error`] when:
/// - The contract has already been initialized
/// - The admin address is invalid
/// - The platform fee percentage is negative or exceeds 10%
/// - Storage operations fail
///
/// # Example
///
/// ```rust
/// # use soroban_sdk::{Env, Address, Vec};
/// # use predictify_hybrid::PredictifyHybrid;
/// # let env = Env::default();
/// # let admin_address = Address::generate(&env);
///
/// // Initialize with default 2% platform fee
/// PredictifyHybrid::initialize(env.clone(), admin_address.clone(), None, None)?;
///
/// // Or initialize with custom 5% platform fee
/// PredictifyHybrid::initialize(env.clone(), admin_address, Some(5), None)?;
/// ```
///
/// # Platform Fee
///
/// The platform fee is a percentage (0-10%) taken from winning payouts to support
/// platform operations. Fee is applied during payout calculation:
/// - Default: 2% (200 basis points)
/// - Minimum: 0% (no fee)
/// - Maximum: 10% (1000 basis points)
///
/// # Security
///
/// The admin address should be carefully chosen as it will have significant
/// control over the contract's operation, including market creation and resolution.
/// Consider using a multi-signature wallet or governance contract for production.
///
/// # Default Configuration
///
/// `initialize()` stores the default development contract configuration. Integrators that
/// need testnet, mainnet, or custom configuration should update configuration explicitly
/// after initialization through the contract's administrative configuration flows.
///
/// # Re-initialization Prevention
///
/// This function can only be called once. Any subsequent calls will return
/// `Error::InvalidState` to prevent admin takeover attacks.
///
/// # Events
///
/// Emits `contract_initialized` and `platform_fee_set` events on successful initialization.
pub fn initialize(
env: Env,
admin: Address,
platform_fee_percentage: Option<i128>,
allowed_assets: Option<Vec<Address>>,
) -> Result<(), Error> {
// Check for re-initialization attempt (critical security check)
if env
.storage()
.persistent()
.has(&Symbol::new(&env, "platform_fee"))
{
return Err(Error::InvalidState);
}
// Determine platform fee (default 2% if not specified)
let fee_percentage = platform_fee_percentage.unwrap_or(DEFAULT_PLATFORM_FEE_PERCENTAGE);
// Validate fee percentage bounds (0-10%)
if fee_percentage < MIN_PLATFORM_FEE_PERCENTAGE
|| fee_percentage > MAX_PLATFORM_FEE_PERCENTAGE
{
return Err(Error::InvalidFeeConfig);
}
// Initialize admin (includes re-initialization check)
AdminInitializer::initialize(&env, &admin)?;
// Initialize circuit breaker defaults required by write-gated entrypoints.
match crate::circuit_breaker::CircuitBreaker::initialize(&env) {
Ok(_) => (),
Err(e) => panic_with_error!(env, e),
}
// Store platform fee configuration in persistent storage
env.storage()
.persistent()
.set(&Symbol::new(&env, "platform_fee"), &fee_percentage);
// Store default contract configuration so validators have deterministic bounds
let mut default_config = crate::config::ConfigManager::get_development_config(&env);
default_config.fees.platform_fee_percentage = fee_percentage;
if let Err(e) = crate::config::ConfigManager::store_config(&env, &default_config) {
panic_with_error!(env, e);
}
// Initialize rate limiter with permissive defaults (0 = no limit)
let rate_limit_config = crate::rate_limiter::RateLimitConfig {
voting_limit: 0,
dispute_limit: 0,
oracle_call_limit: 0,
bet_limit: 0,
events_per_admin_limit: 0,
time_window_seconds: 3600,
};
env.storage().persistent().set(
&crate::rate_limiter::RateLimiterData::Config,
&rate_limit_config,
);
// Seed default runtime configuration so validators and query paths have
// deterministic bounds immediately after deployment.
let default_config = ConfigManager::get_development_config(&env);
ConfigManager::store_config(&env, &default_config)?;
// Seed permissive-but-valid rate limits so admin entrypoints do not
// fail before a custom policy is configured.
crate::rate_limiter::RateLimiter::new(env.clone())
.init_rate_limiter(
admin.clone(),
crate::rate_limiter::RateLimitConfig {
voting_limit: 10_000,
dispute_limit: 1_000,
oracle_call_limit: 1_000,
bet_limit: 10_000,
events_per_admin_limit: 1_000,
time_window_seconds: 3_600,
},
)
.map_err(Error::from)?;
// Initialize allowed assets
if let Some(assets) = allowed_assets {
// Store custom allowed assets
env.storage()
.persistent()
.set(&Symbol::new(&env, "allowed_assets"), &assets);
} else {
// Initialize with defaults
crate::tokens::TokenRegistry::initialize_with_defaults(&env);
}
// Emit contract initialized event
EventEmitter::emit_contract_initialized(&env, &admin, fee_percentage);
// Emit platform fee set event
EventEmitter::emit_platform_fee_set(&env, fee_percentage, &admin);
Ok(())
}
fn stored_primary_admin(env: &Env) -> Result<Address, Error> {
env.storage()
.persistent()
.get(&Symbol::new(env, "Admin"))
.ok_or(Error::AdminNotSet)
}
fn require_primary_admin(env: &Env, admin: &Address) -> Result<(), Error> {
admin.require_auth();
if &Self::stored_primary_admin(env)? != admin {
return Err(Error::Unauthorized);
}
Ok(())
}
fn require_primary_admin_or_panic(env: &Env, admin: &Address) {
if let Err(error) = Self::require_primary_admin(env, admin) {
panic_with_error!(env, error);
}
}
fn require_initialized_admin_root(env: &Env, admin: &Address) -> Result<(), Error> {
admin.require_auth();
let _ = Self::stored_primary_admin(env)?;
Ok(())
}
fn require_admin_permission(
env: &Env,
admin: &Address,
permission: AdminPermission,
) -> Result<(), Error> {
admin.require_auth();
let stored_admin = Self::stored_primary_admin(env)?;
if &stored_admin == admin {
return Ok(());
}
AdminSystemIntegration::validate_admin_unified(env, admin, permission)
}
/// Deposits funds into the user's balance.
///
/// # Parameters
/// * `env` - The environment.
/// * `user` - The user depositing funds.
/// * `asset` - The asset to deposit (e.g., XLM, BTC, ETH).
/// * `amount` - The amount to deposit.
///
/// # Errors
///
/// Returns [`Error`] when validation, authorization, storage, or subsystem checks fail.
///
/// # Events
///
/// State-changing paths may emit events through internal managers; read-only query paths emit no events.
pub fn deposit(
env: Env,
user: Address,
asset: ReflectorAsset,
amount: i128,
) -> Result<Balance, Error> {
if let Err(e) =
crate::circuit_breaker::CircuitBreaker::require_write_allowed(&env, "deposit")
{
return Err(e);
}
balances::BalanceManager::deposit(&env, user, asset, amount)
}
/// Withdraws funds from the user's balance.
///
/// # Parameters
/// * `env` - The environment.
/// * `user` - The user withdrawing funds.
/// * `asset` - The asset to withdraw.
/// * `amount` - The amount to withdraw.
///
/// # Errors
///
/// Returns [`Error`] when validation, authorization, storage, or subsystem checks fail.
///
/// # Events
///
/// State-changing paths may emit events through internal managers; read-only query paths emit no events.
pub fn withdraw(
env: Env,
user: Address,
asset: ReflectorAsset,
amount: i128,
) -> Result<Balance, Error> {
if let Err(e) =
crate::circuit_breaker::CircuitBreaker::require_write_allowed(&env, "withdraw")
{
return Err(e);
}
if !crate::circuit_breaker::CircuitBreaker::are_withdrawals_allowed(&env)? {
return Err(crate::errors::Error::CBOpen);
}
balances::BalanceManager::withdraw(&env, user, asset, amount)
}
/// Gets the current balance of a user for a specific asset.
///
/// # Parameters
/// * `env` - The environment.
/// * `user` - The user to check.
/// * `asset` - The asset to check.
///
/// # Errors
///
/// This entrypoint surfaces contract errors via panic in internal calls.
///
/// # Events
///
/// State-changing paths may emit events through internal managers; read-only query paths emit no events.
pub fn get_balance(env: Env, user: Address, asset: ReflectorAsset) -> Balance {
storage::BalanceStorage::get_balance(&env, &user, &asset)
}
/// Retrieves a specific audit record by index.
pub fn get_audit_record(env: Env, index: u64) -> Option<AuditRecord> {
AuditTrailManager::get_record(&env, index)
}
/// Retrieves the latest audit records (up to limit).
pub fn get_latest_audit_records(env: Env, limit: u64) -> Vec<AuditRecord> {
AuditTrailManager::get_latest_records(&env, limit)
}
/// Retrieves the current head of the audit trail.
pub fn get_audit_trail_head(env: Env) -> Option<AuditTrailHead> {
AuditTrailManager::get_head(&env)
}
/// Verifies the integrity of the audit trail up to a certain depth.
pub fn verify_audit_integrity(env: Env, depth: u64) -> bool {
AuditTrailManager::verify_integrity(&env, depth)
}
/// Creates a new prediction market with specified parameters and oracle configuration.
///
/// This function allows authorized administrators to create prediction markets
/// with custom questions, possible outcomes, duration, and oracle integration.
/// Each market gets a unique identifier and is stored in persistent contract storage.
///
/// # Multi-Outcome Support
///
/// Markets support 2 to N outcomes, enabling both binary (yes/no) and multi-outcome
/// markets (e.g., Team A / Team B / Draw). The contract handles:
/// - Single winner resolution (one outcome wins)
/// - Tie/multi-winner resolution (multiple outcomes win, pool split proportionally)
/// - Outcome validation during bet placement
/// - Proportional payout distribution for ties
///
/// # Parameters
///
/// * `env` - The Soroban environment for blockchain operations
/// * `admin` - The administrator address creating the market (must be authorized)
/// * `question` - The prediction question (non-empty after trimming and within the supported length bounds)
/// * `outcomes` - Vector of possible outcomes (bounded count, non-empty after trimming, and duplicate-safe)
/// * `duration_days` - Market duration in days (must remain within the supported bounds)
/// * `oracle_config` - Configuration for oracle integration (Reflector, Pyth, etc.)
///
/// # Returns
///
/// Returns a unique `Symbol` that serves as the market identifier for all future operations.
///
/// # Panics
///
/// This function will panic with specific errors if:
/// - `Error::Unauthorized` - Caller is not the contract admin
/// - `Error::InvalidQuestion` - Question is empty, whitespace-only, or outside the supported length bounds
/// - `Error::InvalidOutcomes` - Outcomes violate count, emptiness, duplicate, or ambiguity rules
/// - `Error::InvalidDuration` - Duration is outside the supported bounds
/// - Storage operations fail
///
/// # Example
///
/// ```rust
/// # use soroban_sdk::{Env, Address, String, Vec};
/// # use predictify_hybrid::{PredictifyHybrid, OracleConfig, OracleType};
/// # let env = Env::default();
/// # let admin = Address::generate(&env);
///
/// let question = String::from_str(&env, "Will Bitcoin reach $100,000 by 2024?");
/// let outcomes = vec![
/// String::from_str(&env, "Yes"),
/// String::from_str(&env, "No")
/// ];
/// let oracle_config = OracleConfig {
/// oracle_type: OracleType::Reflector,
/// oracle_contract: Address::generate(&env),
/// asset_code: Some(String::from_str(&env, "BTC")),
/// threshold_value: Some(100000),
/// };
///
/// let market_id = PredictifyHybrid::create_market(
/// env.clone(),
/// admin,
/// question,
/// outcomes,
/// 30, // 30 days duration
/// oracle_config
/// );
/// ```
///
/// # Multi-Outcome Example
///
/// ```rust
/// # use soroban_sdk::{Env, Address, String, Vec};
/// # use predictify_hybrid::{PredictifyHybrid, OracleConfig, OracleProvider};
/// # let env = Env::default();
/// # let admin = Address::generate(&env);
///
/// // Create a 3-outcome market (e.g., match result)
/// let question = String::from_str(&env, "Match result?");
/// let outcomes = vec![
/// &env,
/// String::from_str(&env, "Team A"),
/// String::from_str(&env, "Team B"),
/// String::from_str(&env, "Draw"),
/// ];
/// let oracle_config = OracleConfig::new(
/// OracleProvider::Reflector,
/// String::from_str(&env, "BTC/USD"),
/// 50_000_00,
/// String::from_str(&env, "gt"),
/// );
///
/// let market_id = PredictifyHybrid::create_market(
/// env.clone(),
/// admin,
/// question,
/// outcomes,
/// 30,
/// oracle_config
/// );
/// ```
///
/// # Market State
///
/// New markets are created in `MarketState::Active` state, allowing immediate voting.
/// The market will automatically transition to `MarketState::Ended` when the duration expires.
///
/// # Oracle Resolution Policy
///
/// - `oracle_config` is always the first automatic oracle consulted after market end.
/// - `fallback_oracle_config`, when present, is consulted only after one failed primary attempt.
/// - `resolution_timeout` is enforced per market from `end_time`; automatic oracle resolution stops at
/// `end_time + resolution_timeout`.
///
/// # Errors
///
/// This entrypoint surfaces contract errors via panic in internal calls.
///
/// # Events
///
/// State-changing paths may emit events through internal managers; read-only query paths emit no events.
pub fn create_market(
env: Env,
admin: Address,
question: String,
outcomes: Vec<String>,
duration_days: u32,
oracle_config: OracleConfig,
fallback_oracle_config: Option<OracleConfig>,
resolution_timeout: u64,
min_pool_size: Option<i128>,
bet_deadline_mins_before_end: Option<u64>,
dispute_window_seconds: Option<u64>,
) -> Symbol {
if let Err(e) =
crate::circuit_breaker::CircuitBreaker::require_write_allowed(&env, "create_market")
{
panic_with_error!(env, e);
}
let gas_marker = GasTracker::start_tracking(&env);
Self::require_primary_admin_or_panic(&env, &admin);
// Rate limit market creation to prevent abuse
if let Err(rate_err) = crate::rate_limiter::RateLimiter::new(env.clone())
.rate_limit_admin_events(admin.clone())
{
panic_with_error!(env, Error::from(rate_err));
}
if let Err(e) = crate::validation::CreationValidator::validate_market_creation(
&env,
&question,
&outcomes,
&duration_days,
) {
panic_with_error!(env, e);
}
// Validate oracle configuration
if let Err(e) = oracle_config.validate(&env) {
panic_with_error!(env, e);
}
if let Some(ref fallback) = fallback_oracle_config {
if let Err(e) = fallback.validate(&env) {
panic_with_error!(env, e);
}
}
// Validate duration is positive and within acceptable range
if duration_days == 0 {
panic_with_error!(env, Error::InvalidDuration);
}
// Generate a unique collision-resistant market ID
let market_id = MarketIdGenerator::generate_market_id(&env, &admin);
// Calculate end time
let seconds_per_day: u64 = 24 * 60 * 60;
let duration_seconds: u64 = (duration_days as u64) * seconds_per_day;
let end_time: u64 = env.ledger().timestamp() + duration_seconds;
// Calculate bet deadline
let bet_deadline = match bet_deadline_mins_before_end {
Some(mins) => end_time.saturating_sub(mins * 60),
None => 0,
};
let (has_fallback, fallback_cfg) = match &fallback_oracle_config {
Some(c) => (true, c.clone()),
None => (false, OracleConfig::none_sentinel(&env)),
};
// Create a new market
let market = Market {
admin: admin.clone(),
question: question.clone(),
outcomes: outcomes.clone(),
end_time,
oracle_config,
has_fallback,
fallback_oracle_config: fallback_cfg,
resolution_timeout,
oracle_result: None,
votes: Map::new(&env),
total_staked: 0,
dispute_stakes: Map::new(&env),
stakes: Map::new(&env),
claimed: Map::new(&env),
winning_outcomes: None,
fee_collected: false,
state: MarketState::Active,
total_extension_days: 0,
max_extension_days: 30,
extension_history: Vec::new(&env),
category: None,
tags: Vec::new(&env),
min_pool_size,
bet_deadline,
dispute_window_seconds: dispute_window_seconds.unwrap_or(86400),
winnings_swept: false,
};
// Store the market
env.storage().persistent().set(&market_id, &market);
// Emit events
EventEmitter::emit_market_created(&env, &market_id, &question, &outcomes, &admin, end_time);
// Record statistics
statistics::StatisticsManager::record_market_created(&env);
crate::audit_trail::AuditTrailManager::append_record(
&env,
crate::audit_trail::AuditAction::MarketCreated,
admin.clone(),
Map::new(&env),
);
GasTracker::end_tracking(&env, symbol_short!("create"), gas_marker);
market_id
}
/// Creates a new prediction event with specified parameters.
///
/// This function allows authorized admins to create prediction events
/// with specific descriptions, possible outcomes, and end times. Unlike `create_market`,
/// this function accepts an absolute Unix timestamp for the end time.
///
/// # Parameters
///
/// * `env` - The Soroban environment
/// * `admin` - The administrator address (must be authorized)
/// * `description` - The event description or question
/// * `outcomes` - Vector of possible outcomes
/// * `end_time` - Absolute Unix timestamp for when the event ends
/// * `oracle_config` - Primary oracle configuration for automatic resolution
/// * `fallback_oracle_config` - Optional backup oracle attempted only after one failed primary attempt
/// * `resolution_timeout` - Per-event oracle deadline in seconds, measured from `end_time`
///
/// # Returns
///
/// Returns a unique `Symbol` serving as the event identifier.
///
/// # Panics
///
/// Panics if:
/// - Caller is not the contract admin
/// - validation fails (invalid description, outcomes, or end time)
/// - `resolution_timeout` falls outside the supported bounds
///
/// # Validation Rules
///
/// - `description` follows the same non-empty and length policy as market questions
/// - `outcomes` follow the same count, non-empty, duplicate, and ambiguity rules as market creation
/// - `end_time` must be strictly greater than the current ledger timestamp
///
/// # Errors
///
/// This entrypoint surfaces contract errors via panic in internal calls.
///
/// # Events
///
/// State-changing paths may emit events through internal managers; read-only query paths emit no events.
pub fn create_event(
env: Env,
admin: Address,
description: String,
outcomes: Vec<String>,
end_time: u64,
oracle_config: OracleConfig,
fallback_oracle_config: Option<OracleConfig>,
resolution_timeout: u64,
visibility: EventVisibility,
) -> Symbol {
if let Err(e) =
crate::circuit_breaker::CircuitBreaker::require_write_allowed(&env, "create_event")
{
panic_with_error!(env, e);
}
let gas_marker = GasTracker::start_tracking(&env);
Self::require_primary_admin_or_panic(&env, &admin);
// Rate limit event creation to prevent abuse
if let Err(rate_err) = crate::rate_limiter::RateLimiter::new(env.clone())
.rate_limit_admin_events(admin.clone())
{
panic_with_error!(env, Error::from(rate_err));
}
// Validate inputs
if outcomes.len() < 2 {
panic_with_error!(env, Error::InvalidOutcomes);
}
if description.len() == 0 {
panic_with_error!(env, Error::InvalidQuestion);
}
// Validate oracle configuration
if let Err(e) = oracle_config.validate(&env) {
panic_with_error!(env, e);
}
if let Some(ref fallback) = fallback_oracle_config {
if let Err(e) = fallback.validate(&env) {
panic_with_error!(env, e);
}
}
// Generate a unique collision-resistant event ID (reusing market ID generator)
let event_id = MarketIdGenerator::generate_market_id(&env, &admin);
let (has_fallback, fallback_cfg) = match &fallback_oracle_config {
Some(c) => (true, c.clone()),
None => (false, OracleConfig::none_sentinel(&env)),
};
// Create a new event
let event = Event {
id: event_id.clone(),
description: description.clone(),
outcomes: outcomes.clone(),
end_time,
oracle_config,
has_fallback,
fallback_oracle_config: fallback_cfg,
resolution_timeout,
admin: admin.clone(),
created_at: env.ledger().timestamp(),
status: MarketState::Active,
visibility,
allowlist: Vec::new(&env),
};
// Store the event
crate::storage::EventManager::store_event(&env, &event);
// Emit event created event
EventEmitter::emit_event_created(
&env,
&event_id,
&description,
&outcomes,
&admin,
end_time,
);
// Record statistics
statistics::StatisticsManager::record_market_created(&env);
crate::audit_trail::AuditTrailManager::append_record(
&env,
crate::audit_trail::AuditAction::EventCreated,
admin.clone(),
Map::new(&env),
);
let gas_marker = GasTracker::start_tracking(&env);
GasTracker::end_tracking(&env, symbol_short!("evt_crt"), gas_marker);
event_id
}
/// Retrieves an event by its unique identifier.
///
/// # Parameters
///
/// * `env` - The Soroban environment
/// * `event_id` - Unique identifier of the event to retrieve
///
/// # Returns
///
/// Returns `Some(Event)` if found, or `None` otherwise.
///
/// # Errors
///
/// This entrypoint surfaces contract errors via panic in internal calls.
///
/// # Events
///
/// State-changing paths may emit events through internal managers; read-only query paths emit no events.
pub fn get_event(env: Env, event_id: Symbol) -> Option<Event> {
crate::storage::EventManager::get_event(&env, &event_id).ok()
}
/// Allows users to vote on a market outcome by staking tokens.
///
/// This function enables users to participate in prediction markets by voting
/// for their predicted outcome and staking tokens to back their prediction.
/// Users can only vote once per market, and votes cannot be changed after submission.
///
/// # Parameters
///
/// * `env` - The Soroban environment for blockchain operations
/// * `user` - The address of the user casting the vote (must be authenticated)
/// * `market_id` - Unique identifier of the market to vote on
/// * `outcome` - The outcome the user is voting for (must match a market outcome)
/// * `stake` - Amount of tokens to stake on this prediction (in base token units)
///
/// # Panics
///
/// This function will panic with specific errors if:
/// - `Error::MarketNotFound` - Market with given ID doesn't exist
/// - `Error::MarketClosed` - Market voting period has ended
/// - `Error::InvalidOutcome` - Outcome doesn't match any market outcomes
/// - `Error::AlreadyVoted` - User has already voted on this market
///
/// # Example
///
/// ```rust
/// # use soroban_sdk::{Env, Address, String, Symbol};
/// # use predictify_hybrid::PredictifyHybrid;
/// # let env = Env::default();
/// # let user = Address::generate(&env);
/// # let market_id = Symbol::new(&env, "market_1");
///
/// // Vote "Yes" with 1000 token units stake
/// PredictifyHybrid::vote(
/// env.clone(),
/// user,
/// market_id,
/// String::from_str(&env, "Yes"),
/// 1000
/// );
/// ```
///
/// # Token Staking
///
/// The stake amount represents the user's confidence in their prediction.
/// Higher stakes increase potential rewards but also increase risk.
/// Stakes are locked until market resolution and cannot be withdrawn early.
///
/// # Market State Requirements
///
/// - Market must be in `Active` state
/// - Current time must be before market end time
/// - Market must not be cancelled or resolved
///
/// # Errors
///
/// This entrypoint surfaces contract errors via panic in internal calls.
///
/// # Events
///
/// State-changing paths may emit events through internal managers; read-only query paths emit no events.
pub fn vote(env: Env, user: Address, market_id: Symbol, outcome: String, stake: i128) {
let gas_marker = GasTracker::start_tracking(&env);
user.require_auth();
// Rate limit voting to prevent abuse
if let Err(rate_err) = crate::rate_limiter::RateLimiter::new(env.clone())
.rate_limit_voting(user.clone(), market_id.clone())
{
panic_with_error!(env, Error::from(rate_err));
}
let mut market: Market = env
.storage()
.persistent()
.get(&market_id)