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
1135 lines (978 loc) · 41.9 KB
/
Copy pathcontract.rs
File metadata and controls
1135 lines (978 loc) · 41.9 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
// SPDX-License-Identifier: MIT
//! Core contract implementation for the XLM Price Prediction Market.
#![allow(dead_code)]
use soroban_sdk::{contract, contractimpl, symbol_short, Address, BytesN, Env, Map, Symbol, Vec};
use crate::errors::ContractError;
use crate::types::{
ArchivedRoundSummary, BetSide, ConfigChangeKind, ConfigChangePayload, DataKey,
OracleHeartbeatRecord, OraclePayload, OracleRotationProposal, PendingConfigChange,
PrecisionPrediction, ProtocolHealthStatus, ProtocolStatus, Round, RoundArchiveStatus,
RoundPhase, RoundPoolStats, RoundStatus, RuntimeMode, SimulationResult, UserPosition,
UserRoundOutcome, 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
// ─── Oracle rotation expiry ───────────────────────────────────────────────────
const MIN_ROTATION_EXPIRY_SECONDS: u64 = 60; // 1 minute minimum
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;
const ROUND_MODE_UPDOWN: u32 = 0;
const ROUND_MODE_PRECISION: u32 = 1;
const PAYOUT_OUTCOME_LOSS: u32 = 0;
const PAYOUT_OUTCOME_WIN: u32 = 1;
const PAYOUT_OUTCOME_REFUND: u32 = 2;
// ─── 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;
// ─── Protocol fee (Issue #162) ────────────────────────────────────────────────
/// Hard cap on the optional protocol settlement fee, in basis points
/// (1 bp = 0.01%). 1_000 bp = 10% of the round's total pot — the maximum an
/// admin may ever schedule via timelock. Larger values would risk turning
/// the protocol into a de-facto extraction mechanism and are explicitly
/// disallowed to preserve user trust and the conservation invariant.
const MAX_PROTOCOL_FEE_BPS: u32 = 1_000;
/// Denominator for bps math: `fee = total_pot * bps / BPS_DENOMINATOR`.
/// Pinned to 10_000 to match the universal "1 bp = 0.01%" convention.
const BPS_DENOMINATOR: i128 = 10_000;
// ─── Storage schema versioning ───────────────────────────────────────────────
const CURRENT_SCHEMA_VERSION: u32 = 3;
// ─── 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
/// Default archived round summaries retained on-chain (FIFO pruning).
const DEFAULT_ARCHIVE_RETENTION: u32 = 128;
/// Minimum archive retention limit — prevents accidental pruning of all history.
const MIN_ARCHIVE_RETENTION: u32 = 1;
/// Maximum archive retention limit — prevents unbounded storage growth.
const MAX_ARCHIVE_RETENTION: u32 = 10_000;
/// Ledgers to wait before a scheduled critical config change may be applied (~2 hours).
const CONFIG_TIMELOCK_LEDGERS: u32 = 1440;
use crate::admin;
use crate::betting;
use crate::common;
use crate::config;
use crate::queries;
use crate::settlement;
#[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::initialize(env, admin, oracle)
}
/// Returns the stored schema version. If unset, returns legacy version 1.
pub fn get_schema_version(env: Env) -> u32 {
admin::get_schema_version(env)
}
/// Migrates legacy schema version 1 → version 2 (admin only).
pub fn migrate_schema_v1_to_v2(env: Env) -> Result<(), ContractError> {
admin::migrate_schema_v1_to_v2(env)
}
/// Migrates schema version 2 → version 3 (admin only).
pub fn migrate_schema_v2_to_v3(env: Env) -> Result<(), ContractError> {
admin::migrate_schema_v2_to_v3(env)
}
/// Returns whether the contract is currently paused
pub fn is_paused(env: Env) -> bool {
admin::is_paused(env)
}
/// Pauses the contract for emergency recovery (admin only)
pub fn pause_contract(env: Env) -> Result<(), ContractError> {
admin::pause_contract(env)
}
/// Unpauses the contract after recovery (admin only)
pub fn unpause_contract(env: Env) -> Result<(), ContractError> {
admin::unpause_contract(env)
}
/// Returns the current runtime mode (0 = Normal, 1 = ClaimsOnly, 2 = FullyPaused)
pub fn get_runtime_mode(env: Env) -> u32 {
admin::get_runtime_mode(env)
}
/// Sets the runtime mode of the contract (admin only)
pub fn set_runtime_mode(env: Env, mode: u32) -> Result<(), ContractError> {
admin::set_runtime_mode(env, mode)
}
pub fn get_admin(env: Env) -> Option<Address> {
admin::get_admin(env)
}
pub fn get_oracle(env: Env) -> Option<Address> {
admin::get_oracle(env)
}
/// Schedules a timelocked oracle deviation update
pub fn set_oracle_max_deviation_bps(env: Env, bps: Option<u32>) -> Result<(), ContractError> {
admin::set_oracle_max_deviation_bps(env, bps)
}
/// Returns the configured oracle max deviation bps, if set.
pub fn get_oracle_max_deviation_bps(env: Env) -> Option<u32> {
admin::get_oracle_max_deviation_bps(env)
}
/// Arms a one-shot override to bypass deviation checks for the next settlement (admin only).
pub fn arm_oracle_deviation_override(env: Env) -> Result<(), ContractError> {
admin::arm_oracle_deviation_override(env)
}
/// Sets the minimum oracle confidence threshold in basis points (admin only).
pub fn set_oracle_min_confidence_bps(
env: Env,
min_bps: Option<u32>,
) -> Result<(), ContractError> {
admin::set_oracle_min_confidence_bps(env, min_bps)
}
/// Enables or disables strict mode for oracle confidence (admin only).
pub fn set_oracle_strict_mode(env: Env, enabled: bool) -> Result<(), ContractError> {
admin::set_oracle_strict_mode(env, enabled)
}
/// Returns the configured minimum oracle confidence bps, if set.
pub fn get_oracle_min_confidence_bps(env: Env) -> Option<u32> {
admin::get_oracle_min_confidence_bps(env)
}
/// Returns whether oracle strict mode is enabled.
pub fn get_oracle_strict_mode(env: Env) -> bool {
admin::get_oracle_strict_mode(env)
}
/// Records an oracle heartbeat (oracle only).
pub fn update_oracle_heartbeat(env: Env, status: u32) -> Result<(), ContractError> {
admin::update_oracle_heartbeat(env, status)
}
/// Returns the most recent oracle heartbeat record, if any.
pub fn get_oracle_heartbeat(env: Env) -> Option<OracleHeartbeatRecord> {
admin::get_oracle_heartbeat(env)
}
/// Returns `true` if the oracle has a non-stale heartbeat with status not offline (2).
pub fn is_oracle_live(env: Env) -> bool {
admin::is_oracle_live(env)
}
/// Schedules a timelocked stale threshold update
pub fn set_oracle_stale_threshold(env: Env, seconds: u64) -> Result<(), ContractError> {
admin::set_oracle_stale_threshold(env, seconds)
}
/// Returns a composite protocol health status
pub fn get_protocol_health(env: Env) -> ProtocolHealthStatus {
admin::get_protocol_health(env)
}
/// Returns the configured oracle stale threshold, or the default if not set.
/// Returns the global status of the protocol.
///
/// This is the canonical single-call status endpoint for frontends and
/// monitoring dashboards. The returned [`ProtocolStatus`] maps directly to
/// the three mutually-exclusive states visible to end users:
///
/// | return value | meaning |
/// |-------------------|-----------------------------------------------------|
/// | `Active` (0) | A round is live; bets or reveals are accepted. |
/// | `Paused` (1) | Emergency pause active; mutations rejected. |
/// | `ClaimsOnly` (2) | No active round; only `claim_winnings` is useful. |
///
/// **Priority**: `Paused` is always returned first when the contract is
/// paused, regardless of whether an active round exists.
pub fn get_protocol_status(env: Env) -> ProtocolStatus {
if Self::is_paused(env.clone()) {
ProtocolStatus::Paused
} else if env.storage().persistent().has(&DataKey::ActiveRound) {
ProtocolStatus::Active
} else {
ProtocolStatus::ClaimsOnly
}
}
/// Returns the status of a specific round identified by `round_id`.
///
/// Lookup strategy (in priority order):
/// 1. If the round is the **current active round**, derive status from
/// ledger position relative to `bet_end_ledger` / `end_ledger`.
/// 2. If the round appears in the **on-chain archive**, map its
/// [`RoundArchiveStatus`] to the corresponding terminal [`RoundStatus`].
/// 3. If a `CancelledRound` marker exists (archive may be pruned),
/// return `Cancelled`.
/// 4. Otherwise, return `Unknown`.
///
/// | return value | meaning |
/// |-----------------------|---------------------------------------------------------------|
/// | `Unknown` (0) | Round not found; never created or pruned from archive. |
/// | `Betting` (1) | Active; `ledger < bet_end_ledger`. |
/// | `Running` (2) | Active; `bet_end_ledger ≤ ledger < end_ledger`. |
/// | `AwaitingResolve`(3) | Active; `ledger ≥ end_ledger`, oracle not yet called. |
/// | `Resolved` (4) | Settled normally; pot distributed. |
/// | `Cancelled` (5) | Admin-cancelled; stakes refunded. |
/// | `FallbackRefund` (6) | Settled with insufficient participants; stakes refunded. |
///
/// Note: `Betting`, `Running`, and `AwaitingResolve` are **derived** from
/// ledger sequence — they do not involve additional storage writes.
pub fn get_round_status(env: Env, round_id: u64) -> RoundStatus {
// First check if it is the active round
if let Some(active_round) = env
.storage()
.persistent()
.get::<_, Round>(&DataKey::ActiveRound)
{
if active_round.round_id == round_id {
let phase = Self::_derive_round_phase(env.ledger().sequence(), &active_round);
return match phase {
RoundPhase::Betting => RoundStatus::Betting,
RoundPhase::Running => RoundStatus::Running,
RoundPhase::Resolvable => RoundStatus::AwaitingResolve,
};
}
}
// Second, check the archived rounds summary
let archive_key = DataKey::ArchivedRound(round_id);
if let Some(archive) = env
.storage()
.persistent()
.get::<_, ArchivedRoundSummary>(&archive_key)
{
return match archive.status {
RoundArchiveStatus::Resolved => RoundStatus::Resolved,
RoundArchiveStatus::Cancelled => RoundStatus::Cancelled,
RoundArchiveStatus::FallbackRefund => RoundStatus::FallbackRefund,
};
}
// Third, fallback check for cancelled rounds (in case it was pruned but CancelledRound flag remains)
if Self::is_round_cancelled(env.clone(), round_id) {
return RoundStatus::Cancelled;
}
// Otherwise, it's not active, not in archive, not cancelled.
RoundStatus::Unknown
}
/// Returns the configured oracle stale threshold, or the default (3600 s) if not set.
pub fn get_oracle_stale_threshold(env: Env) -> u64 {
admin::get_oracle_stale_threshold(env)
}
// ─── Oracle rotation (two-step with expiry) ─────────────────────────────
/// Proposes a new oracle address with an expiry window (admin only).
///
/// The proposal must be accepted via [`Self::accept_oracle_rotation`] before
/// `expires_in_seconds` elapses, otherwise acceptance is rejected.
/// Minimum expiry is 60 seconds.
///
/// Emits `("oracle", "propose")`.
pub fn propose_oracle_rotation(
env: Env,
new_oracle: Address,
expires_in_seconds: u64,
) -> 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)?;
if expires_in_seconds < MIN_ROTATION_EXPIRY_SECONDS {
return Err(ContractError::InvalidDuration);
}
let proposed_at = env.ledger().timestamp();
let expires_at = proposed_at
.checked_add(expires_in_seconds)
.ok_or(ContractError::Overflow)?;
let proposal = OracleRotationProposal {
new_oracle: new_oracle.clone(),
proposed_at,
expires_at,
};
let key = DataKey::OracleRotationProposal;
env.storage().persistent().set(&key, &proposal);
Self::_extend_persistent_ttl(&env, &key);
#[allow(deprecated)]
env.events().publish(
(symbol_short!("oracle"), symbol_short!("propose")),
(new_oracle, expires_at),
);
Ok(())
}
/// Accepts a pending oracle rotation proposal before expiry (any caller).
///
/// If the proposal has expired the call returns `RotationExpired` and the
/// stale proposal is removed after emitting `("oracle", "expired")`.
/// On success the stored oracle address is updated and
/// `("oracle", "accept")` is emitted.
pub fn accept_oracle_rotation(env: Env) -> Result<(), ContractError> {
Self::_require_supported_schema(&env)?;
Self::_ensure_not_paused(&env)?;
let key = DataKey::OracleRotationProposal;
let proposal: OracleRotationProposal = env
.storage()
.persistent()
.get(&key)
.ok_or(ContractError::NoPendingRotation)?;
let current_ts = env.ledger().timestamp();
if current_ts > proposal.expires_at {
env.storage().persistent().remove(&key);
#[allow(deprecated)]
env.events().publish(
(symbol_short!("oracle"), symbol_short!("expired")),
(
proposal.new_oracle,
proposal.proposed_at,
proposal.expires_at,
),
);
return Err(ContractError::NoPendingRotation);
}
let oracle_key = DataKey::Oracle;
let previous: Address = env
.storage()
.persistent()
.get(&oracle_key)
.ok_or(ContractError::OracleNotSet)?;
env.storage()
.persistent()
.set(&oracle_key, &proposal.new_oracle);
Self::_extend_persistent_ttl(&env, &oracle_key);
env.storage().persistent().remove(&key);
#[allow(deprecated)]
env.events().publish(
(symbol_short!("oracle"), symbol_short!("accept")),
(previous, proposal.new_oracle),
);
Ok(())
}
/// Cancels a pending oracle rotation proposal before it expires (admin only).
///
/// Emits `("oracle", "cancel")` on success.
pub fn cancel_oracle_rotation(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();
Self::_ensure_not_paused(&env)?;
let key = DataKey::OracleRotationProposal;
let proposal: OracleRotationProposal = env
.storage()
.persistent()
.get(&key)
.ok_or(ContractError::NoPendingRotation)?;
env.storage().persistent().remove(&key);
#[allow(deprecated)]
env.events().publish(
(symbol_short!("oracle"), symbol_short!("cancel")),
(proposal.new_oracle,),
);
Ok(())
}
/// Returns the pending oracle rotation proposal, if any.
pub fn get_oracle_rotation_proposal(env: Env) -> Option<OracleRotationProposal> {
let key = DataKey::OracleRotationProposal;
Self::_extend_persistent_ttl(&env, &key);
let proposal: Option<OracleRotationProposal> = env.storage().persistent().get(&key);
if let Some(ref prop) = proposal {
if env.ledger().timestamp() > prop.expires_at {
env.storage().persistent().remove(&key);
#[allow(deprecated)]
env.events().publish(
(symbol_short!("oracle"), symbol_short!("expired")),
(prop.new_oracle.clone(), prop.proposed_at, prop.expires_at),
);
return None;
}
}
proposal
}
/// 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> {
config::set_windows(env, bet_ledgers, run_ledgers)
}
pub fn set_max_stake(env: Env, max_amount: Option<i128>) -> Result<(), ContractError> {
config::set_max_stake(env, max_amount)
}
pub fn get_max_stake(env: Env) -> Option<i128> {
config::get_max_stake(env)
}
pub fn set_max_user_exposure(
env: Env,
max_exposure: Option<i128>,
) -> Result<(), ContractError> {
config::set_max_user_exposure(env, max_exposure)
}
pub fn get_max_user_exposure(env: Env) -> Option<i128> {
config::get_max_user_exposure(env)
}
pub fn set_max_pending_winnings(
env: Env,
max_pending: Option<i128>,
) -> Result<(), ContractError> {
config::set_max_pending_winnings(env, max_pending)
}
pub fn schedule_windows(
env: Env,
bet_ledgers: u32,
run_ledgers: u32,
) -> Result<(), ContractError> {
config::schedule_windows(env, bet_ledgers, run_ledgers)
}
pub fn schedule_max_stake(env: Env, max_amount: Option<i128>) -> Result<(), ContractError> {
config::schedule_max_stake(env, max_amount)
}
pub fn schedule_max_user_exposure(
env: Env,
max_exposure: Option<i128>,
) -> Result<(), ContractError> {
config::schedule_max_user_exposure(env, max_exposure)
}
pub fn schedule_max_pending_winnings(
env: Env,
max_pending: Option<i128>,
) -> Result<(), ContractError> {
config::schedule_max_pending_winnings(env, max_pending)
}
pub fn schedule_oracle_stale_threshold(env: Env, seconds: u64) -> Result<(), ContractError> {
config::schedule_oracle_stale_threshold(env, seconds)
}
pub fn schedule_oracle_deviation_bps(env: Env, bps: Option<u32>) -> Result<(), ContractError> {
config::schedule_oracle_deviation_bps(env, bps)
}
pub fn schedule_protocol_fee_bps(env: Env, bps: Option<u32>) -> Result<(), ContractError> {
config::schedule_protocol_fee_bps(env, bps)
}
pub fn set_protocol_fee_bps(env: Env, bps: Option<u32>) -> Result<(), ContractError> {
config::set_protocol_fee_bps(env, bps)
}
pub fn get_protocol_fee_bps(env: Env) -> Option<u32> {
config::get_protocol_fee_bps(env)
}
pub fn get_protocol_fee_treasury(env: Env) -> i128 {
config::get_protocol_fee_treasury(env)
}
pub fn withdraw_protocol_fee(
env: Env,
recipient: Address,
amount: i128,
) -> Result<i128, ContractError> {
config::withdraw_protocol_fee(env, recipient, amount)
}
pub fn get_pending_config_change(
env: Env,
kind: ConfigChangeKind,
) -> Option<PendingConfigChange> {
config::get_pending_config_change(env, kind)
}
pub fn apply_scheduled_changes(env: Env, kind: ConfigChangeKind) -> Result<(), ContractError> {
config::apply_scheduled_changes(env, kind)
}
pub fn cancel_config_change(env: Env, kind: ConfigChangeKind) -> Result<(), ContractError> {
config::cancel_config_change(env, kind)
}
pub fn get_max_pending_winnings(env: Env) -> Option<i128> {
config::get_max_pending_winnings(env)
}
pub fn set_min_participants(env: Env, min: Option<u32>) -> Result<(), ContractError> {
config::set_min_participants(env, min)
}
pub fn get_min_participants(env: Env) -> Option<u32> {
config::get_min_participants(env)
}
pub fn set_max_precision_participants(env: Env, max: u32) -> Result<(), ContractError> {
config::set_max_precision_participants(env, max)
}
pub fn get_max_precision_participants(env: Env) -> u32 {
config::get_max_precision_participants(env)
}
pub fn set_mint_limit(env: Env, limit: u32) -> Result<(), ContractError> {
config::set_mint_limit(env, limit)
}
pub fn get_mint_limit(env: Env) -> u32 {
config::get_mint_limit(env)
}
pub fn set_archive_retention(env: Env, limit: u32) -> Result<(), ContractError> {
config::set_archive_retention(env, limit)
}
pub fn get_archive_retention(env: Env) -> u32 {
config::get_archive_retention(env)
}
pub fn set_close_buffer_ledgers(env: Env, buffer_ledgers: u32) -> Result<(), ContractError> {
config::set_close_buffer_ledgers(env, buffer_ledgers)
}
pub fn get_close_buffer_ledgers(env: Env) -> u32 {
config::get_close_buffer_ledgers(env)
}
/// Creates a new prediction round (admin only)
pub fn create_round(
env: Env,
start_price: u128,
mode: Option<u32>,
) -> Result<(), ContractError> {
betting::create_round(env, start_price, mode)
}
pub fn place_bet(
env: Env,
user: Address,
amount: i128,
side: BetSide,
) -> Result<(), ContractError> {
betting::place_bet(env, user, amount, side)
}
pub fn place_precision_prediction(
env: Env,
user: Address,
amount: i128,
predicted_price: u128,
) -> Result<(), ContractError> {
betting::place_precision_prediction(env, user, amount, predicted_price)
}
pub fn predict_price(
env: Env,
user: Address,
guessed_price: u128,
amount: i128,
) -> Result<(), ContractError> {
betting::predict_price(env, user, guessed_price, amount)
}
pub fn commit_prediction(
env: Env,
user: Address,
hash: BytesN<32>,
amount: i128,
) -> Result<(), ContractError> {
betting::commit_prediction(env, user, hash, amount)
}
pub fn reveal_prediction(
env: Env,
user: Address,
predicted_price: u128,
salt: BytesN<32>,
) -> Result<(), ContractError> {
betting::reveal_prediction(env, user, predicted_price, salt)
}
/// Mints 1000 vXLM for new users (one-time only)
pub fn mint_initial(env: Env, user: Address) -> i128 {
betting::mint_initial(env, user)
}
pub fn resolve_round(env: Env, payload: OraclePayload) -> Result<(), ContractError> {
settlement::resolve_round(env, payload)
}
pub fn cancel_round(env: Env, reason: u32) -> Result<(), ContractError> {
settlement::cancel_round(env, reason)
}
pub fn is_round_cancelled(env: Env, round_id: u64) -> bool {
settlement::is_round_cancelled(env, round_id)
}
pub fn claim_winnings(env: Env, user: Address) -> Result<i128, ContractError> {
settlement::claim_winnings(env, user)
}
pub fn get_active_round(env: Env) -> Option<Round> {
queries::get_active_round(env)
}
pub fn get_round_pool_stats(env: Env) -> Option<RoundPoolStats> {
queries::get_round_pool_stats(env)
}
pub fn get_round_phase(env: Env) -> Result<RoundPhase, ContractError> {
queries::get_round_phase(env)
}
pub fn get_last_round_id(env: Env) -> u64 {
queries::get_last_round_id(env)
}
pub fn get_archived_round(env: Env, round_id: u64) -> Option<ArchivedRoundSummary> {
queries::get_archived_round(env, round_id)
}
pub fn get_recent_archived_rounds(env: Env, limit: u32) -> Vec<ArchivedRoundSummary> {
queries::get_recent_archived_rounds(env, limit)
}
pub fn get_user_archived_participation(
env: Env,
user: Address,
round_id: u64,
) -> Option<UserRoundOutcome> {
queries::get_user_archived_participation(env, user, round_id)
}
pub fn get_user_stats(env: Env, user: Address) -> UserStats {
queries::get_user_stats(env, user)
}
pub fn get_pending_winnings(env: Env, user: Address) -> i128 {
queries::get_pending_winnings(env, user)
}
pub fn get_user_position(env: Env, user: Address) -> Option<UserPosition> {
queries::get_user_position(env, user)
}
pub fn get_user_precision_prediction(env: Env, user: Address) -> Option<PrecisionPrediction> {
queries::get_user_precision_prediction(env, user)
}
pub fn get_precision_predictions(env: Env) -> Vec<PrecisionPrediction> {
queries::get_precision_predictions(env)
}
pub fn get_updown_positions(env: Env) -> Map<Address, UserPosition> {
queries::get_updown_positions(env)
}
pub fn get_precision_predictions_page(
env: Env,
offset: u32,
limit: u32,
) -> Vec<PrecisionPrediction> {
queries::get_precision_predictions_page(env, offset, limit)
}
pub fn get_updown_positions_page(
env: Env,
offset: u32,
limit: u32,
) -> Vec<(Address, UserPosition)> {
queries::get_updown_positions_page(env, offset, limit)
}
/// Returns user's vXLM balance
pub fn balance(env: Env, user: Address) -> i128 {
common::balance(env, user)
}
/// Estimates payouts for the active round given a hypothetical final price.
/// Does not mutate storage. Returns SimulationResult.
pub fn simulate_payout(env: Env, final_price: u128) -> Result<SimulationResult, ContractError> {
queries::simulate_payout(env, final_price)
}
}
impl VirtualTokenContract {
pub(crate) fn _set_balance(env: &Env, user: Address, amount: i128) {
let key = DataKey::Balance(user);
env.storage().persistent().set(&key, &amount);
Self::_extend_persistent_ttl(env, &key);
}
fn _ensure_not_paused(env: &Env) -> Result<(), ContractError> {
let key = DataKey::Paused;
Self::_extend_persistent_ttl(env, &key);
let mode = env
.storage()
.persistent()
.get::<_, RuntimeMode>(&key)
.unwrap_or(RuntimeMode::Normal);
if mode == RuntimeMode::FullyPaused {
return Err(ContractError::ContractPaused);
}
Ok(())
}
fn _ensure_normal_mode(env: &Env) -> Result<(), ContractError> {
let key = DataKey::Paused;
Self::_extend_persistent_ttl(env, &key);
let mode = env
.storage()
.persistent()
.get::<_, RuntimeMode>(&key)
.unwrap_or(RuntimeMode::Normal);
if mode != RuntimeMode::Normal {
return Err(ContractError::ContractPaused);
}
Ok(())
}
fn _set_mode(env: &Env, new_mode: RuntimeMode) -> Result<(), ContractError> {
let key = DataKey::Paused;
let old_mode = env
.storage()
.persistent()
.get::<_, RuntimeMode>(&key)
.unwrap_or(RuntimeMode::Normal);
if old_mode != new_mode {
env.storage().persistent().set(&key, &new_mode);
Self::_extend_persistent_ttl(env, &key);
#[allow(deprecated)]
env.events().publish(
(symbol_short!("mode"), Symbol::new(env, "transition")),
(old_mode as u32, new_mode as u32),
);
}
Ok(())
}
/// Derives the round lifecycle phase for `round` at `ledger_sequence`.
fn _derive_round_phase(ledger_sequence: u32, round: &Round) -> RoundPhase {
if ledger_sequence < round.bet_end_ledger {
RoundPhase::Betting
} else if ledger_sequence < round.end_ledger {
RoundPhase::Running
} else {
RoundPhase::Resolvable
}
}
fn _schema_version(env: &Env) -> Option<u32> {
env.storage().persistent().get(&DataKey::SchemaVersion)
}
fn _require_supported_schema(env: &Env) -> Result<u32, ContractError> {
Self::_extend_persistent_ttl(env, &DataKey::SchemaVersion);
if env.storage().persistent().has(&DataKey::Admin) {
Self::_extend_persistent_ttl(env, &DataKey::Admin);
}
let v = Self::_schema_version(env).unwrap_or(1);
if v == 0 || v > CURRENT_SCHEMA_VERSION {
return Err(ContractError::UnsupportedSchemaVersion);
}
Ok(v)
}
fn assert_no_active_round(env: &Env) -> Result<(), ContractError> {
if env.storage().persistent().has(&DataKey::ActiveRound) {
return Err(ContractError::RoundAlreadyActive);
}
Ok(())
}
/// Checked addition for payout accumulation.
///
/// All payout aggregation (refunds, winnings, precision payouts) routes
/// through this helper so overflow always maps to the stable
/// `PayoutOverflow` variant rather than a generic `Overflow`. This makes
/// the failure mode auditable and distinguishable from non-financial
/// overflow (e.g. round-ID counter, ledger arithmetic).
///
/// All-or-nothing guarantee: callers must not mutate storage before all
/// payout math is complete and checked. The functions below enforce this
/// by computing the new value first and only writing it afterward.
#[inline(always)]
fn payout_add(a: i128, b: i128) -> Result<i128, ContractError> {
a.checked_add(b).ok_or(ContractError::PayoutOverflow)
}
#[inline(always)]
fn payout_mul(a: i128, b: i128) -> Result<i128, ContractError> {
a.checked_mul(b).ok_or(ContractError::PayoutOverflow)
}
fn _emit_payout_outcome(
env: &Env,
round_id: u64,
mode: u32,
user: Address,
gross_payout: i128,
outcome_type: u32,
) {
#[allow(deprecated)]
env.events().publish(
(symbol_short!("payout"), symbol_short!("outcome")),
(round_id, mode, user, gross_payout, outcome_type),
);
}
/// Accumulates `amount` into a user's pending winnings, enforcing the cap if set (Issue #120).
///
/// Reads and writes `DataKey::PendingWinnings(user)` in one place, ensuring the cap
/// check and overflow protection are applied consistently across all payout paths.
fn _accumulate_pending(env: &Env, user: Address, amount: i128) -> Result<(), ContractError> {
let key = DataKey::PendingWinnings(user);
let existing: i128 = env.storage().persistent().get(&key).unwrap_or(0);
let new_pending = Self::payout_add(existing, amount)?;
// Enforce pending winnings cap if configured
if let Some(cap) = env
.storage()
.persistent()
.get::<_, i128>(&DataKey::MaxPendingWinnings)
{
if new_pending > cap {
return Err(ContractError::PendingWinningsCapExceeded);
}
}
env.storage().persistent().set(&key, &new_pending);
Self::_extend_persistent_ttl(env, &key);
Ok(())
}
fn _validate_windows(bet_ledgers: u32, run_ledgers: u32) -> Result<(), ContractError> {
if bet_ledgers == 0 || run_ledgers == 0 {
return Err(ContractError::InvalidDuration);
}
if bet_ledgers > MAX_BET_WINDOW_LEDGERS || run_ledgers > MAX_RUN_WINDOW_LEDGERS {
return Err(ContractError::WindowOutOfRange);
}
if bet_ledgers >= run_ledgers {
return Err(ContractError::InvalidDuration);
}
Ok(())
}
fn _validate_max_stake(max_amount: Option<i128>) -> Result<(), ContractError> {
if let Some(v) = max_amount {
if v < MIN_CAP_VALUE {
return Err(ContractError::InvalidBetAmount);
}
}
Ok(())
}
fn _validate_oracle_stale_threshold(seconds: u64) -> Result<(), ContractError> {
if !(MIN_ORACLE_STALE_THRESHOLD..=MAX_ORACLE_STALE_THRESHOLD).contains(&seconds) {
return Err(ContractError::InvalidDuration);
}
Ok(())
}
fn _validate_oracle_max_deviation_bps(bps: Option<u32>) -> Result<(), ContractError> {
if let Some(v) = bps {
if v == 0 || v > MAX_ORACLE_DEVIATION_BPS {
return Err(ContractError::WindowOutOfRange);
}
}
Ok(())
}
/// Validates a requested protocol-fee bps (Issue #162).
/// `None` always allowed (disables fee entirely, restoring pre-#162
/// byte-for-byte behaviour). `Some(0)` is rejected — only explicit `None`
/// is the legitimate way to express "fee disabled". `Some(bps)` must
/// satisfy `1 <= bps <= MAX_PROTOCOL_FEE_BPS`.
fn _validate_protocol_fee_bps(bps: Option<u32>) -> Result<(), ContractError> {
if let Some(v) = bps {
if v == 0 || v > MAX_PROTOCOL_FEE_BPS {
return Err(ContractError::InvalidProtocolFeeBps);
}
}
Ok(())
}
/// Reads the currently-configured protocol fee in bps (Issue #162).
/// Bumps TTL only when the key is present (avoids extra storage writes
/// on the hot "fee disabled" path through every competitive settlement).
fn _read_protocol_fee_bps(env: &Env) -> Option<u32> {
let key = DataKey::ProtocolFeeBps;
let v: Option<u32> = env.storage().persistent().get(&key);
if v.is_some() {
Self::_extend_persistent_ttl(env, &key);
}
v
}
/// Credits `fee_amount` stroops to the protocol fee treasury and emits
/// `("protocol", "fee_collected")` (Issue #162). TTL on the treasury
/// key is extended on every write so the cumulative balance never
/// falls into archival. Payload mirrors the active bps so indexers
/// do not need an extra storage read.
fn _collect_protocol_fee(
env: &Env,
round_id: u64,
fee_amount: i128,
bps_active: Option<u32>,
) -> Result<(), ContractError> {
if fee_amount <= 0 {
return Ok(());
}
let treasury_key = DataKey::ProtocolFeeTreasury;
let current: i128 = env.storage().persistent().get(&treasury_key).unwrap_or(0);
let new_treasury = current