forked from TevaLabs/Xelma-Blockchain
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontract.rs
More file actions
2776 lines (2458 loc) · 102 KB
/
Copy pathcontract.rs
File metadata and controls
2776 lines (2458 loc) · 102 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
//! Core contract implementation for the XLM Price Prediction Market.
use soroban_sdk::xdr::ToXdr;
use soroban_sdk::{
contract, contractimpl, panic_with_error, symbol_short, Address, Bytes, BytesN, Env, Map, Vec,
};
use crate::errors::ContractError;
use crate::types::{
ArchivedRoundSummary, BetSide, ConfigChangeKind, ConfigChangePayload, DataKey,
OracleHeartbeatRecord, OraclePayload, PendingConfigChange, PrecisionCommitment,
PrecisionPrediction, Round, RoundArchiveStatus, RoundMode, UserPosition, UserStats,
};
// ─── Economic control limits ─────────────────────────────────────────────────
/// Minimum allowed value when setting an economic cap to prevent zero-value lockouts.
const MIN_CAP_VALUE: i128 = 1;
/// Upper bound on the minimum-participants config to prevent unbounded gas in resolution.
const MAX_MIN_PARTICIPANTS: u32 = 10_000;
const DEFAULT_MAX_PRECISION_PARTICIPANTS: u32 = 1_000;
const MAX_PRECISION_PARTICIPANTS_LIMIT: u32 = 10_000;
/// Maximum number of entries returned per page by paginated query methods,
/// regardless of the caller-requested `limit` (Issue #139).
const MAX_PAGE_SIZE: u32 = 100;
// ─── Oracle heartbeat limits ──────────────────────────────────────────────────
const DEFAULT_ORACLE_STALE_THRESHOLD: u64 = 3_600; // 1 hour
const MIN_ORACLE_STALE_THRESHOLD: u64 = 60; // 1 minute
const MAX_ORACLE_STALE_THRESHOLD: u64 = 86_400; // 24 hours
const DEFAULT_BET_WINDOW_LEDGERS: u32 = 6;
const DEFAULT_RUN_WINDOW_LEDGERS: u32 = 12;
const MAX_BET_WINDOW_LEDGERS: u32 = 1_440;
const MAX_RUN_WINDOW_LEDGERS: u32 = 2_880;
// ─── Oracle deviation guardrails ─────────────────────────────────────────────
/// Maximum allowed basis points for oracle deviation is bounded to avoid absurd configs.
/// 100_000 bp = 1000% deviation (effectively "off", but still explicit).
const MAX_ORACLE_DEVIATION_BPS: u32 = 100_000;
// ─── Storage schema versioning ───────────────────────────────────────────────
const CURRENT_SCHEMA_VERSION: u32 = 2;
// ─── Start-price bounds (Issue #119) ─────────────────────────────────────────
/// Minimum start price in protocol units — prevents zero-value and dust rounds.
const MIN_START_PRICE: u128 = 1;
/// Maximum start price in protocol units — guards against overflow in payout math.
const MAX_START_PRICE: u128 = 1_000_000_000_000_000_000;
// ─── Storage TTL Lifecycle Limits (Issue #142) ──────────────────────────────
/// Minimum remaining ledgers before a persistent entry is extended.
const TTL_BUMP_THRESHOLD: u32 = 17_280; // ~1 day at 5-second ledgers
/// Amount of ledgers to extend a persistent entry to when below threshold.
const TTL_BUMP_AMOUNT: u32 = 518_400; // ~30 days at 5-second ledgers
/// Maximum archived round summaries retained on-chain (FIFO pruning).
const MAX_ARCHIVED_ROUNDS: u32 = 128;
/// Ledgers to wait before a scheduled critical config change may be applied (~2 hours).
const CONFIG_TIMELOCK_LEDGERS: u32 = 1440;
#[contract]
pub struct VirtualTokenContract;
#[contractimpl]
impl VirtualTokenContract {
/// Initializes the contract with admin and oracle addresses (one-time only)
pub fn initialize(env: Env, admin: Address, oracle: Address) -> Result<(), ContractError> {
admin.require_auth();
if admin == oracle {
return Err(ContractError::AdminIsOracle);
}
if env.storage().persistent().has(&DataKey::Admin) {
return Err(ContractError::AlreadyInitialized);
}
env.storage().persistent().set(&DataKey::Admin, &admin);
env.storage().persistent().set(&DataKey::Oracle, &oracle);
env.storage().persistent().set(&DataKey::Paused, &false);
env.storage()
.persistent()
.set(&DataKey::SchemaVersion, &CURRENT_SCHEMA_VERSION);
// Set default window values
env.storage()
.persistent()
.set(&DataKey::BetWindowLedgers, &DEFAULT_BET_WINDOW_LEDGERS);
env.storage()
.persistent()
.set(&DataKey::RunWindowLedgers, &DEFAULT_RUN_WINDOW_LEDGERS);
Self::_extend_persistent_ttl(&env, &DataKey::Admin);
Self::_extend_persistent_ttl(&env, &DataKey::Oracle);
Self::_extend_persistent_ttl(&env, &DataKey::Paused);
Self::_extend_persistent_ttl(&env, &DataKey::SchemaVersion);
Self::_extend_persistent_ttl(&env, &DataKey::BetWindowLedgers);
Self::_extend_persistent_ttl(&env, &DataKey::RunWindowLedgers);
Ok(())
}
/// Returns the stored schema version. If unset, returns legacy version 1.
pub fn get_schema_version(env: Env) -> u32 {
let key = DataKey::SchemaVersion;
Self::_extend_persistent_ttl(&env, &key);
Self::_schema_version(&env).unwrap_or(1)
}
/// Migrates legacy schema version 1 → current schema version 2 (admin only).
///
/// Guardrails:
/// - Must not have an active round (avoids partial state interpretation changes)
/// - Only supports v1 → v2 in this release
pub fn migrate_schema_v1_to_v2(env: Env) -> Result<(), ContractError> {
let admin_key = DataKey::Admin;
Self::_extend_persistent_ttl(&env, &admin_key);
let admin: Address = env
.storage()
.persistent()
.get(&admin_key)
.ok_or(ContractError::AdminNotSet)?;
admin.require_auth();
Self::_ensure_not_paused(&env)?;
if env.storage().persistent().has(&DataKey::ActiveRound) {
return Err(ContractError::MigrationActiveRound);
}
let from = Self::_schema_version(&env).unwrap_or(1);
if from != 1 || CURRENT_SCHEMA_VERSION != 2 {
return Err(ContractError::InvalidMigrationPath);
}
let schema_key = DataKey::SchemaVersion;
env.storage()
.persistent()
.set(&schema_key, &CURRENT_SCHEMA_VERSION);
Self::_extend_persistent_ttl(&env, &schema_key);
#[allow(deprecated)]
env.events().publish(
(symbol_short!("schema"), symbol_short!("migrated")),
(from, CURRENT_SCHEMA_VERSION),
);
Ok(())
}
/// Returns whether the contract is currently paused
pub fn is_paused(env: Env) -> bool {
let key = DataKey::Paused;
Self::_extend_persistent_ttl(&env, &key);
env.storage().persistent().get(&key).unwrap_or(false)
}
/// Pauses the contract for emergency recovery (admin only)
pub fn pause_contract(env: Env) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
let admin: Address = env
.storage()
.persistent()
.get(&DataKey::Admin)
.ok_or(ContractError::AdminNotSet)?;
admin.require_auth();
env.storage().persistent().set(&DataKey::Paused, &true);
Self::_extend_persistent_ttl(&env, &DataKey::Paused);
Ok(())
}
/// Unpauses the contract after recovery (admin only)
pub fn unpause_contract(env: Env) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
let admin: Address = env
.storage()
.persistent()
.get(&DataKey::Admin)
.ok_or(ContractError::AdminNotSet)?;
admin.require_auth();
env.storage().persistent().set(&DataKey::Paused, &false);
Self::_extend_persistent_ttl(&env, &DataKey::Paused);
Ok(())
}
/// Creates a new prediction round (admin only)
/// mode: 0 = Up/Down (default), 1 = Precision (Legends)
pub fn create_round(
env: Env,
start_price: u128,
mode: Option<u32>,
) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
if start_price < MIN_START_PRICE {
return Err(ContractError::StartPriceTooLow);
}
if start_price > MAX_START_PRICE {
return Err(ContractError::StartPriceTooHigh);
}
// Default to Up/Down mode (0) if not specified
let mode_value = mode.unwrap_or(0);
// Validate mode is either 0 or 1
if mode_value > 1 {
return Err(ContractError::InvalidMode);
}
let round_mode = if mode_value == 0 {
RoundMode::UpDown
} else {
RoundMode::Precision
};
let admin: Address = env
.storage()
.persistent()
.get(&DataKey::Admin)
.ok_or(ContractError::AdminNotSet)?;
admin.require_auth();
Self::_ensure_not_paused(&env)?;
Self::assert_no_active_round(&env)?;
// Get configured windows (with defaults)
Self::_extend_persistent_ttl(&env, &DataKey::BetWindowLedgers);
let bet_ledgers: u32 = env
.storage()
.persistent()
.get(&DataKey::BetWindowLedgers)
.unwrap_or(DEFAULT_BET_WINDOW_LEDGERS);
Self::_extend_persistent_ttl(&env, &DataKey::RunWindowLedgers);
let run_ledgers: u32 = env
.storage()
.persistent()
.get(&DataKey::RunWindowLedgers)
.unwrap_or(DEFAULT_RUN_WINDOW_LEDGERS);
// Generate unique round ID
Self::_extend_persistent_ttl(&env, &DataKey::LastRoundId);
let last_round_id: u64 = env
.storage()
.persistent()
.get(&DataKey::LastRoundId)
.unwrap_or(0);
let round_id = last_round_id
.checked_add(1)
.ok_or(ContractError::Overflow)?;
env.storage()
.persistent()
.set(&DataKey::LastRoundId, &round_id);
Self::_extend_persistent_ttl(&env, &DataKey::LastRoundId);
let start_ledger = env.ledger().sequence();
let bet_end_ledger = start_ledger
.checked_add(bet_ledgers)
.ok_or(ContractError::Overflow)?;
let end_ledger = start_ledger
.checked_add(run_ledgers)
.ok_or(ContractError::Overflow)?;
let round = Round {
round_id,
price_start: start_price,
start_ledger,
bet_end_ledger,
end_ledger,
pool_up: 0,
pool_down: 0,
mode: round_mode.clone(),
};
env.storage()
.persistent()
.set(&DataKey::ActiveRound, &round);
Self::_extend_persistent_ttl(&env, &DataKey::ActiveRound);
// Note: individual position keys (DataKey::Position / DataKey::PrecisionPosition)
// are cleaned up at resolve time; no bulk-map clearing needed here.
// Emit round creation event with round ID and mode
// Topic: ("round", "created")
// Payload: (round_id: u64, start_price: u128, start_ledger: u32, bet_end_ledger: u32, end_ledger: u32, mode: u32)
#[allow(deprecated)]
env.events().publish(
(symbol_short!("round"), symbol_short!("created")),
(
round_id,
start_price,
start_ledger,
bet_end_ledger,
end_ledger,
mode_value,
),
);
Ok(())
}
/// Returns the currently active round, if any
pub fn get_active_round(env: Env) -> Option<Round> {
env.storage().persistent().get(&DataKey::ActiveRound)
}
/// Returns the ID of the last created round (0 if no rounds created yet)
pub fn get_last_round_id(env: Env) -> u64 {
env.storage()
.persistent()
.get(&DataKey::LastRoundId)
.unwrap_or(0)
}
/// Returns a compact archived round summary by round id, if retained.
pub fn get_archived_round(env: Env, round_id: u64) -> Option<ArchivedRoundSummary> {
env.storage()
.persistent()
.get(&DataKey::ArchivedRound(round_id))
}
/// Returns up to `limit` most recently archived rounds (newest first).
///
/// Pass `limit = 0` to receive an empty list. Values above [`MAX_ARCHIVED_ROUNDS`]
/// are capped automatically.
pub fn get_recent_archived_rounds(env: Env, limit: u32) -> Vec<ArchivedRoundSummary> {
let env_ref = &env;
let recent: Vec<u64> = env
.storage()
.persistent()
.get(&DataKey::RecentArchivedRoundIds)
.unwrap_or(Vec::new(env_ref));
let mut result = Vec::new(env_ref);
if limit == 0 || recent.is_empty() {
return result;
}
let fetch_cap = if limit > MAX_ARCHIVED_ROUNDS {
MAX_ARCHIVED_ROUNDS
} else {
limit
};
let mut fetched: u32 = 0;
let mut idx = recent.len();
while idx > 0 && fetched < fetch_cap {
idx -= 1;
if let Some(round_id) = recent.get(idx) {
if let Some(summary) = env
.storage()
.persistent()
.get(&DataKey::ArchivedRound(round_id))
{
result.push_back(summary);
fetched += 1;
}
}
}
result
}
pub fn get_admin(env: Env) -> Option<Address> {
let key = DataKey::Admin;
Self::_extend_persistent_ttl(&env, &key);
env.storage().persistent().get(&key)
}
pub fn get_oracle(env: Env) -> Option<Address> {
let key = DataKey::Oracle;
Self::_extend_persistent_ttl(&env, &key);
env.storage().persistent().get(&key)
}
/// Schedules a timelocked oracle deviation update (alias for [`Self::schedule_oracle_deviation_bps`]).
///
/// - `None`: disables deviation guardrails
/// - `Some(bps)`: enables guardrails with a threshold in basis points (1 bp = 0.01%)
pub fn set_oracle_max_deviation_bps(env: Env, bps: Option<u32>) -> Result<(), ContractError> {
Self::schedule_oracle_deviation_bps(env, bps)
}
/// Returns the configured oracle max deviation bps, if set.
pub fn get_oracle_max_deviation_bps(env: Env) -> Option<u32> {
let key = DataKey::OracleMaxDeviationBps;
Self::_extend_persistent_ttl(&env, &key);
env.storage().persistent().get(&key)
}
/// Arms a one-shot override to bypass deviation checks for the next settlement (admin only).
/// The flag is automatically cleared after a settlement uses it.
pub fn arm_oracle_deviation_override(env: Env) -> Result<(), ContractError> {
let admin_key = DataKey::Admin;
Self::_extend_persistent_ttl(&env, &admin_key);
let admin: Address = env
.storage()
.persistent()
.get(&admin_key)
.ok_or(ContractError::AdminNotSet)?;
admin.require_auth();
Self::_ensure_not_paused(&env)?;
let override_key = DataKey::OracleDeviationOverrideArmed;
env.storage().persistent().set(&override_key, &true);
Self::_extend_persistent_ttl(&env, &override_key);
Ok(())
}
// ─── Oracle heartbeat and liveness (on-chain health tracking) ───────────
/// Records an oracle heartbeat (oracle only).
/// `status`: 0 = active, 1 = degraded, 2 = offline.
/// Stores current ledger timestamp; emits `("oracle", "heartbeat")`.
pub fn update_oracle_heartbeat(env: Env, status: u32) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
if status > 2 {
return Err(ContractError::InvalidOracleStatus);
}
Self::_extend_persistent_ttl(&env, &DataKey::Oracle);
let oracle: Address = env
.storage()
.persistent()
.get(&DataKey::Oracle)
.ok_or(ContractError::OracleNotSet)?;
oracle.require_auth();
let ts = env.ledger().timestamp();
let record = OracleHeartbeatRecord {
timestamp: ts,
status,
};
env.storage()
.persistent()
.set(&DataKey::OracleHeartbeat, &record);
Self::_extend_persistent_ttl(&env, &DataKey::OracleHeartbeat);
#[allow(deprecated)]
env.events().publish(
(symbol_short!("oracle"), symbol_short!("heartbeat")),
(ts, status),
);
Ok(())
}
/// Returns the most recent oracle heartbeat record, if any.
pub fn get_oracle_heartbeat(env: Env) -> Option<OracleHeartbeatRecord> {
let key = DataKey::OracleHeartbeat;
Self::_extend_persistent_ttl(&env, &key);
env.storage().persistent().get(&key)
}
/// Returns `true` if the oracle has a non-stale heartbeat with status not offline (2).
/// Uses the configured stale threshold, defaulting to 3600 seconds.
pub fn is_oracle_live(env: Env) -> bool {
let heartbeat_key = DataKey::OracleHeartbeat;
Self::_extend_persistent_ttl(&env, &heartbeat_key);
let record: OracleHeartbeatRecord = match env.storage().persistent().get(&heartbeat_key) {
Some(r) => r,
None => return false,
};
if record.status == 2 {
return false;
}
let threshold_key = DataKey::OracleStaleThreshold;
Self::_extend_persistent_ttl(&env, &threshold_key);
let threshold: u64 = env
.storage()
.persistent()
.get(&threshold_key)
.unwrap_or(DEFAULT_ORACLE_STALE_THRESHOLD);
let current_time = env.ledger().timestamp();
current_time <= record.timestamp.saturating_add(threshold)
}
/// Schedules a timelocked stale threshold update (alias for [`Self::schedule_oracle_stale_threshold`]).
/// Allowed range: 60–86400 seconds (1 minute to 24 hours).
pub fn set_oracle_stale_threshold(env: Env, seconds: u64) -> Result<(), ContractError> {
Self::schedule_oracle_stale_threshold(env, seconds)
}
/// Returns the configured oracle stale threshold, or the default (3600 s) if not set.
pub fn get_oracle_stale_threshold(env: Env) -> u64 {
let key = DataKey::OracleStaleThreshold;
Self::_extend_persistent_ttl(&env, &key);
env.storage()
.persistent()
.get(&key)
.unwrap_or(DEFAULT_ORACLE_STALE_THRESHOLD)
}
/// Schedules a timelocked windows update (alias for [`Self::schedule_windows`]).
/// bet_ledgers: Number of ledgers users can place bets
/// run_ledgers: Total number of ledgers before round can be resolved
pub fn set_windows(env: Env, bet_ledgers: u32, run_ledgers: u32) -> Result<(), ContractError> {
Self::schedule_windows(env, bet_ledgers, run_ledgers)
}
// ─── Economic controls (Issue #113) ─────────────────────────────────────
/// Schedules a timelocked max stake update (alias for [`Self::schedule_max_stake`]).
/// Pass `None` to disable the cap.
pub fn set_max_stake(env: Env, max_amount: Option<i128>) -> Result<(), ContractError> {
Self::schedule_max_stake(env, max_amount)
}
/// Returns the current maximum stake cap, if set.
pub fn get_max_stake(env: Env) -> Option<i128> {
let key = DataKey::MaxStake;
Self::_extend_persistent_ttl(&env, &key);
env.storage().persistent().get(&key)
}
/// Schedules a timelocked exposure cap update (alias for [`Self::schedule_max_user_exposure`]).
/// Pass `None` to disable the cap.
pub fn set_max_user_exposure(
env: Env,
max_exposure: Option<i128>,
) -> Result<(), ContractError> {
Self::schedule_max_user_exposure(env, max_exposure)
}
/// Returns the current per-user round exposure cap, if set.
pub fn get_max_user_exposure(env: Env) -> Option<i128> {
let key = DataKey::MaxUserRoundExposure;
Self::_extend_persistent_ttl(&env, &key);
env.storage().persistent().get(&key)
}
// ─── Accounting safety (Issue #120) ─────────────────────────────────────
/// Schedules a timelocked pending winnings cap update (alias for [`Self::schedule_max_pending_winnings`]).
/// Pass `None` to disable the cap.
pub fn set_max_pending_winnings(
env: Env,
max_pending: Option<i128>,
) -> Result<(), ContractError> {
Self::schedule_max_pending_winnings(env, max_pending)
}
// ─── Timelocked critical config (governance safety) ─────────────────────
/// Schedules a timelocked update to betting and execution windows (admin only).
/// The change is stored pending until `apply_scheduled_changes` is called after the delay.
pub fn schedule_windows(
env: Env,
bet_ledgers: u32,
run_ledgers: u32,
) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
Self::_validate_windows(bet_ledgers, run_ledgers)?;
Self::_schedule_config_change(
&env,
ConfigChangeKind::Windows,
ConfigChangePayload::Windows(bet_ledgers, run_ledgers),
)
}
/// Schedules a timelocked update to the maximum stake cap (admin only).
pub fn schedule_max_stake(env: Env, max_amount: Option<i128>) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
Self::_validate_max_stake(max_amount)?;
Self::_schedule_config_change(
&env,
ConfigChangeKind::MaxStake,
ConfigChangePayload::MaxStake(max_amount),
)
}
/// Schedules a timelocked update to the per-user round exposure cap (admin only).
pub fn schedule_max_user_exposure(
env: Env,
max_exposure: Option<i128>,
) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
Self::_validate_max_stake(max_exposure)?;
Self::_schedule_config_change(
&env,
ConfigChangeKind::MaxUserRoundExposure,
ConfigChangePayload::MaxUserRoundExposure(max_exposure),
)
}
/// Schedules a timelocked update to the pending winnings cap (admin only).
pub fn schedule_max_pending_winnings(
env: Env,
max_pending: Option<i128>,
) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
Self::_validate_max_stake(max_pending)?;
Self::_schedule_config_change(
&env,
ConfigChangeKind::MaxPendingWinnings,
ConfigChangePayload::MaxPendingWinnings(max_pending),
)
}
/// Schedules a timelocked update to the oracle stale threshold (admin only).
pub fn schedule_oracle_stale_threshold(env: Env, seconds: u64) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
Self::_validate_oracle_stale_threshold(seconds)?;
Self::_schedule_config_change(
&env,
ConfigChangeKind::OracleStaleThreshold,
ConfigChangePayload::OracleStaleThreshold(seconds),
)
}
/// Schedules a timelocked update to the oracle max deviation threshold (admin only).
pub fn schedule_oracle_deviation_bps(env: Env, bps: Option<u32>) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
Self::_validate_oracle_max_deviation_bps(bps)?;
Self::_schedule_config_change(
&env,
ConfigChangeKind::OracleMaxDeviationBps,
ConfigChangePayload::OracleMaxDeviationBps(bps),
)
}
/// Returns a pending timelocked config change for the given kind, if any.
pub fn get_pending_config_change(
env: Env,
kind: ConfigChangeKind,
) -> Option<PendingConfigChange> {
env.storage()
.persistent()
.get(&DataKey::PendingConfigChange(kind))
}
/// Applies a scheduled critical config change after its activation ledger (any caller).
pub fn apply_scheduled_changes(env: Env, kind: ConfigChangeKind) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
Self::_ensure_not_paused(&env)?;
let key = DataKey::PendingConfigChange(kind.clone());
let pending: PendingConfigChange = env
.storage()
.persistent()
.get(&key)
.ok_or(ContractError::CommitmentNotFound)?;
let current_ledger = env.ledger().sequence();
if current_ledger < pending.activation_ledger {
return Err(ContractError::RoundNotEnded);
}
Self::_apply_config_payload(&env, &kind, &pending.payload)?;
env.storage().persistent().remove(&key);
#[allow(deprecated)]
env.events().publish(
(symbol_short!("config"), symbol_short!("applied")),
(kind, pending.activation_ledger),
);
Ok(())
}
/// Cancels a pending timelocked config change before activation (admin only).
pub fn cancel_config_change(env: Env, kind: ConfigChangeKind) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
let admin: Address = env
.storage()
.persistent()
.get(&DataKey::Admin)
.ok_or(ContractError::AdminNotSet)?;
admin.require_auth();
Self::_ensure_not_paused(&env)?;
let key = DataKey::PendingConfigChange(kind.clone());
let pending: PendingConfigChange = env
.storage()
.persistent()
.get(&key)
.ok_or(ContractError::CommitmentNotFound)?;
if env.ledger().sequence() >= pending.activation_ledger {
return Err(ContractError::RoundNotCancellable);
}
let cancelled_at = env.ledger().sequence();
#[allow(deprecated)]
env.events().publish(
(symbol_short!("config"), symbol_short!("cancelled")),
(kind, cancelled_at),
);
env.storage().persistent().remove(&key);
Ok(())
}
/// Returns the current maximum pending winnings cap, if set.
pub fn get_max_pending_winnings(env: Env) -> Option<i128> {
let key = DataKey::MaxPendingWinnings;
Self::_extend_persistent_ttl(&env, &key);
env.storage().persistent().get(&key)
}
// ─── Minimum participants (competitive settlement integrity) ─────────────
/// Sets the minimum participant count required for competitive settlement (admin only).
/// Rounds that end below this threshold are refunded to all participants.
/// Pass `None` to disable the threshold.
pub fn set_min_participants(env: Env, min: Option<u32>) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
let admin: Address = env
.storage()
.persistent()
.get(&DataKey::Admin)
.ok_or(ContractError::AdminNotSet)?;
admin.require_auth();
Self::_ensure_not_paused(&env)?;
let key = DataKey::MinParticipants;
if let Some(v) = min {
if v == 0 || v > MAX_MIN_PARTICIPANTS {
return Err(ContractError::InvalidMinParticipants);
}
env.storage().persistent().set(&key, &v);
Self::_extend_persistent_ttl(&env, &key);
} else {
env.storage().persistent().remove(&key);
}
Ok(())
}
/// Returns the current minimum participant threshold, if set.
pub fn get_min_participants(env: Env) -> Option<u32> {
let key = DataKey::MinParticipants;
Self::_extend_persistent_ttl(&env, &key);
env.storage().persistent().get(&key)
}
/// Sets the maximum participant count for Precision rounds (admin only).
/// The value must be in the range 1..=10_000. Unset contracts use the
/// protocol default of 1_000 participants.
pub fn set_max_precision_participants(env: Env, max: u32) -> Result<(), ContractError> {
let admin: Address = env
.storage()
.persistent()
.get(&DataKey::Admin)
.ok_or(ContractError::AdminNotSet)?;
admin.require_auth();
Self::_ensure_not_paused(&env)?;
if max == 0 || max > MAX_PRECISION_PARTICIPANTS_LIMIT {
return Err(ContractError::InvalidPrecisionParticipantCap);
}
let key = DataKey::MaxPrecisionParticipants;
env.storage().persistent().set(&key, &max);
Self::_extend_persistent_ttl(&env, &key);
Ok(())
}
/// Returns the configured Precision participant cap, or the default if unset.
pub fn get_max_precision_participants(env: Env) -> u32 {
let key = DataKey::MaxPrecisionParticipants;
Self::_extend_persistent_ttl(&env, &key);
env.storage()
.persistent()
.get(&key)
.unwrap_or(DEFAULT_MAX_PRECISION_PARTICIPANTS)
}
/// Returns user statistics (wins, losses, streaks)
pub fn get_user_stats(env: Env, user: Address) -> UserStats {
let key = DataKey::UserStats(user);
Self::_extend_persistent_ttl(&env, &key);
env.storage().persistent().get(&key).unwrap_or(UserStats {
total_wins: 0,
total_losses: 0,
current_streak: 0,
best_streak: 0,
})
}
/// Returns user's claimable winnings
pub fn get_pending_winnings(env: Env, user: Address) -> i128 {
let key = DataKey::PendingWinnings(user);
Self::_extend_persistent_ttl(&env, &key);
env.storage().persistent().get(&key).unwrap_or(0)
}
/// Places a bet on the active round (Up/Down mode only).
///
/// Storage layout: each participant's position is stored under its own
/// composite key `DataKey::Position(round_id, user)` — O(1) read/write
/// regardless of how many other participants exist. An ordered participant
/// list `DataKey::RoundParticipants(round_id)` is maintained for O(n)
/// iteration at resolution time only.
pub fn place_bet(
env: Env,
user: Address,
amount: i128,
side: BetSide,
) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
user.require_auth();
Self::_ensure_not_paused(&env)?;
if amount <= 0 {
return Err(ContractError::InvalidBetAmount);
}
// Enforce max stake cap (Issue #113)
if let Some(max_stake) = env
.storage()
.persistent()
.get::<_, i128>(&DataKey::MaxStake)
{
if amount > max_stake {
return Err(ContractError::StakeExceedsMax);
}
}
// Single read of the active round — cache in call scope
let mut round: Round = env
.storage()
.persistent()
.get(&DataKey::ActiveRound)
.ok_or(ContractError::NoActiveRound)?;
// Enforce per-user round exposure cap (Issue #113)
if let Some(max_exposure) = env
.storage()
.persistent()
.get::<_, i128>(&DataKey::MaxUserRoundExposure)
{
if amount > max_exposure {
return Err(ContractError::ExposureCapExceeded);
}
}
// Verify round is in Up/Down mode
if round.mode != RoundMode::UpDown {
return Err(ContractError::WrongModeForPrediction);
}
let current_ledger = env.ledger().sequence();
if current_ledger >= round.bet_end_ledger {
return Err(ContractError::RoundEnded);
}
let user_balance = Self::balance(env.clone(), user.clone());
if user_balance < amount {
return Err(ContractError::InsufficientBalance);
}
// O(1) duplicate-bet check — read one small key, not the full map
let pos_key = DataKey::Position(round.round_id, user.clone());
if env.storage().persistent().has(&pos_key) {
return Err(ContractError::AlreadyBet);
}
// Deduct balance
let new_balance = user_balance
.checked_sub(amount)
.ok_or(ContractError::Overflow)?;
Self::_set_balance(&env, user.clone(), new_balance);
// Write single-user position key — O(1), constant-size entry
let position = UserPosition {
amount,
side: side.clone(),
};
env.storage().persistent().set(&pos_key, &position);
// Append to participant list (needed for O(n) resolution iteration)
let participants_key = DataKey::RoundParticipants(round.round_id);
let mut participants: Vec<Address> = env
.storage()
.persistent()
.get(&participants_key)
.unwrap_or(Vec::new(&env));
participants.push_back(user.clone());
env.storage()
.persistent()
.set(&participants_key, &participants);
// Update cached round pools and write once
match side {
BetSide::Up => {
round.pool_up = round
.pool_up
.checked_add(amount)
.ok_or(ContractError::Overflow)?;
}
BetSide::Down => {
round.pool_down = round
.pool_down
.checked_add(amount)
.ok_or(ContractError::Overflow)?;
}
}
env.storage()
.persistent()
.set(&DataKey::ActiveRound, &round);
// Emit bet placed event
// Topic: ("bet", "placed")
// Payload: (user: Address, round_id: u64, amount: i128, side: u32 where 0=Up, 1=Down)
let side_value: u32 = match side {
BetSide::Up => 0,
BetSide::Down => 1,
};
#[allow(deprecated)]
env.events().publish(
(symbol_short!("bet"), symbol_short!("placed")),
(user, round.round_id, amount, side_value),
);
Ok(())
}
/// Places a precision prediction on the active round (Precision/Legends mode only)
/// predicted_price: price scaled to 4 decimals (e.g., 0.2297 → 2297)
///
/// Per-user key `DataKey::PrecisionPosition(round_id, user)` gives O(1)
/// write cost independent of participant count.
pub fn place_precision_prediction(
env: Env,
user: Address,
amount: i128,
predicted_price: u128,
) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
user.require_auth();
Self::_ensure_not_paused(&env)?;
if amount <= 0 {
return Err(ContractError::InvalidBetAmount);
}
// Enforce max stake cap (Issue #113)
if let Some(max_stake) = env
.storage()
.persistent()
.get::<_, i128>(&DataKey::MaxStake)
{
if amount > max_stake {
return Err(ContractError::StakeExceedsMax);
}
}
// Validate price scale (must be 4 decimal places, max value 9999 for 0.9999)
// Reasonable max: 99999999 (9999.9999 XLM)
if predicted_price > 99_999_999 {
return Err(ContractError::InvalidPriceScale);
}
// Single read of the active round — cache in call scope
let round: Round = env
.storage()
.persistent()
.get(&DataKey::ActiveRound)
.ok_or(ContractError::NoActiveRound)?;
// Enforce per-user round exposure cap (Issue #113)
if let Some(max_exposure) = env
.storage()
.persistent()
.get::<_, i128>(&DataKey::MaxUserRoundExposure)
{
if amount > max_exposure {
return Err(ContractError::ExposureCapExceeded);
}
}
// Verify round is in Precision mode
if round.mode != RoundMode::Precision {
return Err(ContractError::WrongModeForPrediction);
}
let current_ledger = env.ledger().sequence();
if current_ledger >= round.bet_end_ledger {
return Err(ContractError::RoundEnded);
}
// O(1) duplicate-prediction check — single composite key read
let pred_key = DataKey::PrecisionPosition(round.round_id, user.clone());
let commit_key = DataKey::PrecisionCommitment(round.round_id, user.clone());
if env.storage().persistent().has(&pred_key) || env.storage().persistent().has(&commit_key)
{
return Err(ContractError::AlreadyBet);
}
let participants_key = DataKey::RoundParticipants(round.round_id);
let mut participants: Vec<Address> = env
.storage()
.persistent()
.get(&participants_key)
.unwrap_or(Vec::new(&env));
let max_precision_participants = Self::get_max_precision_participants(env.clone());
if participants.len() >= max_precision_participants {
return Err(ContractError::PrecisionParticipantCapExceeded);
}
let user_balance = Self::balance(env.clone(), user.clone());
if user_balance < amount {