1
+ module cccy ::randoom {
2
+ use std::signer;
3
+ use std::vector;
4
+ use aptos_std::smart_vector;
5
+ use aptos_std::smart_vector::SmartVector ;
6
+ use aptos_framework::aptos_coin::AptosCoin ;
7
+ use aptos_framework::coin;
8
+ use aptos_framework::coin::Coin ;
9
+ use aptos_framework::event;
10
+ use aptos_framework::randomness;
11
+
12
+ #[event]
13
+ struct Event <T > has drop ,store {
14
+ value: T
15
+ }
16
+
17
+ #[event]
18
+ struct Winner has drop ,store { \
19
+ value: address
20
+ }
21
+
22
+ entry fun random_u8 (){
23
+ event::emit (
24
+ Event {
25
+
26
+ value:randomness::u8_integer ()
27
+ }
28
+ );
29
+ }
30
+ fun init_module (caller:&signer ){
31
+ move_to (caller,Pools {
32
+ titckets_user: smart_vector::empty (),
33
+
34
+ coins:coin::zero (),
35
+
36
+ is_closed:false
37
+ })
38
+ }
39
+
40
+ struct Pools has key {
41
+
42
+ titckets_user: SmartVector <address >,
43
+ number:vector <u64 >,
44
+ coins:Coin <AptosCoin >,
45
+ is_closed:bool
46
+ }
47
+
48
+
49
+ public fun get_ticket_price ():u64 {TICKET_PRICE }
50
+ const TICKET_PRICE :u64 = 10_000 ;
51
+
52
+ entry fun pick_winner () acquires Pools {
53
+ draw_winner ();
54
+ }
55
+
56
+
57
+ fun draw_winner () acquires Pools {
58
+
59
+ let pool = borrow_global_mut <Pools >(@cccy );
60
+ assert !(!pool.is_closed,HAS_CLOSE ); // close ?
61
+ assert !(!smart_vector::is_empty (&pool.titckets_user),NO_TICKETS ); // buy tickets ?
62
+
63
+ let winner_id = randomness::u64_range (0 ,smart_vector::length (&pool.titckets_user));
64
+
65
+ let winner = *smart_vector::borrow (&pool.titckets_user,winner_id);
66
+
67
+ let coins = coin::extract_all (&mut pool.coins);
68
+
69
+ coin::deposit <AptosCoin >(winner,coins);
70
+
71
+ pool.is_closed = true ;
72
+
73
+ event::emit (
74
+ Winner {
75
+ value:winner
76
+ }
77
+ );
78
+ }
79
+
80
+ const HAS_CLOSE :u64 = 403 ;
81
+ const NO_TICKETS :u64 = 404 ;
82
+
83
+ #[test_only]
84
+ public (friend ) fun init_module_test (caller:&signer ) {
85
+ init_module (caller);
86
+ }
87
+ }
0 commit comments