forked from StellarCheckMate/Checkmate-Escrow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
5715 lines (5071 loc) · 206 KB
/
Copy pathlib.rs
File metadata and controls
5715 lines (5071 loc) · 206 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]
// Several contract entry points (e.g. `create_match_with_conversion`) take one
// parameter per on-chain field; grouping them into a struct would change the
// public contract ABI, so the arg-count lint is suppressed crate-wide instead.
#![allow(clippy::too_many_arguments)]
#[cfg(test)]
extern crate std;
/// Escrow Contract for Checkmate — trustless chess wagering on Stellar.
///
/// For a comprehensive reference of all error codes (their numeric values, causes, and recovery
/// actions), see [`Error Codes Reference`](../../docs/error-codes.md).
///
/// # Error Codes Quick Reference
///
/// Every function that returns a `Result<T, Error>` surfaces errors as numeric discriminants.
/// Common errors:
/// - `#1` — `MatchNotFound` — Invalid or expired match ID
/// - `#4` — `Unauthorized` — Caller lacks required permissions or contract not initialized
/// - `#5` — `InvalidState` — Match is in wrong state for this operation
/// - `#7` — `AlreadyInitialized` — Contract already initialized
/// - `#9` — `ContractPaused` — Operations blocked during pause
///
/// See [`docs/error-codes.md`](../../docs/error-codes.md) for all 50 error codes with causes and recovery actions.
pub mod errors;
pub mod types;
#[cfg(test)]
pub mod formal_verification;
#[cfg(test)]
mod formal_verification_tests;
#[cfg(test)]
mod kani_harness;
#[cfg(test)]
mod tests;
use errors::Error;
use soroban_sdk::{
contract, contractimpl, symbol_short, token, Address, Bytes, BytesN, Env, IntoVal, String,
Symbol, Vec,
};
use types::{
BalanceAtTimestamp, BalanceSnapshot, DataKey, Dispute, DisputeState, FeeTier, Match,
MatchState, OracleRotationState, PendingAdminProposal, PendingOracleRotation, Platform,
PlatformStats, PlayerBalanceSnapshot, PlayerTier, ProtocolConfig, SnapshotReason,
TempOracleRotation, Winner,
};
/// ~30 days at 5s/ledger. Used as the default TTL and expiration threshold.
const MATCH_TTL_LEDGERS: u32 = 518_400;
/// Fixed-size ring buffer capacity for balance snapshots per match. A normal
/// match lifecycle (created + 2 deposits + completed/cancelled) produces at
/// most 4 snapshots, so this leaves headroom while bounding storage growth
/// for matches that somehow generate more transitions.
const MAX_SNAPSHOTS_PER_MATCH: u32 = 8;
/// Fixed-size ring buffer capacity for player-level balance snapshots.
/// Player history spans many matches, so this is larger than the per-match
/// cap. Older entries are silently overwritten once the buffer fills; the
/// monotonic `index`/`PlayerBalanceSnapshotCount` lets callers detect gaps.
const MAX_PLAYER_SNAPSHOTS: u32 = 32;
/// Default match expiration timeout used when no explicit timeout is configured.
pub const DEFAULT_MATCH_TIMEOUT_LEDGERS: u32 = MATCH_TTL_LEDGERS;
/// Average Stellar ledger close time (seconds). Used only to convert the
/// public, seconds-denominated `ProtocolConfig::match_timeout_seconds` into
/// the ledger-sequence delta `expire_match` compares against internally.
const SECONDS_PER_LEDGER: u64 = 5;
/// Default match expiration timeout: 30 days.
pub const DEFAULT_MATCH_TIMEOUT_SECONDS: u64 = 2_592_000;
/// Minimum match timeout: 1 day.
pub const MIN_MATCH_TIMEOUT_SECONDS: u64 = 86_400;
/// Maximum match timeout: 90 days.
pub const MAX_MATCH_TIMEOUT_SECONDS: u64 = 7_776_000;
/// Default voting period for disputes: 1 day (17,280 ledgers at 5s/ledger).
pub const VOTING_PERIOD_LEDGERS: u32 = 17_280;
/// Time window (in seconds, since `last_heartbeat`) within which a player
/// may invoke `dispute_and_rollback_match` against an Active match to claw
/// back a stake after claiming the opponent disconnected. 24 hours.
pub const ROLLBACK_WINDOW_SECONDS: u64 = 24 * 60 * 60; // 86_400
/// Time window (in seconds, since `last_heartbeat`) after which an admin
/// may invoke `admin_resolve_stalled_match` to recover funds from an Active
/// match that has received no oracle result. Set to 7 days (longer than the
/// player-initiated 24h rollback window) to give the oracle ample time to
/// recover from transient outages without admin intervention, while still
/// providing a bounded recovery path so funds are never permanently locked.
pub const ADMIN_STALL_WINDOW_SECONDS: u64 = 7 * 24 * 60 * 60; // 604_800
/// Maximum allowed byte length for a `dispute_and_rollback_match` reason.
const MAX_REASON_LEN: u32 = 256;
/// Default dispute bond as basis points of match stake (1% = 100 basis points).
/// Set to 100 = 1% of stake required to open a dispute.
pub const DEFAULT_DISPUTE_BOND_BASIS_POINTS: u32 = 100;
/// Minimum holding duration in ledgers before acquired tokens can vote.
/// Set to 100 ledgers (~8 minutes at 5s/ledger) to prevent flash-loan attacks.
pub const DEFAULT_MINIMUM_HOLD_DURATION: u32 = 100;
/// Quorum threshold as basis points of dispute snapshot weight.
/// Set to 2000 = 20% minimum participation for resolution.
pub const DEFAULT_QUORUM_BASIS_POINTS: u32 = 2000;
/// Maximum allowed byte length for a game_id string.
///
/// Platform-specific formats:
/// - Lichess: 8 alphanumeric characters (e.g. `"abcd1234"`)
/// - Chess.com: numeric string, typically 7–12 digits (e.g. `"123456789"`)
///
/// Both formats fit well within this limit.
const MAX_GAME_ID_LEN: u32 = 64;
/// Exact game ID length required for Lichess (8 alphanumeric characters).
const LICHESS_GAME_ID_LEN: u32 = 8;
/// Minimum/maximum game ID length accepted for Chess.com (numeric string).
const CHESS_COM_GAME_ID_MIN_LEN: u32 = 7;
const CHESS_COM_GAME_ID_MAX_LEN: u32 = 12;
/// Default minimum `stake_amount` accepted by `create_match` and friends
/// when no admin override has been configured via `set_minimum_stake`.
/// Kept at `1` (the pre-existing implicit floor from the `stake_amount > 0`
/// check) so this ships without silently invalidating existing low-stake
/// matches/tests; admins can raise it with `set_minimum_stake`.
pub const DEFAULT_MINIMUM_STAKE: i128 = 1;
/// Completed-match thresholds for unlocking progressively higher stake bands.
const SILVER_MIN_COMPLETED_MATCHES: u32 = 3;
const GOLD_MIN_COMPLETED_MATCHES: u32 = 6;
const PLATINUM_MIN_COMPLETED_MATCHES: u32 = 10;
/// Stake bounds for each tier.
const BRONZE_MIN_STAKE: i128 = 1;
const BRONZE_MAX_STAKE: i128 = 100;
const SILVER_MIN_STAKE: i128 = 101;
const SILVER_MAX_STAKE: i128 = 500;
const GOLD_MIN_STAKE: i128 = 501;
const GOLD_MAX_STAKE: i128 = 1_000;
const PLATINUM_MIN_STAKE: i128 = 1_001;
/// Maximum number of simultaneously-active matches per player. This prevents
/// attacker-inflated cost growth in ActiveMatch index operations.
const MAX_ACTIVE_MATCHES_PER_PLAYER: u32 = 1_000;
/// Hard cap on unbounded match scans. The deprecated get_*_matches() functions
/// scan the full match history and are limited to this many results to cap
/// per-call cost. Callers requiring more results should use the _paginated variants.
const MAX_UNBOUNDED_MATCH_RESULTS: u32 = 10_000;
// ── Upgrade / migration constants ─────────────────────────────────────────────
/// Current contract version: major=0, minor=1, patch=0 → 1_000 * 0 + 1 * 1000 + 0.
/// Encoded as major * 1_000_000 + minor * 1_000 + patch so numeric comparisons work.
pub const CONTRACT_VERSION: u32 = 1_000; // 0.1.0
/// Minimum ledger gap between scheduling an upgrade and executing it (7-day review).
/// At the default 5 s/ledger: 7 * 24 * 3600 / 5 = 120_960.
pub const UPGRADE_REVIEW_PERIOD_LEDGERS: u32 = 120_960;
/// Extend instance storage TTL on every invocation so Admin, Oracle, Paused, and other
/// instance keys never expire.
fn extend_instance_ttl(env: &Env) {
env.storage()
.instance()
.extend_ttl(MATCH_TTL_LEDGERS / 2, MATCH_TTL_LEDGERS);
}
#[contract]
pub struct EscrowContract;
#[contractimpl]
impl EscrowContract {
/// Initialize the contract with a trusted oracle address and an admin.
pub fn initialize(env: Env, oracle: Address, admin: Address) -> Result<(), Error> {
if env.storage().instance().has(&DataKey::Oracle) {
return Err(Error::AlreadyInitialized);
}
if oracle == env.current_contract_address() {
return Err(Error::InvalidAddress);
}
env.storage().instance().set(&DataKey::Oracle, &oracle);
env.storage().instance().set(&DataKey::Admin, &admin);
env.storage().instance().set(&DataKey::MatchCount, &0u64);
env.storage().instance().set(&DataKey::Paused, &false);
env.storage()
.instance()
.set(&DataKey::AllowlistEnforced, &false);
env.storage()
.instance()
.set(&DataKey::AllowedTokenCount, &0u32);
env.storage().instance().set(
&DataKey::DisputeBondBasisPoints,
&DEFAULT_DISPUTE_BOND_BASIS_POINTS,
);
env.storage().instance().set(
&DataKey::MinimumHoldDuration,
&DEFAULT_MINIMUM_HOLD_DURATION,
);
env.storage()
.instance()
.set(&DataKey::QuorumBasisPoints, &DEFAULT_QUORUM_BASIS_POINTS);
env.storage()
.instance()
.set(&DataKey::ContractVersion, &CONTRACT_VERSION);
env.events().publish(
(Symbol::new(&env, "escrow"), symbol_short!("init")),
(oracle, admin),
);
Ok(())
}
/// Pause the contract — admin only. Blocks create_match, deposit, and submit_result.
pub fn pause(env: Env, caller: Address) -> Result<(), Error> {
extend_instance_ttl(&env);
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
if caller != admin {
return Err(Error::Unauthorized);
}
env.storage().instance().set(&DataKey::Paused, &true);
env.events()
.publish((Symbol::new(&env, "admin"), symbol_short!("paused")), ());
Ok(())
}
/// Unpause the contract — admin only.
pub fn unpause(env: Env, caller: Address) -> Result<(), Error> {
extend_instance_ttl(&env);
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
if caller != admin {
return Err(Error::Unauthorized);
}
env.storage().instance().set(&DataKey::Paused, &false);
env.events()
.publish((Symbol::new(&env, "admin"), symbol_short!("unpaused")), ());
Ok(())
}
/// Returns true if the contract is currently paused.
pub fn is_paused(env: Env) -> bool {
extend_instance_ttl(&env);
env.storage()
.instance()
.get(&DataKey::Paused)
.unwrap_or(false)
}
/// Returns true if the contract has been initialized.
pub fn is_initialized(env: Env) -> bool {
extend_instance_ttl(&env);
env.storage().instance().has(&DataKey::Oracle)
}
/// Update the protocol configuration.
pub fn set_protocol_config(env: Env, config: ProtocolConfig) -> Result<(), Error> {
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
admin.require_auth();
if config.protocol_fee_bps > 10_000 {
return Err(Error::InvalidAmount);
}
env.storage()
.instance()
.set(&DataKey::ProtocolConfig, &config);
Ok(())
}
/// Get the current protocol configuration.
pub fn get_protocol_config(env: Env) -> Result<ProtocolConfig, Error> {
Ok(Self::get_config(&env))
}
/// Set the referral fee share in basis points (admin only).
///
/// The referral fee is calculated as `platform_fee * referral_share_bps / 10_000` and sent
/// to the referrer address stored on the match. Default is 2000 (20%).
pub fn set_referral_share_bps(env: Env, basis_points: u32) -> Result<(), Error> {
extend_instance_ttl(&env);
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
admin.require_auth();
env.storage()
.instance()
.set(&DataKey::ReferralShareBasisPoints, &basis_points);
Ok(())
}
/// Get the referral fee share in basis points. Default: 2000 (20%).
pub fn get_referral_share_bps(env: Env) -> u32 {
env.storage()
.instance()
.get(&DataKey::ReferralShareBasisPoints)
.unwrap_or(2000u32)
}
/// Set the caller's preferred payout token — player only.
///
/// When a player has a preferred payout token set and it differs from the
/// match's stake token, `claim_vested_payout` will attempt to pay out in
/// the preferred token using the match's oracle-supplied `conversion_rate`
/// and `token_b` fields (set via `create_match_with_conversion`).
///
/// Pass `None` to clear the preference and revert to the match stake token.
pub fn set_preferred_payout_token(
env: Env,
player: Address,
token_address: Option<Address>,
) -> Result<(), Error> {
extend_instance_ttl(&env);
player.require_auth();
let key = DataKey::PlayerPreferredToken(player);
match token_address {
Some(addr) => {
env.storage().persistent().set(&key, &addr);
env.storage()
.persistent()
.extend_ttl(&key, MATCH_TTL_LEDGERS, MATCH_TTL_LEDGERS);
}
None => {
env.storage().persistent().remove(&key);
}
}
Ok(())
}
/// Get the caller's preferred payout token, or `None` if not set.
pub fn get_preferred_payout_token(env: Env, player: Address) -> Option<Address> {
env.storage()
.persistent()
.get(&DataKey::PlayerPreferredToken(player))
}
/// Add a token to the allowlist — admin only.
pub fn add_allowed_token(env: Env, token: Address) -> Result<(), Error> {
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
admin.require_auth();
let already_allowed: bool = env
.storage()
.instance()
.get(&DataKey::AllowedToken(token.clone()))
.unwrap_or(false);
env.storage()
.instance()
.set(&DataKey::AllowedToken(token.clone()), &true);
if !already_allowed {
let count: u32 = env
.storage()
.instance()
.get(&DataKey::AllowedTokenCount)
.unwrap_or(0);
let next_count = count.checked_add(1).ok_or(Error::Overflow)?;
env.storage()
.instance()
.set(&DataKey::AllowedTokenCount, &next_count);
env.storage()
.instance()
.set(&DataKey::AllowlistEnforced, &true);
} else {
env.storage()
.instance()
.set(&DataKey::AllowlistEnforced, &true);
}
Self::append_allowed_token(&env, &token);
env.events().publish(
(Symbol::new(&env, "admin"), symbol_short!("token_add")),
token,
);
Ok(())
}
/// Remove a token from the allowlist — admin only.
pub fn remove_allowed_token(env: Env, token: Address) -> Result<(), Error> {
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
admin.require_auth();
let was_allowed = env
.storage()
.instance()
.has(&DataKey::AllowedToken(token.clone()));
env.storage()
.instance()
.remove(&DataKey::AllowedToken(token.clone()));
if was_allowed {
let count: u32 = env
.storage()
.instance()
.get(&DataKey::AllowedTokenCount)
.unwrap_or(0);
let next_count = count.saturating_sub(1);
env.storage()
.instance()
.set(&DataKey::AllowedTokenCount, &next_count);
if next_count == 0 {
env.storage()
.instance()
.set(&DataKey::AllowlistEnforced, &false);
}
}
Self::remove_allowed_token_from_list(&env, &token);
env.events()
.publish((Symbol::new(&env, "admin"), symbol_short!("tok_rm")), token);
Ok(())
}
/// Check if a token is allowed.
pub fn is_token_allowed(env: Env, token: Address) -> bool {
let key = DataKey::AllowedToken(token.clone());
env.storage().instance().get(&key).unwrap_or(false)
}
/// Register a stablecoin issuer — admin only.
///
/// Any Stellar token whose issuer account matches a registered issuer is
/// considered a stablecoin. When `stablecoin_only_mode` is enabled in
/// [`ProtocolConfig`], `create_match` rejects tokens that don't pass the
/// [`Self::is_stablecoin`] check.
pub fn add_stablecoin_issuer(env: Env, issuer: Address) -> Result<(), Error> {
extend_instance_ttl(&env);
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
admin.require_auth();
let already_registered: bool = env
.storage()
.instance()
.get(&DataKey::StablecoinIssuer(issuer.clone()))
.unwrap_or(false);
env.storage()
.instance()
.set(&DataKey::StablecoinIssuer(issuer.clone()), &true);
if !already_registered {
let count: u32 = env
.storage()
.instance()
.get(&DataKey::StablecoinIssuerCount)
.unwrap_or(0);
let next_count = count.checked_add(1).ok_or(Error::Overflow)?;
env.storage()
.instance()
.set(&DataKey::StablecoinIssuerCount, &next_count);
}
env.events().publish(
(
Symbol::new(&env, "admin"),
Symbol::new(&env, "sc_issuer_add"),
),
issuer,
);
Ok(())
}
/// Remove a stablecoin issuer — admin only.
pub fn remove_stablecoin_issuer(env: Env, issuer: Address) -> Result<(), Error> {
extend_instance_ttl(&env);
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
admin.require_auth();
let was_registered: bool = env
.storage()
.instance()
.get(&DataKey::StablecoinIssuer(issuer.clone()))
.unwrap_or(false);
if was_registered {
env.storage()
.instance()
.remove(&DataKey::StablecoinIssuer(issuer.clone()));
let count: u32 = env
.storage()
.instance()
.get(&DataKey::StablecoinIssuerCount)
.unwrap_or(0);
let next_count = count.saturating_sub(1);
env.storage()
.instance()
.set(&DataKey::StablecoinIssuerCount, &next_count);
}
env.events().publish(
(
Symbol::new(&env, "admin"),
Symbol::new(&env, "sc_issuer_rm"),
),
issuer,
);
Ok(())
}
/// Check whether `token` qualifies as a stablecoin.
///
/// A token is a stablecoin when its issuer (obtained from the SAC contract)
/// has been registered via [`Self::add_stablecoin_issuer`]. Returns `false`
/// when no issuers have been registered yet.
pub fn is_stablecoin(env: Env, token: Address) -> bool {
Self::check_is_stablecoin(&env, &token)
}
/// Internal helper for stablecoin check (avoids `env` ownership issues).
fn check_is_stablecoin(env: &Env, token: &Address) -> bool {
// A token on Soroban is issued by an Address.
// We check whether the token address itself is registered as a stablecoin issuer,
// or whether there is a registered issuer for that token's issuer account.
// Since in Soroban the SAC (Stellar Asset Contract) address encodes the issuer,
// we treat the token address directly and check issuer registry by the token address.
// Clients are expected to call add_stablecoin_issuer with the token's contract address
// (for SAC tokens) or a known issuer Address.
env.storage()
.instance()
.get(&DataKey::StablecoinIssuer(token.clone()))
.unwrap_or(false)
}
/// Return the current allowlist as an ordered list.
pub fn get_allowed_tokens(env: Env) -> Result<soroban_sdk::Vec<Address>, Error> {
Ok(Self::get_allowed_token_list(&env))
}
fn get_allowed_token_list(env: &Env) -> soroban_sdk::Vec<Address> {
if let Some(allowed_tokens) = env.storage().persistent().get(&DataKey::AllowedTokens) {
env.storage().persistent().extend_ttl(
&DataKey::AllowedTokens,
MATCH_TTL_LEDGERS,
MATCH_TTL_LEDGERS,
);
allowed_tokens
} else {
soroban_sdk::vec![env]
}
}
fn set_allowed_token_list(env: &Env, allowed_tokens: &soroban_sdk::Vec<Address>) {
if allowed_tokens.is_empty() {
env.storage().persistent().remove(&DataKey::AllowedTokens);
} else {
env.storage()
.persistent()
.set(&DataKey::AllowedTokens, allowed_tokens);
env.storage().persistent().extend_ttl(
&DataKey::AllowedTokens,
MATCH_TTL_LEDGERS,
MATCH_TTL_LEDGERS,
);
}
}
fn append_allowed_token(env: &Env, token: &Address) {
let mut allowed_tokens: soroban_sdk::Vec<Address> = env
.storage()
.persistent()
.get(&DataKey::AllowedTokens)
.unwrap_or_else(|| soroban_sdk::vec![env]);
if !allowed_tokens.iter().any(|existing| existing == *token) {
allowed_tokens.push_back(token.clone());
Self::set_allowed_token_list(env, &allowed_tokens);
} else if env.storage().persistent().has(&DataKey::AllowedTokens) {
env.storage().persistent().extend_ttl(
&DataKey::AllowedTokens,
MATCH_TTL_LEDGERS,
MATCH_TTL_LEDGERS,
);
}
}
fn remove_allowed_token_from_list(env: &Env, token: &Address) {
let allowed_tokens = Self::get_allowed_token_list(env);
if allowed_tokens.is_empty() {
return;
}
let mut updated = soroban_sdk::vec![env];
for existing in allowed_tokens.iter() {
if existing != *token {
updated.push_back(existing.clone());
}
}
Self::set_allowed_token_list(env, &updated);
}
// ── Token Blacklist (issue #962) ─────────────────────────────────────────
/// Add a token to the blacklist — admin only.
///
/// Blacklisted tokens are permanently rejected in `create_match` even when
/// the allowlist is not enforced. The `reason` string (max 256 bytes) is
/// stored on-chain for auditability.
pub fn add_token_to_blacklist(env: Env, token: Address, reason: String) -> Result<(), Error> {
extend_instance_ttl(&env);
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
admin.require_auth();
let is_new = !env
.storage()
.instance()
.has(&DataKey::BlacklistedToken(token.clone()));
env.storage()
.instance()
.set(&DataKey::BlacklistedToken(token.clone()), &reason);
if is_new {
let mut list: soroban_sdk::Vec<Address> = env
.storage()
.persistent()
.get(&DataKey::BlacklistedTokens)
.unwrap_or_else(|| soroban_sdk::vec![&env]);
list.push_back(token.clone());
env.storage()
.persistent()
.set(&DataKey::BlacklistedTokens, &list);
env.storage().persistent().extend_ttl(
&DataKey::BlacklistedTokens,
MATCH_TTL_LEDGERS,
MATCH_TTL_LEDGERS,
);
}
env.events().publish(
(
Symbol::new(&env, "admin"),
Symbol::new(&env, "tok_blacklist"),
),
token,
);
Ok(())
}
/// Remove a token from the blacklist — admin only.
pub fn remove_token_from_blacklist(env: Env, token: Address) -> Result<(), Error> {
extend_instance_ttl(&env);
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
admin.require_auth();
env.storage()
.instance()
.remove(&DataKey::BlacklistedToken(token.clone()));
// Remove from the persistent list.
if let Some(list) = env
.storage()
.persistent()
.get::<DataKey, soroban_sdk::Vec<Address>>(&DataKey::BlacklistedTokens)
{
let mut updated: soroban_sdk::Vec<Address> = soroban_sdk::vec![&env];
for existing in list.iter() {
if existing != token {
updated.push_back(existing.clone());
}
}
env.storage()
.persistent()
.set(&DataKey::BlacklistedTokens, &updated);
env.storage().persistent().extend_ttl(
&DataKey::BlacklistedTokens,
MATCH_TTL_LEDGERS,
MATCH_TTL_LEDGERS,
);
}
env.events().publish(
(
Symbol::new(&env, "admin"),
Symbol::new(&env, "tok_unblacklist"),
),
token,
);
Ok(())
}
/// Returns `true` when `token` is on the blacklist.
pub fn is_token_blacklisted(env: Env, token: Address) -> bool {
env.storage()
.instance()
.has(&DataKey::BlacklistedToken(token))
}
/// Returns all blacklisted token addresses.
pub fn get_blacklist(env: Env) -> soroban_sdk::Vec<Address> {
env.storage()
.persistent()
.get(&DataKey::BlacklistedTokens)
.unwrap_or_else(|| soroban_sdk::vec![&env])
}
// ── Dynamic Fee Tiers (issue #963) ───────────────────────────────────────
/// Set the dynamic fee tier schedule — admin only.
///
/// `tiers` must be ordered by `max_stake` ascending. The last entry acts
/// as the open-ended catch-all (set `max_stake = i128::MAX`). Pass an
/// empty `Vec` to clear the schedule and fall back to zero protocol fees.
pub fn set_fee_tiers(env: Env, tiers: soroban_sdk::Vec<FeeTier>) -> Result<(), Error> {
extend_instance_ttl(&env);
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
admin.require_auth();
// Validate ordering: each tier's max_stake must be strictly greater
// than the previous tier's max_stake.
let mut prev_max: i128 = -1;
for tier in tiers.iter() {
if tier.max_stake <= prev_max {
return Err(Error::InvalidAmount);
}
prev_max = tier.max_stake;
}
env.storage().persistent().set(&DataKey::FeeTiers, &tiers);
env.storage().persistent().extend_ttl(
&DataKey::FeeTiers,
MATCH_TTL_LEDGERS,
MATCH_TTL_LEDGERS,
);
env.events().publish(
(
Symbol::new(&env, "admin"),
Symbol::new(&env, "fee_tiers_set"),
),
(),
);
Ok(())
}
/// Return the current fee tier schedule.
pub fn get_fee_tiers(env: Env) -> soroban_sdk::Vec<FeeTier> {
env.storage()
.persistent()
.get(&DataKey::FeeTiers)
.unwrap_or_else(|| soroban_sdk::vec![&env])
}
/// Calculate the fee in token units for a given `stake_amount` using the
/// tiered schedule. `pot` is `stake_amount * 2`.
///
/// Returns `0` when no fee tiers are configured.
pub fn calculate_fee_by_tier(env: Env, stake_amount: i128) -> Result<i128, Error> {
Self::compute_tiered_fee(&env, stake_amount)
}
/// Internal helper — resolves the basis-point rate for `stake_amount` and
/// computes the fee.
fn compute_tiered_fee(env: &Env, stake_amount: i128) -> Result<i128, Error> {
let tiers: soroban_sdk::Vec<FeeTier> = env
.storage()
.persistent()
.get(&DataKey::FeeTiers)
.unwrap_or_else(|| soroban_sdk::vec![env]);
if tiers.is_empty() {
return Ok(0);
}
// Find the first tier whose max_stake >= stake_amount.
let mut selected_bps: u32 = 0;
let mut found = false;
for tier in tiers.iter() {
if stake_amount <= tier.max_stake {
selected_bps = tier.fee_basis_points;
found = true;
break;
}
}
// If stake exceeds all explicit thresholds, use the last tier.
if !found {
if let Some(last) = tiers.get(tiers.len().saturating_sub(1)) {
selected_bps = last.fee_basis_points;
}
}
// fee = pot * bps / 10_000 where pot = stake * 2
let pot = stake_amount.checked_mul(2).ok_or(Error::Overflow)?;
let fee = pot
.checked_mul(selected_bps as i128)
.ok_or(Error::Overflow)?
.checked_div(10_000)
.ok_or(Error::Overflow)?;
Ok(fee)
}
/// Validate that `game_id` matches the format expected for `platform`.
///
/// - Lichess: exactly 8 ASCII alphanumeric characters.
/// - Chess.com: 7–12 ASCII digits.
///
/// Also enforces the shared non-empty / `MAX_GAME_ID_LEN` bound before
/// applying the platform-specific check.
fn validate_game_id_format(game_id: &String, platform: &Platform) -> Result<(), Error> {
let len = game_id.len();
if len == 0 || len > MAX_GAME_ID_LEN {
return Err(Error::InvalidGameId);
}
let mut buf = [0u8; MAX_GAME_ID_LEN as usize];
let slice = &mut buf[..len as usize];
game_id.copy_into_slice(slice);
match platform {
Platform::Lichess => {
if len != LICHESS_GAME_ID_LEN || !slice.iter().all(|b| b.is_ascii_alphanumeric()) {
return Err(Error::InvalidGameId);
}
}
Platform::ChessDotCom => {
if !(CHESS_COM_GAME_ID_MIN_LEN..=CHESS_COM_GAME_ID_MAX_LEN).contains(&len)
|| !slice.iter().all(|b| b.is_ascii_digit())
{
return Err(Error::InvalidGameId);
}
}
}
Ok(())
}
/// Create a new match. Both players must call `deposit` before the game starts.
///
/// # Parameters
/// - `game_id`: The platform-specific game identifier, validated against `platform`.
/// - **Lichess**: exactly 8 alphanumeric characters (e.g. `"abcd1234"`).
/// Taken from the game URL: `https://lichess.org/<game_id>`
/// - **Chess.com**: 7–12 numeric digits (e.g. `"123456789"`).
/// Taken from the game URL: `https://www.chess.com/game/live/<game_id>`
/// An ID that doesn't match its platform's format is rejected at
/// creation time rather than failing later at oracle result-submission.
/// - `platform`: Must match the platform the `game_id` was issued by.
/// Use `Platform::Lichess` or `Platform::ChessDotCom` accordingly.
///
/// # Errors
/// Returns `Error::InvalidGameId` if `game_id` is empty, exceeds `MAX_GAME_ID_LEN`
/// (64 bytes), or doesn't match the format expected for `platform`.
/// Returns `Error::DuplicateGameId` if the same `game_id` has already been used.
/// Returns `Error::InvalidAmount` if `stake_amount` is below the configured
/// `minimum_stake` (see `set_minimum_stake`).
pub fn create_match(
env: Env,
player1: Address,
player2: Address,
stake_amount: i128,
token: Address,
game_id: String,
platform: Platform,
) -> Result<u64, Error> {
extend_instance_ttl(&env);
player1.require_auth();
if env
.storage()
.instance()
.get(&DataKey::Paused)
.unwrap_or(false)
{
return Err(Error::ContractPaused);
}
// Blacklisted tokens are permanently rejected, regardless of allowlist status.
if Self::is_token_blacklisted(env.clone(), token.clone()) {
return Err(Error::TokenNotAllowed);
}
// Check allowlist enforcement
let allowlist_enforced: bool = env
.storage()
.instance()
.get(&DataKey::AllowlistEnforced)
.unwrap_or(false);
if allowlist_enforced && !Self::is_token_allowed(env.clone(), token.clone()) {
return Err(Error::TokenNotAllowed);
}
// Stablecoin-only mode: reject non-stablecoin tokens when enabled
let protocol_cfg = Self::get_config(&env);
if protocol_cfg.stablecoin_only_mode && !Self::check_is_stablecoin(&env, &token) {
return Err(Error::NotStablecoin);
}
if stake_amount < protocol_cfg.minimum_stake {
return Err(Error::InvalidAmount);
}
if let Some(max_stake) = protocol_cfg.maximum_stake {
if stake_amount > max_stake {
return Err(Error::InvalidAmount);
}
}
Self::require_player_tier_for_stake(&env, &player1, stake_amount)?;
Self::require_player_tier_for_stake(&env, &player2, stake_amount)?;
Self::validate_game_id_format(&game_id, &platform)?;
// Reject if either player is invalid
if player1 == player2 {
return Err(Error::InvalidPlayers);
}
if player2 == env.current_contract_address() {
return Err(Error::InvalidPlayers);
}
if env
.storage()
.persistent()
.has(&DataKey::GameId(game_id.clone()))
{
return Err(Error::DuplicateGameId);
}
let id: u64 = env
.storage()
.instance()
.get(&DataKey::MatchCount)
.unwrap_or(0);
if env.storage().persistent().has(&DataKey::Match(id)) {
return Err(Error::AlreadyExists);
}
let m = Match {
id,
player1: player1.clone(),
player2: player2.clone(),
stake_amount,
token,
game_id,
platform,
state: MatchState::Pending,
player1_deposited: false,
player2_deposited: false,
created_ledger: env.ledger().sequence(),
completed_ledger: None,
winner: Winner::None,
vested_at: None,
player1_claimed: false,
player2_claimed: false,
conversion_rate: None,
token_b: None,
conversion_rate_ledger: None,
paused_ledger: None,