Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
850 lines (765 loc) · 30.1 KB
/
Copy pathlib.rs
File metadata and controls
850 lines (765 loc) · 30.1 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
#![no_std]
#![cfg_attr(not(test), deny(clippy::unwrap_used))]
use soroban_sdk::{
auth::{ContractContext, InvokerContractAuthEntry, SubContractInvocation},
contract, contracterror, contractimpl, contracttype, token,
xdr::ToXdr,
Address, Bytes, BytesN, Env, IntoVal, String, Symbol, Val, Vec,
};
mod admin;
mod attestation;
mod claim;
mod draw;
mod events;
mod helpers;
mod init;
mod randomness;
mod tickets;
mod views;
pub(crate) use helpers::do_finalize_with_seed;
pub(crate) use helpers::{
calculate_tier_prize, read_raffle, require_admin, require_global_not_paused,
require_not_paused, request_randomness, transition_status, transition_to_drawing,
validate_token_address, write_raffle, Guard,
};
use raffle_shared::{
constants::{
DEFAULT_CLAIM_EXPIRY_SECONDS, DEFAULT_CLAIM_LOCKUP_SECONDS, DEFAULT_SWAP_DEADLINE_SECONDS,
EMERGENCY_WITHDRAW_DELAY_SECONDS, MAX_CLAIM_LOCKUP_SECONDS, MAX_DESCRIPTION_LENGTH,
MAX_PRIZES, MAX_PRIZE_AMOUNT, MAX_PROTOCOL_FEE_BP, MAX_SWEEP_UNCLAIMED_PER_CALL,
MAX_SWAP_DEADLINE_SECONDS, MAX_TICKETS_LIMIT, MIN_CLAIM_EXPIRY_SECONDS, MIN_TICKET_PRICE,
ORACLE_TIMEOUT_LEDGERS,
},
CancelReason, FailureReason, FairnessData, QuorumConfig, RaffleConfig, RaffleStatus,
RandomnessSource, RandomnessType, Ticket,
};
use self::randomness::{
build_vrf_proof_message, OracleSeedWinnerSelection, WinnerSelectionStrategy,
};
use crate::events::{
CancelScheduled, ContractPaused, ContractUnpaused, DrawTriggered, EmergencyWithdrawn,
FeesWithdrawn, MetadataHashUpdated, OracleAddressUpdated, PrizeClaimed, PrizeDeposited,
PrizeRefunded, ProtocolFeeUpdated, RaffleCancelled, RaffleCreated, RaffleFailed,
RaffleFinalized, RaffleStatusChanged, OracleSeedDelivered, RandomnessFallbackTriggered,
RandomnessReceived, RandomnessRequested, StorageWiped, SwapDeadlineUpdated, TicketNftMinted,
TicketPurchased,
TicketRefunded, TicketSalesPaused, TicketSalesResumed, TokensRescued, WinnerDrawn,
OracleSeedDelivered,
};
const RANDOMNESS_MIN_DELAY_LEDGERS: u32 = 10;
#[contract]
pub struct RaffleInstance;
#[contracttype]
#[derive(Clone)]
pub struct Raffle {
pub creator: Address,
pub description: String,
pub end_time: u64,
pub no_deadline: bool,
pub max_tickets: u32,
pub max_tickets_per_tx: u32,
pub max_tickets_per_address: u32,
pub min_tickets: u32,
pub allow_multiple: bool,
pub ticket_price: i128,
pub payment_token: Address,
/// The token used for prize deposit and claims. The current initializer
/// always sets this to `payment_token`; the config override is not wired.
pub prize_token: Address,
pub prize_amount: i128,
pub prizes: Vec<u32>,
pub tickets_sold: u32,
pub status: RaffleStatus,
pub prize_deposited: bool,
/// Winner addresses, indexed by prize tier.
pub winners: Vec<Address>,
/// Per-tier claim flag, parallel to `winners`.
pub claimed_winners: Vec<bool>,
pub randomness_source: RandomnessSource,
pub oracle_address: Option<Address>,
pub protocol_fee_bp: u32,
pub treasury_address: Option<Address>,
pub swap_router: Option<Address>,
pub tikka_token: Option<Address>,
pub finalized_at: Option<u64>,
pub claim_lockup_seconds: u64,
pub claim_expiry_seconds: u64,
pub swap_deadline_seconds: u64,
pub ticket_sales_paused: bool,
/// The percentage of max_tickets covered by the early bird discount (0 to disable).
pub early_bird_ticket_percentage: u32,
/// The discount amount specified in basis points.
pub early_bird_discount_bp: u32,
pub metadata_hash: BytesN<32>,
pub unique_winners: bool,
pub nft_contract: Option<Address>,
}
#[contracttype]
#[derive(Clone)]
pub struct FairnessMetadata {
pub seed: u64,
pub randomness_source: RandomnessSource,
pub winning_ticket_indices: Vec<u32>,
pub draw_timestamp: u64,
pub draw_sequence: u32,
pub unique_winners: bool,
}
#[soroban_sdk::contracttype]
#[derive(Clone)]
pub enum DataKey {
Raffle,
TicketCount(Address),
Ticket(u32),
TicketRefunded(u32),
Factory,
ReentrancyGuard,
Paused,
Admin,
RandomnessSeed,
RandomnessRequested,
RandomnessRequestLedger,
RandomnessRequestId,
FinishTime,
AccumulatedFees,
CommitEntry(u32),
DrawingLock,
TicketBuyers,
/// Reserved per-owner ticket ID index: owner Address → Vec<u32> of ticket
/// IDs. It is not currently written by ticket purchase logic.
OwnerTickets(Address),
PendingAdminCancel,
/// Quorum randomness: maps registered oracle address → submitted seed.
QuorumSeed(Address),
/// Quorum randomness: ordered list of oracles that have submitted.
QuorumSubmittedOracles,
}
#[contracttype]
#[derive(Clone)]
pub struct CommitRevealEntry {
pub committer: Address,
pub hash: BytesN<32>,
}
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub enum Error {
/// Raffle storage entry is missing. Code 1.
RaffleNotFound = 1,
/// Raffle is not in an active state for ticket sales. Code 2.
RaffleInactive = 2,
/// All tickets have been sold. Code 3.
TicketsSoldOut = 3,
/// Caller balance is insufficient for the operation. Code 4.
InsufficientFunds = 4,
/// Caller is not authorized for this action. Code 5.
NotAuthorized = 5,
/// External randomness requested but oracle is not configured. Code 6.
OracleNotSet = 6,
/// Randomness was already requested for this draw. Code 7.
RandomnessAlreadyRequested = 7,
/// No pending randomness request exists. Code 8.
NoRandomnessRequest = 8,
/// Fallback randomness cannot be used yet. Code 9.
FallbackTooEarly = 9,
/// Prize has not been deposited by the creator. Code 11.
PrizeNotDeposited = 11,
/// Prize tier was already claimed or swept. Code 12.
PrizeAlreadyClaimed = 12,
/// Prize deposit was already completed. Code 13.
PrizeAlreadyDeposited = 13,
/// Caller is not the winner for this tier. Code 14.
NotWinner = 14,
/// Claim or sweep attempted before the configured delay elapsed. Code 15.
ClaimTooEarly = 15,
/// One or more input parameters are invalid. Code 21.
InvalidParameters = 21,
/// Ticket quantity is out of range. Code 22.
InvalidQuantity = 22,
/// Raffle status does not allow this operation. Code 23.
InvalidStatus = 23,
/// Contract is paused. Code 24.
ContractPaused = 24,
/// Requested lifecycle transition is not allowed. Code 25.
InvalidStateTransition = 25,
/// Raffle end time has passed. Code 26.
RaffleExpired = 26,
/// Minimum ticket threshold was not met. Code 31.
InsufficientTickets = 31,
/// Address already holds a ticket when multiples are disallowed. Code 32.
MultipleTicketsNotAllowed = 32,
/// No tickets were sold. Code 33.
NoTicketsSold = 33,
/// Ticket record was not found. Code 34.
TicketNotFound = 34,
/// Raffle has already ended. Code 35.
RaffleEnded = 35,
/// Integer overflow in a contract calculation. Code 41.
ArithmeticOverflow = 41,
/// Contract initialization was already performed. Code 42.
AlreadyInitialized = 42,
/// Contract has not been initialized. Code 43.
NotInitialized = 43,
/// Reentrant call detected. Code 44.
Reentrancy = 44,
/// Token transfer failed. Code 45.
TokenTransferFailed = 45,
/// No active tickets remain for the operation. Code 46.
NoActiveTickets = 46,
/// Token swap deadline has passed. Code 47.
DeadlinePassed = 47,
/// Swap output below slippage tolerance. Code 48.
SlippageExceeded = 48,
/// Index is out of bounds. Code 49.
InvalidIndex = 49,
/// More prize tiers configured than tickets sold. Code 50.
MorePrizesThanTickets = 50,
/// Computed prize amount is zero. Code 51.
ZeroPrize = 51,
/// Token address is invalid or unsupported. Code 52.
InvalidTokenAddress = 52,
/// Prize tier count exceeds protocol maximum. Code 53.
TooManyPrizes = 53,
/// Emergency withdraw attempted before the delay elapsed. Code 54.
EmergencyTooEarly = 54,
/// Minimum tickets exceed maximum tickets. Code 55.
InvalidTicketRange = 55,
/// Accumulated fees are below the requested withdrawal. Code 56.
InsufficientAccumulatedFees = 56,
/// Prize configuration is locked after deposits or sales. Code 57.
PrizeConfigurationLocked = 57,
/// Ticket purchase exceeds per-transaction cap. Code 58.
ExceedsMaxTicketsPerTx = 58,
DrawingAlreadyInProgress = 59,
/// Invalid status for entering the drawing phase. Code 60.
InvalidStatusForDrawingTransition = 60,
/// Draw has already completed. Code 61.
DrawingAlreadyComplete = 61,
/// End time is in the past or otherwise invalid. Code 62.
InvalidEndTime = 62,
/// Admin address is zero, self, or otherwise invalid. Code 63.
InvalidAdminAddress = 63,
/// Randomness callback received before the minimum delay. Code 64.
RandomnessTooEarly = 64,
CancelTimelockActive = 65,
CancelNotScheduled = 66,
ExceedsMaxTicketsPerAddress = 67,
OracleNotRegistered = 68,
DuplicateOracleSubmission = 69,
}
#[contractimpl]
impl RaffleInstance {
pub fn init(
env: Env,
factory: Address,
admin: Address,
creator: Address,
config: RaffleConfig,
) -> Result<(), Error> {
if env.storage().instance().has(&DataKey::Raffle) {
return Err(Error::AlreadyInitialized);
}
if config.description.len() > MAX_DESCRIPTION_LENGTH {
return Err(Error::InvalidParameters);
}
let now = env.ledger().timestamp();
if config.no_deadline && config.end_time != 0 {
return Err(Error::InvalidParameters);
}
if !config.no_deadline && config.end_time <= now {
return Err(Error::InvalidParameters);
}
// Explicit check: end_time must be either 0 (no deadline) or in the future
if config.end_time != 0 && config.end_time <= now {
return Err(Error::InvalidEndTime);
}
if config.max_tickets == 0 || config.max_tickets > MAX_TICKETS_LIMIT {
return Err(Error::InvalidParameters);
}
if config.max_tickets < config.min_tickets {
return Err(Error::InvalidTicketRange);
}
if config.max_tickets_per_tx == 0 || config.max_tickets_per_tx > config.max_tickets {
return Err(Error::InvalidParameters);
}
if config.max_tickets_per_address > 0
&& config.max_tickets_per_address > config.max_tickets
{
return Err(Error::InvalidParameters);
}
if config.ticket_price < MIN_TICKET_PRICE {
return Err(Error::InvalidParameters);
}
if config.prize_amount < config.ticket_price {
return Err(Error::InvalidParameters);
}
if config.prize_amount > MAX_PRIZE_AMOUNT {
return Err(Error::InvalidParameters);
}
if config.prizes.is_empty() {
return Err(Error::InvalidParameters);
}
if config.prizes.len() > MAX_PRIZES {
return Err(Error::TooManyPrizes);
}
let mut total_prizes_bp = 0u32;
for prize_bp in config.prizes.iter() {
total_prizes_bp += prize_bp;
}
if total_prizes_bp != 10000 {
return Err(Error::InvalidParameters);
}
if config.protocol_fee_bp > 10000 {
return Err(Error::InvalidParameters);
}
if config.protocol_fee_bp > 0 && config.treasury_address.is_none() {
return Err(Error::InvalidParameters);
}
if config.randomness_source == RandomnessSource::External {
match config.oracle_address {
None => return Err(Error::InvalidParameters),
Some(ref addr) if *addr == env.current_contract_address() => {
return Err(Error::InvalidParameters);
}
Some(_) => {}
}
}
// Quorum validation: k must be > 0, oracles must be non-empty, and
// oracle_address must not be set (oracles are embedded in the enum).
if let RandomnessSource::Quorum(QuorumConfig { k, oracles }) = &config.randomness_source {
if *k == 0 || *k > oracles.len() as u32 {
return Err(Error::InvalidParameters);
}
if oracles.len() > 10 {
return Err(Error::InvalidParameters);
}
// Self-check: none of the oracles may be the raffle contract itself.
for i in 0..oracles.len() {
if let Some(addr) = oracles.get(i) {
if addr == env.current_contract_address() {
return Err(Error::InvalidParameters);
}
}
}
// Quorum mode must not also set a single oracle_address.
if config.oracle_address.is_some() {
return Err(Error::InvalidParameters);
}
}
if config.randomness_source != RandomnessSource::External
&& config.randomness_source
!= RandomnessSource::Quorum(QuorumConfig {
k: 1,
oracles: Vec::new(&env),
})
&& config.oracle_address.is_some()
{
return Err(Error::InvalidParameters);
}
if config.metadata_hash == BytesN::from_array(&env, &[0u8; 32]) {
return Err(Error::InvalidParameters);
}
// Validate that the payment_token is a valid token contract
validate_token_address(&env, &config.payment_token)?;
// The prize-token config override is not wired into initialization.
let prize_token = config.payment_token.clone();
// Resolve default values for fields that use 0 as "use default"
let config = config.resolve_defaults();
// #259: claim_lockup_seconds must be within [0, MAX_CLAIM_LOCKUP_SECONDS].
let claim_lockup = config.claim_lockup_seconds.unwrap_or(DEFAULT_CLAIM_LOCKUP_SECONDS);
if claim_lockup > MAX_CLAIM_LOCKUP_SECONDS {
return Err(Error::InvalidParameters);
}
let claim_expiry = config.claim_expiry_seconds.unwrap_or(DEFAULT_CLAIM_EXPIRY_SECONDS);
if claim_expiry < MIN_CLAIM_EXPIRY_SECONDS {
return Err(Error::InvalidParameters);
}
if claim_expiry <= claim_lockup {
return Err(Error::InvalidParameters);
}
// Swap deadline must be within [0, MAX_SWAP_DEADLINE_SECONDS].
let swap_deadline = config.swap_deadline_seconds.unwrap_or(DEFAULT_SWAP_DEADLINE_SECONDS);
if swap_deadline > MAX_SWAP_DEADLINE_SECONDS {
return Err(Error::InvalidParameters);
}
// Validate early bird parameters
if config.early_bird_ticket_percentage > 100 {
return Err(Error::InvalidParameters);
}
if config.early_bird_ticket_percentage > 0 && config.early_bird_discount_bp > 10000 {
return Err(Error::InvalidParameters);
}
let raffle = Raffle {
creator: creator.clone(),
description: config.description.clone(),
end_time: config.end_time,
no_deadline: config.no_deadline,
max_tickets: config.max_tickets,
max_tickets_per_tx: config.max_tickets_per_tx,
max_tickets_per_address: config.max_tickets_per_address,
min_tickets: config.min_tickets,
allow_multiple: config.allow_multiple,
ticket_price: config.ticket_price,
payment_token: config.payment_token.clone(),
prize_token: prize_token.clone(),
prize_amount: config.prize_amount,
prizes: config.prizes.clone(),
tickets_sold: 0,
status: RaffleStatus::PendingPrize,
prize_deposited: false,
winners: Vec::new(&env),
claimed_winners: Vec::new(&env),
randomness_source: config.randomness_source.clone(),
oracle_address: config.oracle_address,
protocol_fee_bp: config.protocol_fee_bp,
treasury_address: config.treasury_address,
swap_router: config.swap_router,
tikka_token: config.tikka_token,
finalized_at: None,
claim_lockup_seconds: claim_lockup,
claim_expiry_seconds: claim_expiry,
swap_deadline_seconds: swap_deadline,
ticket_sales_paused: false,
early_bird_ticket_percentage: config.early_bird_ticket_percentage,
early_bird_discount_bp: config.early_bird_discount_bp,
metadata_hash: config.metadata_hash.clone(),
unique_winners: config.unique_winners,
nft_contract: config.nft_contract,
};
write_raffle(&env, &raffle);
env.storage().instance().set(&DataKey::Factory, &factory);
env.storage().instance().set(&DataKey::Admin, &admin);
// Store metadata hash for attestation verification
env.storage()
.persistent()
.set(&DataKey::MetadataHash, &config.metadata_hash);
RaffleCreated {
raffle_id: env.current_contract_address(),
creator,
end_time: config.end_time,
max_tickets: config.max_tickets,
ticket_price: config.ticket_price,
payment_token: config.payment_token,
prize_amount: config.prize_amount,
prizes: config.prizes,
description: config.description,
randomness_source: config.randomness_source,
metadata_hash: config.metadata_hash,
unique_winners: config.unique_winners,
claim_expiry_seconds: claim_expiry,
}
.publish(&env);
Ok(())
}
pub fn deposit_prize(env: Env) -> Result<(), Error> {
init::deposit_prize(env)
}
pub fn buy_tickets(env: Env, buyer: Address, quantity: u32) -> Result<u32, Error> {
tickets::buy_tickets(env, buyer, quantity)
}
pub fn buy_tickets_for(
env: Env,
buyer: Address,
recipient: Address,
quantity: u32,
) -> Result<u32, Error> {
tickets::buy_tickets_for(env, buyer, recipient, quantity)
}
pub fn submit_commit(env: Env, ticket_id: u32, hash: BytesN<32>) -> Result<(), Error> {
tickets::submit_commit(env, ticket_id, hash)
}
pub fn finalize_raffle(env: Env) -> Result<(), Error> {
draw::finalize_raffle(env)
}
pub fn provide_randomness(
env: Env,
random_seed: u64,
public_key: BytesN<32>,
proof: BytesN<64>,
request_id: u64,
) -> Result<Address, Error> {
draw::provide_randomness(env, random_seed, public_key, proof, request_id)
}
/// Accept a seed from a single oracle in a k-of-n Quorum configuration.
///
/// The caller must be one of the registered oracles in the raffle's
/// `RandomnessSource::Quorum` list. Each oracle may submit at
/// most once. Once the k-th valid submission is received, the seeds are
/// aggregated via `aggregate_quorum_seeds` and the raffle is finalized.
pub fn provide_quorum_randomness(
env: Env,
caller: Address,
random_seed: u64,
request_id: u64,
) -> Result<(), Error> {
let drawing_lock: bool = env
.storage()
.instance()
.get(&DataKey::DrawingLock)
.unwrap_or(false);
if !drawing_lock {
return Err(Error::InvalidStatus);
}
caller.require_auth();
let raffle = read_raffle(&env)?;
// Verify random seed context: request_id
let stored: u64 = env
.storage()
.instance()
.get(&DataKey::RandomnessRequestId)
.ok_or(Error::NoRandomnessRequest)?;
if stored != request_id {
return Err(Error::InvalidParameters);
}
// Extract the oracle list from the Quorum config.
let (k, oracles) = match &raffle.randomness_source {
RandomnessSource::Quorum(QuorumConfig { k, oracles }) => (*k, oracles.clone()),
_ => return Err(Error::InvalidParameters),
};
// Verify caller is a registered oracle.
let mut is_registered = false;
for i in 0..oracles.len() {
if let Some(addr) = oracles.get(i) {
if addr == caller {
is_registered = true;
break;
}
}
}
if !is_registered {
return Err(Error::OracleNotRegistered);
}
// Dedup: reject if this oracle already submitted.
if env.storage().persistent().has(&DataKey::QuorumSeed(caller.clone())) {
return Err(Error::DuplicateOracleSubmission);
}
// Store the seed.
env.storage()
.persistent()
.set(&DataKey::QuorumSeed(caller.clone()), &random_seed);
// Track submission order.
let mut submitted: Vec<Address> = env
.storage()
.persistent()
.get(&DataKey::QuorumSubmittedOracles)
.unwrap_or_else(|| Vec::new(&env));
submitted.push_back(caller.clone());
env.storage()
.persistent()
.set(&DataKey::QuorumSubmittedOracles, &submitted);
let count = submitted.len() as u32;
// Emit delivery event.
OracleSeedDelivered {
oracle: caller.clone(),
seed: random_seed,
request_id,
current_count: count,
threshold: k,
timestamp: env.ledger().timestamp(),
}
.publish(&env);
// Check if quorum reached.
if count >= k {
// Build the seed list from storage.
let mut seeds = Vec::new(&env);
for i in 0..submitted.len() {
if let Some(addr) = submitted.get(i) {
if let Some(s) = env
.storage()
.persistent()
.get::<_, u64>(&DataKey::QuorumSeed(addr.clone()))
{
seeds.push_back((addr.clone(), s));
}
}
}
let aggregate = randomness::aggregate_quorum_seeds(&env, &seeds);
helpers::do_finalize_with_seed(&env, raffle, aggregate, RandomnessType::Vrf)?;
}
Ok(())
}
pub fn trigger_randomness_fallback(
env: Env,
caller: Address,
do_refund: bool,
) -> Result<(), Error> {
draw::trigger_randomness_fallback(env, caller, do_refund)
}
pub fn claim_prize(env: Env, winner: Address, tier_index: u32) -> Result<i128, Error> {
claim::claim_prize(env, winner, tier_index)
}
/// Permissionless sweep of unclaimed prizes to treasury after `claim_expiry_seconds`
/// has elapsed since finalization. Processes at most `limit` tiers starting at
/// `start_index`. Returns the number of prizes swept in this call.
pub fn sweep_unclaimed(
env: Env,
start_index: u32,
limit: u32,
) -> Result<u32, Error> {
crate::claim::sweep_unclaimed(env, start_index, limit)
}
pub fn withdraw_fees(env: Env, recipient: Address, amount: i128) -> Result<(), Error> {
admin::withdraw_fees(env, recipient, amount)
}
pub fn get_accumulated_fees(env: Env) -> i128 {
views::get_accumulated_fees(env)
}
/// Aggregate dashboard view returning key raffle metrics in a single call.
///
/// See [`views::get_stats`] for full documentation.
pub fn get_stats(env: Env) -> Result<RaffleStats, Error> {
views::get_stats(env)
}
pub fn cancel_raffle(env: Env, reason: CancelReason) -> Result<(), Error> {
admin::cancel_raffle(env, reason)
}
/// Executes a previously scheduled admin cancellation (#406).
///
/// Only succeeds once the timelock set by `cancel_raffle` has elapsed.
/// Calling it earlier returns `CancelTimelockActive`; calling it with no
/// pending schedule returns `CancelNotScheduled`.
pub fn execute_admin_cancel(env: Env) -> Result<(), Error> {
// This function was not implemented in the modules, keeping it inline for now.
// To complete the refactor, this logic should be moved to `admin.rs`.
Err(Error::InvalidParameters)
}
/// Returns the timestamp at which a scheduled admin cancel becomes
/// executable, or `None` if no cancel is currently scheduled (#406).
pub fn get_pending_cancel(env: Env) -> Option<u64> {
// This function was not implemented in the modules, keeping it inline for now.
// To complete the refactor, this logic should be moved to `views.rs`.
None
}
pub fn refund_prize(env: Env) -> Result<(), Error> {
claim::refund_prize(env)
}
pub fn emergency_withdraw(env: Env, caller: Address) -> Result<(), Error> {
admin::emergency_withdraw(env, caller)
}
pub fn refund_ticket(env: Env, ticket_id: u32) -> Result<i128, Error> {
claim::refund_ticket(env, ticket_id)
}
pub fn batch_refund_tickets(
env: Env,
owner: Address,
ticket_ids: Vec<u32>,
) -> Result<i128, Error> {
// This function was not implemented in the modules, keeping it inline for now.
// To complete the refactor, this logic should be moved to `claim.rs`.
Err(Error::InvalidParameters)
}
pub fn get_raffle(env: Env) -> Result<Raffle, Error> {
views::get_raffle(env)
}
pub fn get_fairness_data(env: Env) -> Result<FairnessData, Error> {
views::get_fairness_data(env)
}
/// Return a complete attestation package for third-party draw verification.
///
/// Combines fairness data, metadata hash, winner addresses, winning ticket IDs,
/// randomness source, and a hash of the effective raffle configuration into a
/// single response. A verifier needs only this one call to obtain everything
/// required to independently re-derive the winners.
///
/// Only available in `Finalized` or `Claimed` states; returns `InvalidStatus`
/// otherwise.
///
/// See [`docs/RANDOMNESS.md`] for the verification procedure.
pub fn get_draw_attestation(
env: Env,
) -> Result<attestation::DrawAttestation, Error> {
attestation::get_draw_attestation(&env)
}
/// Return all ticket IDs owned by `owner`.
///
/// Uses the `OwnerTickets` index maintained during `buy_tickets` for an
/// O(1) read. Falls back to an empty Vec when the address has never
/// purchased a ticket.
pub fn get_my_tickets(env: Env, owner: Address) -> Vec<u32> {
// This function was not implemented in the modules, keeping it inline for now.
// To complete the refactor, this logic should be moved to `views.rs`.
Vec::new(&env)
}
pub fn wipe_storage(env: Env) -> Result<(), Error> {
admin::wipe_storage(env)
}
pub fn pause(env: Env) -> Result<(), Error> {
admin::pause(env)
}
pub fn unpause(env: Env) -> Result<(), Error> {
admin::unpause(env)
}
pub fn is_paused(env: Env) -> bool {
views::is_paused(env)
}
pub fn pause_ticket_sales(env: Env, caller: Address) -> Result<(), Error> {
admin::pause_ticket_sales(env, caller)
}
pub fn resume_ticket_sales(env: Env, caller: Address) -> Result<(), Error> {
admin::resume_ticket_sales(env, caller)
}
pub fn is_ticket_sales_paused(env: Env) -> bool {
views::is_ticket_sales_paused(env)
}
pub fn get_remaining_ticket_allowance(
env: Env,
owner: Address,
) -> Result<u32, Error> {
views::get_remaining_ticket_allowance(env, owner)
}
/// Quote the exact cost of buying `quantity` tickets including early-bird
/// discounts and protocol fees.
///
/// Read-only — does not mutate state, does not require auth, does not
/// check raffle status, pausing, or availability. Returns a
/// [`BuyQuote`] with the full pricing breakdown. Uses the same
/// internal helper as `buy_tickets` so quote and execution cannot
/// diverge.
pub fn preview_buy(env: Env, quantity: u32) -> Result<BuyQuote, Error> {
views::preview_buy(env, quantity)
}
/// Sweep tokens that were accidentally sent to this contract.
/// Configured payment and prize tokens can only be swept to the extent
/// that all outstanding refunds, fees, and prize claims remain covered.
pub fn rescue_tokens(
env: Env,
token: Address,
recipient: Address,
amount: i128,
) -> Result<(), Error> {
admin::rescue_tokens(env, token, recipient, amount)
}
/// Sweep residual payment-token balance to the treasury after the raffle is
/// fully settled (`Claimed` or `Cancelled` with no outstanding prize or
/// ticket-refund entitlements).
///
/// See also: [`docs/EVENTS.md`](../../../docs/EVENTS.md) — `DustSwept`.
pub fn sweep_dust(env: Env) -> Result<(), Error> {
self::admin::sweep_dust(env)
}
pub fn update_oracle_address(env: Env, new_oracle: Address) -> Result<(), Error> {
admin::update_oracle_address(env, new_oracle)
}
pub fn set_protocol_fee_bp(env: Env, new_fee_bp: u32) -> Result<(), Error> {
admin::set_protocol_fee_bp(env, new_fee_bp)
}
pub fn set_swap_deadline(env: Env, new_deadline_seconds: u64) -> Result<(), Error> {
admin::set_swap_deadline(env, new_deadline_seconds)
}
pub fn update_metadata_hash(env: Env, new_hash: BytesN<32>) -> Result<(), Error> {
// This function was not implemented in the modules, keeping it inline for now.
// To complete the refactor, this logic should be moved to `admin.rs`.
Err(Error::InvalidParameters)
}
/// Permissionless entrypoint — anyone may call this to prevent a raffle
/// from being archived by Soroban's TTL expiry.
///
/// This entrypoint is currently unimplemented and returns
/// [`Error::InvalidParameters`]. It does not bump any TTLs.
pub fn extend_ttl(env: Env) -> Result<(), Error> {
let _raffle = read_raffle(&env)?;
Err(Error::InvalidParameters)
}
}
#[cfg(test)]
mod test;
#[cfg(test)]
mod tests;