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
8526 lines (7901 loc) · 305 KB
/
Copy pathlib.rs
File metadata and controls
8526 lines (7901 loc) · 305 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]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
extern crate alloc;
// ===== MODULE DECLARATIONS =====
// These must be declared here so Rust knows to compile them as part of this crate.
const SYM_ADMIN: &str = "Admin";
const SYM_PLATFORM_FEE: &str = "platform_fee";
pub use config::PERCENTAGE_DENOMINATOR;
mod admin;
// #[cfg(any())]
// mod admin_auth_audit_tests;
// #[cfg(any())]
// mod error_code_tests;
pub mod analytics;
mod balances;
mod batch_operations;
mod bets;
pub mod circuit_breaker;
mod config;
mod err;
mod force_resolve;
mod event_archive;
mod events;
pub mod gov_registry;
mod fees;
mod gas;
mod governance;
mod markets;
mod monitoring;
mod oracles;
mod reentrancy_guard;
mod reporting;
// #[cfg(any())]
// mod reporting_tests;
// #[cfg(any())]
// mod state_snapshot_reporting_tests;
// #[cfg(any())]
// mod require_auth_coverage_tests;
#[cfg(test)]
mod resolution_event_ordering_tests;
mod resolution;
mod storage;
mod deprecated;
pub use deprecated::{DeprecatedEntry, DeprecatedRegistry, MAX_REGISTRY_ENTRIES};
#[cfg(test)]
mod deprecated_tests;
mod types;
mod upgrade_manager;
mod utils;
mod validation;
// mod validation_tests; // disabled - API drift
mod versioning;
mod voting;
mod market_analytics;
mod performance_benchmarks;
mod disputes;
mod edge_cases;
mod extensions;
mod graceful_degradation;
mod market_id_generator;
mod metadata_limits;
mod queries;
mod recovery;
mod statistics;
mod tokens;
mod rate_limiter;
mod dispute_multisig;
mod event_topic_catalog;
mod storage_tier_audit;
mod leaderboard;
mod lists;
// #[cfg(any())]
// mod voting_invariants;
// Modules whose declarations were dropped during the lib.rs collapse in
// e5db2d8 but whose files and call sites were retained/re-added afterwards.
// Restored here so the crate links again.
mod disputes;
mod edge_cases;
mod extensions;
mod graceful_degradation;
mod leaderboard;
mod market_analytics;
mod market_id_generator;
mod metadata_limits;
mod performance_benchmarks;
mod queries;
mod rate_limiter;
mod recovery;
mod statistics;
pub mod tokens;
#[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");
}
mod performance_benchmarks;
mod market_analytics;
pub mod timelock;
// #[cfg(any())]
// mod circuit_breaker_tests;
// #[cfg(test)]
// mod oracle_fallback_timeout_tests;
use bets::BetStorage;
// `BetStatus` is available at the crate root via `pub use types::*` below.
use gas::BudgetGuard;
use resolution::ResolutionOutcomeCache;
use storage::BalanceStorage;
use types::{Market, ReflectorAsset};
// `CircuitBreaker`, `Error`, `EventEmitter`, `ClaimInfo` and the soroban_sdk
// prelude items are imported/re-exported once below; duplicating them here
// tripped E0252 "defined multiple times".
// #[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(any())]
// mod upgrade_manager_tests;
// `capability_bitmap_tests.rs` does not exist in the tree; the capability
// bitmap is covered by the unit tests inside `capabilities.rs`.
#[cfg(test)]
mod market_state_matrix_tests;
#[cfg(test)]
mod timelock_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(test)]
mod force_resolve_tests;
// #[cfg(any())]
// mod statistics_tests;
// #[cfg(any())]
// mod resolution_delay_dispute_window_tests;
#[cfg(test)]
mod analytics_snapshot_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)]
#[path = "tests/fee_config_commit_reveal_tests.rs"]
mod fee_config_commit_reveal_tests;
// #[cfg(test)]
// mod event_creation_tests;
// Re-export commonly used items
use admin::{
AdminAnalyticsResult, AdminFunctions, AdminInitializer, AdminManager, AdminPermission,
AdminRole, AdminSystemIntegration,
};
pub use admin::Severity;
pub use err::Error;
use crate::storage::{
check_market_creation_rent, check_market_creation_rent_budget, DataKey, MARKET_TTL_LEDGERS,
};
// 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::config::{
ConfigManager, DEFAULT_PLATFORM_FEE_PERCENTAGE, MAX_PLATFORM_FEE_PERCENTAGE,
MIN_PLATFORM_FEE_PERCENTAGE,
};
use crate::events::emit_deprecated;
use crate::gas::GasTracker;
use crate::graceful_degradation::{OracleBackup, OracleHealth};
use crate::market_id_generator::MarketIdGenerator;
use alloc::format;
use soroban_sdk::{
Address, BytesN, Map, String, Vec,
};
impl From<crate::reentrancy_guard::GuardError> for Error {
fn from(_err: crate::reentrancy_guard::GuardError) -> Self {
Error::InvalidState
}
}
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,
}
}
}
// Short symbol keys (max length 9 for Soroban compatibility). These consts were
// dropped in the e5db2d8 lib.rs collapse but are still referenced by the storage
// helpers below; restored here.
const SYM_PLATFORM_FEE: &str = "plat_fee"; // was "platform_fee" (12 chars)
const SYM_ALLOWED_ASSETS: &str = "allowed"; // was "allowed_assets" (14 chars)
const SYM_ADMIN: &str = "Admin"; // 5 chars
/// Basis-point denominator for percentage math (100% = 10000 bps).
pub(crate) 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";
/// Returns `true` once a market has passed its `end_time + resolution_timeout`.
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)
}
/// Probe an oracle for an automatic result; `Err(OracleUnavailable)` when inactive.
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"))
}
#[contract]
pub struct PredictifyHybrid;
// ===== CONTRACT IMPLEMENTATION =====
#[contractimpl]
impl PredictifyHybrid {
/// Initializes the contract: sets the primary admin, platform fee, default
/// runtime configuration, circuit breaker, rate limiter, and allowed assets.
///
/// # Parameters
/// * `admin` - The primary administrator address.
/// * `platform_fee_percentage` - Optional platform fee in basis points; defaults to 2%.
/// * `allowed_assets` - Optional custom allow-list of deposit assets.
///
/// # Errors
///
/// Returns [`Error::InvalidState`] if already initialized, [`Error::InvalidFeeConfig`]
/// if the fee is out of bounds, or any subsystem initialization error.
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, SYM_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, SYM_PLATFORM_FEE), &fee_percentage);
// Seed default runtime configuration so validators and query paths have
// deterministic bounds immediately after deployment.
let mut default_config = ConfigManager::get_development_config(&env);
default_config.fees.platform_fee_percentage = fee_percentage;
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 {
env.storage()
.persistent()
.set(&Symbol::new(&env, SYM_ALLOWED_ASSETS), &assets);
} else {
crate::tokens::TokenRegistry::initialize_with_defaults(&env);
}
// Emit contract initialized and platform fee events
EventEmitter::emit_contract_initialized(&env, &admin, fee_percentage);
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, SYM_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.
pub fn deposit(
env: Env,
user: Address,
asset: ReflectorAsset,
amount: i128,
) -> Result<Balance, Error> {
crate::circuit_breaker::CircuitBreaker::require_write_allowed(&env, "deposit")?;
balances::BalanceManager::deposit(&env, user, asset, amount)
}
/// Withdraws funds from the user's balance.
pub fn withdraw(
env: Env,
user: Address,
asset: ReflectorAsset,
amount: i128,
) -> Result<Balance, Error> {
crate::circuit_breaker::CircuitBreaker::require_write_allowed(&env, "withdraw")?;
if !crate::circuit_breaker::CircuitBreaker::are_withdrawals_allowed(&env)? {
return Err(Error::CBOpen);
}
balances::BalanceManager::withdraw(&env, user, asset, amount)
}
/// Gets the current balance of a user for a specific asset (read-only).
pub fn get_balance(env: Env, user: Address, asset: ReflectorAsset) -> Balance {
storage::BalanceStorage::get_balance(&env, &user, &asset)
}
/// Distribute payouts to winning voters and bettors for a resolved market.
///
/// This function iterates over all voters and bettors, calculates each winner's
/// proportional share of the total pool (after platform fee), credits their balance,
/// and emits a winnings-claimed event. A `BudgetGuard` is checked every 10 iterations
/// to abort gracefully before the host CPU-instruction limit is reached.
///
/// # Parameters
/// * `env` - Soroban environment
/// * `market_id` - Symbol identifying the resolved market
///
/// # 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>,
dispute_stake_floor: Option<i128>,
) -> 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
// ConfigNotFound means rate limiting is not configured — skip the check
if let Err(rate_err) = crate::rate_limiter::RateLimiter::new(env.clone())
.rate_limit_admin_events(admin.clone())
{
if !matches!(rate_err, crate::rate_limiter::RateLimiterError::ConfigNotFound) {
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)),
};
let metadata_commitment =
Market::compute_metadata_commitment(&env, &question, &outcomes, &oracle_config);
// Create a new market
let market = Market {
admin: admin.clone(),
question: question.clone(),
outcomes: outcomes.clone(),
end_time,
oracle_config,
metadata_commitment,
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,
timelock_config: timelock::MarketTimelockConfig::default(),
dispute_stake_floor,
};
// Pre-flight checks: ensure sufficient storage rent budget.
//
// This entrypoint returns `Symbol` rather than `Result`, so a failed
// check is surfaced as a panic. Callers using `try_create_market`
// observe `Error::InsufficientStorageRent` or
// `Error::InsufficientStorageRentBudget` respectively.
//
// The aggregate check runs second and covers all three persistent
// entries this entrypoint writes: the market record below, the
// platform statistics record via `record_market_created`, and the
// audit trail record via `append_record`.
if let Err(e) = check_market_creation_rent(&env) {
panic_with_error!(env, e);
}
if let Err(e) = check_market_creation_rent_budget(&env) {
panic_with_error!(env, e);
}
// Store the market
env.storage().persistent().set(&market_id, &market);
env.storage().persistent().extend_ttl(&market_id, MARKET_TTL_LEDGERS, MARKET_TTL_LEDGERS);
// 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),
None,
);
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())
{
if !matches!(rate_err, crate::rate_limiter::RateLimiterError::ConfigNotFound) {
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),
None,
);
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())
{
if !matches!(rate_err, crate::rate_limiter::RateLimiterError::ConfigNotFound) {
panic_with_error!(env, Error::from(rate_err));
}
}
let mut market: Market = env
.storage()
.persistent()
.get(&market_id)
.unwrap_or_else(|| {
panic_with_error!(env, Error::MarketNotFound);
});
// Check if the market is still active
if market.state != MarketState::Active {
panic_with_error!(env, Error::InvalidState);
}
// Respect bet_deadline if set, otherwise use end_time
let cutoff = if market.bet_deadline > 0 {
market.bet_deadline
} else {
market.end_time
};
if env.ledger().timestamp() >= cutoff {
panic_with_error!(env, Error::MarketClosed);
}
// Validate outcome
let outcome_exists = market.outcomes.iter().any(|o| o == outcome);
if !outcome_exists {
panic_with_error!(env, Error::InvalidOutcome);
}
// Check if user already voted
if market.votes.get(user.clone()).is_some() {
panic_with_error!(env, Error::AlreadyVoted);
}
// Lock funds (transfer from user to contract)
match bets::BetUtils::lock_funds(&env, &user, stake) {
Ok(_) => {}
Err(e) => panic_with_error!(env, e),
}
// Store the vote and stake
market.votes.set(user.clone(), outcome.clone());
market.stakes.set(user.clone(), stake);
market.total_staked += stake;
env.storage().persistent().set(&market_id, &market);
// Invalidate analytics cache so next read recomputes fresh stats.
analytics::AnalyticsCache::new(&env).invalidate(&market_id);
// Emit vote cast event
EventEmitter::emit_vote_cast(&env, &market_id, &user, &outcome, stake);
GasTracker::end_tracking(&env, symbol_short!("vote"), gas_marker);