draffle 0.1.0

dRaffle program
Documentation
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
use anchor_lang::solana_program::program_pack::Pack;
use anchor_lang::{prelude::*, InstructionData};
use assert_matches::assert_matches;
use bincode::deserialize;
use bytemuck;
use draffle::{Entrants, Raffle};
use solana_program_test::{processor, tokio, ProgramTest, ProgramTestContext};
use solana_sdk::{
    instruction::{Instruction, InstructionError},
    pubkey::Pubkey,
    signature::{Keypair, Signer},
    system_instruction, system_program, sysvar,
    transaction::{Transaction, TransactionError},
};
use std::mem::size_of;
use std::str::FromStr;

#[tokio::test]
async fn test_raffle() {
    let mut draffle_program_test = DraffleProgramTest::start_new().await;

    let entrants_keypair = Keypair::new();

    let proceeds_mint_keypair = Keypair::new();
    // NFT like
    let first_prize_mint_keypair = Keypair::new();
    // Fungible
    let second_prize_mint_keypair = Keypair::new();

    let program_id = draffle_program_test.program_id;
    let payer_pk = draffle_program_test.context.payer.pubkey();

    // Setup
    initialize_mint(&proceeds_mint_keypair, 9, &mut draffle_program_test).await;
    let creator_proceeds_ata = initialize_ata(
        &payer_pk,
        &proceeds_mint_keypair.pubkey(),
        &mut draffle_program_test,
    )
    .await;
    initialize_mint(&first_prize_mint_keypair, 0, &mut draffle_program_test).await;
    let creator_first_prize_ata = initialize_ata(
        &payer_pk,
        &first_prize_mint_keypair.pubkey(),
        &mut draffle_program_test,
    )
    .await;
    mint_some(
        &creator_first_prize_ata,
        &first_prize_mint_keypair.pubkey(),
        &mut draffle_program_test,
        1,
    )
    .await;
    initialize_mint(&second_prize_mint_keypair, 4, &mut draffle_program_test).await;
    let creator_second_prize_ata = initialize_ata(
        &payer_pk,
        &second_prize_mint_keypair.pubkey(),
        &mut draffle_program_test,
    )
    .await;
    mint_some(
        &creator_second_prize_ata,
        &second_prize_mint_keypair.pubkey(),
        &mut draffle_program_test,
        321,
    )
    .await;
    let users = prepare_users(&proceeds_mint_keypair.pubkey(), &mut draffle_program_test).await;

    // Create raffle
    let (raffle, _) = Pubkey::find_program_address(
        &[b"raffle".as_ref(), entrants_keypair.pubkey().as_ref()],
        &draffle_program_test.program_id,
    );

    let (proceeds, _) = Pubkey::find_program_address(
        &[raffle.key().as_ref(), b"proceeds".as_ref()],
        &draffle_program_test.program_id,
    );

    let clock = draffle_program_test.get_clock().await;
    println!("{:?}", clock);
    let end_timestamp: i64 = clock.unix_timestamp + 5;
    let ticket_price = 1234;

    let entrants_rent_exempt_threshold = draffle_program_test
        .context
        .banks_client
        .get_rent()
        .await
        .unwrap()
        .minimum_balance(8 + size_of::<draffle::Entrants>());

    draffle_program_test
        .process_tx_and_assert_ok(
            &[
                system_instruction::create_account(
                    &payer_pk,
                    &entrants_keypair.pubkey(),
                    entrants_rent_exempt_threshold,
                    8 + size_of::<draffle::Entrants>() as u64,
                    &program_id,
                ),
                Instruction {
                    program_id,
                    accounts: draffle::accounts::CreateRaffle {
                        raffle,
                        entrants: entrants_keypair.pubkey(),
                        creator: payer_pk,
                        proceeds,
                        proceeds_mint: proceeds_mint_keypair.pubkey(),
                        system_program: system_program::id(),
                        token_program: spl_token::id(),
                        rent: sysvar::rent::ID,
                    }
                    .to_account_metas(None),
                    data: draffle::instruction::CreateRaffle {
                        end_timestamp,
                        ticket_price,
                        max_entrants: 5000,
                    }
                    .data(),
                },
            ],
            &[&entrants_keypair],
        )
        .await;

    // Add first prize
    let (first_prize, _) = Pubkey::find_program_address(
        &[raffle.key().as_ref(), b"prize", &0u32.to_le_bytes()],
        &program_id,
    );
    draffle_program_test
        .process_tx_and_assert_ok(
            &[Instruction {
                program_id,
                accounts: draffle::accounts::AddPrize {
                    raffle,
                    creator: payer_pk,
                    from: creator_first_prize_ata,
                    prize: first_prize,
                    prize_mint: first_prize_mint_keypair.pubkey(),
                    system_program: system_program::id(),
                    token_program: spl_token::id(),
                    rent: sysvar::rent::ID,
                }
                .to_account_metas(None),
                data: draffle::instruction::AddPrize {
                    prize_index: 0,
                    amount: 1,
                }
                .data(),
            }],
            &[],
        )
        .await;

    // Add second prize
    let (second_prize, _) = Pubkey::find_program_address(
        &[raffle.key().as_ref(), b"prize", &1u32.to_le_bytes()],
        &program_id,
    );
    draffle_program_test
        .process_tx_and_assert_ok(
            &[Instruction {
                program_id,
                accounts: draffle::accounts::AddPrize {
                    raffle,
                    creator: payer_pk,
                    from: creator_second_prize_ata,
                    prize: second_prize,
                    prize_mint: second_prize_mint_keypair.pubkey(),
                    system_program: system_program::id(),
                    token_program: spl_token::id(),
                    rent: sysvar::rent::ID,
                }
                .to_account_metas(None),
                data: draffle::instruction::AddPrize {
                    prize_index: 1,
                    amount: 123,
                }
                .data(),
            }],
            &[],
        )
        .await;

    // Buy tickets
    for (i, user) in users.iter().enumerate() {
        draffle_program_test
            .process_tx_and_assert_ok(
                &[Instruction {
                    program_id,
                    accounts: draffle::accounts::BuyTickets {
                        raffle,
                        entrants: entrants_keypair.pubkey(),
                        proceeds,
                        buyer_token_account: user.proceeds_mint_ata,
                        buyer_transfer_authority: user.keypair.pubkey(),
                        token_program: spl_token::id(),
                    }
                    .to_account_metas(None),
                    data: draffle::instruction::BuyTickets {
                        amount: fibonacci(i as u32) + 1,
                    }
                    .data(),
                }],
                &[&user.keypair],
            )
            .await;
    }

    // Try to collect proceeds before end

    // Draw winner too early
    draffle_program_test
        .process_tx_and_assert_err(
            &[Instruction {
                program_id,
                accounts: draffle::accounts::RevealWinners {
                    raffle,
                    recent_blockhashes: sysvar::recent_blockhashes::ID,
                }
                .to_account_metas(None),
                data: draffle::instruction::RevealWinners.data(),
            }],
            &[],
            TransactionError::InstructionError(
                0,
                InstructionError::Custom(draffle::RaffleError::RaffleStillRunning as u32 + 300),
            ),
        )
        .await;

    // Progress to after raffle end time
    loop {
        let clock = draffle_program_test.get_clock().await;
        if clock.unix_timestamp > end_timestamp + draffle::TIME_BUFFER {
            break;
        }
        draffle_program_test
            .context
            .warp_to_slot(clock.slot + 5)
            .unwrap();
    }

    // Draw winner
    draffle_program_test
        .process_tx_and_assert_ok(
            &[Instruction {
                program_id,
                accounts: draffle::accounts::RevealWinners {
                    raffle,
                    recent_blockhashes: sysvar::recent_blockhashes::ID,
                }
                .to_account_metas(None),
                data: draffle::instruction::RevealWinners.data(),
            }],
            &[],
        )
        .await;

    let raffle_data = &draffle_program_test
        .context
        .banks_client
        .get_account(raffle)
        .await
        .unwrap()
        .unwrap()
        .data;
    let raffle_state: Raffle = Raffle::try_deserialize(&mut raffle_data.as_ref()).unwrap();

    assert_eq!(true, raffle_state.randomness.is_some());

    // Claim first prize
    let entrants_data = &draffle_program_test
        .context
        .banks_client
        .get_account(entrants_keypair.pubkey())
        .await
        .unwrap()
        .unwrap()
        .data;
    let entrants: &Entrants = bytemuck::from_bytes::<Entrants>(&entrants_data[8..]);
    println!("{:?}", &entrants.entrants[..20]);

    let first_prize_winner_ticket =
        draffle::randomness_tools::expand(raffle_state.randomness.unwrap(), 0) % entrants.total;
    let first_prize_winner = entrants.entrants[first_prize_winner_ticket as usize];
    let winner_prize_ata = spl_associated_token_account::get_associated_token_address(
        &first_prize_winner,
        &first_prize_mint_keypair.pubkey(),
    );

    println!("first_prize_winner_ticket: {}", first_prize_winner_ticket);
    println!("Entrants data winner: {}", first_prize_winner);

    draffle_program_test
        .process_tx_and_assert_ok(
            &[
                spl_associated_token_account::create_associated_token_account(
                    &payer_pk,
                    &first_prize_winner,
                    &first_prize_mint_keypair.pubkey(),
                ),
                Instruction {
                    program_id,
                    accounts: draffle::accounts::ClaimPrize {
                        raffle,
                        entrants: entrants_keypair.pubkey(),
                        prize: first_prize,
                        winner_token_account: winner_prize_ata,
                        token_program: spl_token::ID,
                    }
                    .to_account_metas(None),
                    data: draffle::instruction::ClaimPrize {
                        prize_index: 0,
                        ticket_index: first_prize_winner_ticket,
                    }
                    .data(),
                },
            ],
            &[],
        )
        .await;

    // Close entrants before all prizes are claimed
    draffle_program_test
        .process_tx_and_assert_err(
            &[Instruction {
                program_id,
                accounts: draffle::accounts::CloseEntrants {
                    raffle,
                    entrants: entrants_keypair.pubkey(),
                    creator: payer_pk,
                }
                .to_account_metas(None),
                data: draffle::instruction::CloseEntrants.data(),
            }],
            &[],
            TransactionError::InstructionError(
                0,
                InstructionError::Custom(draffle::RaffleError::UnclaimedPrizes as u32 + 300),
            ),
        )
        .await;

    // Claim second prize
    let second_prize_winner_ticket =
        draffle::randomness_tools::expand(raffle_state.randomness.unwrap(), 1) % entrants.total;
    let second_prize_winner = entrants.entrants[second_prize_winner_ticket as usize];
    let second_prize_winner_ata = spl_associated_token_account::get_associated_token_address(
        &second_prize_winner,
        &second_prize_mint_keypair.pubkey(),
    );

    draffle_program_test
        .process_tx_and_assert_ok(
            &[
                spl_associated_token_account::create_associated_token_account(
                    &payer_pk,
                    &second_prize_winner,
                    &second_prize_mint_keypair.pubkey(),
                ),
                Instruction {
                    program_id,
                    accounts: draffle::accounts::ClaimPrize {
                        raffle,
                        entrants: entrants_keypair.pubkey(),
                        prize: second_prize,
                        winner_token_account: second_prize_winner_ata,
                        token_program: spl_token::ID,
                    }
                    .to_account_metas(None),
                    data: draffle::instruction::ClaimPrize {
                        prize_index: 1,
                        ticket_index: second_prize_winner_ticket,
                    }
                    .data(),
                },
            ],
            &[],
        )
        .await;

    // Collect proceeds
    draffle_program_test
        .process_tx_and_assert_ok(
            &[Instruction {
                program_id,
                accounts: draffle::accounts::CollectProceeds {
                    raffle,
                    proceeds,
                    creator: payer_pk,
                    creator_proceeds: creator_proceeds_ata,
                    token_program: spl_token::ID,
                }
                .to_account_metas(None),
                data: draffle::instruction::CollectProceeds.data(),
            }],
            &[],
        )
        .await;

    // Close entrants
    draffle_program_test
        .process_tx_and_assert_ok(
            &[
                Instruction {
                    program_id,
                    accounts: draffle::accounts::CloseEntrants {
                        raffle,
                        entrants: entrants_keypair.pubkey(),
                        creator: payer_pk,
                    }
                    .to_account_metas(None),
                    data: draffle::instruction::CloseEntrants.data(),
                },
                // Self transfer to prevent identical signature as before
                system_instruction::transfer(&payer_pk, &payer_pk, 0),
            ],
            &[],
        )
        .await;
}

pub async fn initialize_mint(
    mint_keypair: &Keypair,
    decimals: u8,
    draffle_program_test: &mut DraffleProgramTest,
) {
    let mint_rent_exempt_threshold = draffle_program_test
        .context
        .banks_client
        .get_rent()
        .await
        .unwrap()
        .minimum_balance(spl_token::state::Mint::LEN);

    draffle_program_test
        .process_tx_and_assert_ok(
            &[
                system_instruction::create_account(
                    &draffle_program_test.context.payer.pubkey(),
                    &mint_keypair.pubkey(),
                    mint_rent_exempt_threshold,
                    spl_token::state::Mint::LEN as u64,
                    &spl_token::id(),
                ),
                spl_token::instruction::initialize_mint(
                    &spl_token::id(),
                    &mint_keypair.pubkey(),
                    &draffle_program_test.context.payer.pubkey(),
                    None,
                    decimals,
                )
                .unwrap(),
            ],
            &[mint_keypair],
        )
        .await;
}

pub async fn initialize_ata(
    user: &Pubkey,
    mint: &Pubkey,
    draffle_program_test: &mut DraffleProgramTest,
) -> Pubkey {
    draffle_program_test
        .process_tx_and_assert_ok(
            &[
                spl_associated_token_account::create_associated_token_account(
                    &draffle_program_test.context.payer.pubkey(),
                    user,
                    mint,
                ),
            ],
            &[],
        )
        .await;
    spl_associated_token_account::get_associated_token_address(user, mint)
}

// To simplify, the payer is mint authority of all mints
pub async fn mint_some(
    token_account: &Pubkey,
    mint: &Pubkey,
    draffle_program_test: &mut DraffleProgramTest,
    amount: u64,
) {
    draffle_program_test
        .process_tx_and_assert_ok(
            &[spl_token::instruction::mint_to(
                &spl_token::id(),
                mint,
                &token_account,
                &draffle_program_test.context.payer.pubkey(),
                &[],
                amount,
            )
            .unwrap()],
            &[],
        )
        .await;
}

pub struct User {
    keypair: Keypair,
    proceeds_mint_ata: Pubkey,
}

async fn prepare_users(
    proceeds_mint: &Pubkey,
    draffle_program_test: &mut DraffleProgramTest,
) -> Vec<User> {
    let mut users = Vec::new();
    for _ in 0..10 {
        let keypair = Keypair::new();
        let proceeds_mint_ata =
            initialize_ata(&keypair.pubkey(), proceeds_mint, draffle_program_test).await;
        mint_some(
            &proceeds_mint_ata,
            proceeds_mint,
            draffle_program_test,
            1000000,
        )
        .await;
        users.push(User {
            keypair,
            proceeds_mint_ata,
        })
    }
    users
}

fn fibonacci(n: u32) -> u32 {
    match n {
        0 => 1,
        1 => 1,
        _ => fibonacci(n - 1) + fibonacci(n - 2),
    }
}

pub struct DraffleProgramTest {
    pub context: ProgramTestContext,
    pub rent: Rent,
    pub program_id: Pubkey,
}

impl DraffleProgramTest {
    pub async fn start_new() -> Self {
        let program_id = Pubkey::from_str("DJgm9u3C2eiWVeokxwzJ92GbS5j2qiqsZ16YMoe8ShXf").unwrap();
        let pt = ProgramTest::new("draffle", program_id.clone(), processor!(draffle::entry));

        let mut context = pt.start_with_context().await;
        let rent = context.banks_client.get_rent().await.unwrap();

        Self {
            context,
            rent,
            program_id,
        }
    }

    pub async fn process_tx_and_assert_ok(
        &mut self,
        instructions: &[Instruction],
        signers: &[&Keypair],
    ) {
        let mut all_signers = vec![&self.context.payer];
        all_signers.extend_from_slice(signers);

        let tx = Transaction::new_signed_with_payer(
            &instructions,
            Some(&self.context.payer.pubkey()),
            &all_signers,
            self.context.last_blockhash,
        );

        assert_matches!(
            self.context.banks_client.process_transaction(tx).await,
            Ok(())
        );
    }

    pub async fn process_tx_and_assert_err(
        &mut self,
        instructions: &[Instruction],
        signers: &[&Keypair],
        transaction_error: TransactionError,
    ) {
        let mut all_signers = vec![&self.context.payer];
        all_signers.extend_from_slice(signers);

        let tx = Transaction::new_signed_with_payer(
            &instructions,
            Some(&self.context.payer.pubkey()),
            &all_signers,
            self.context.last_blockhash,
        );

        assert_eq!(
            transaction_error,
            self.context
                .banks_client
                .process_transaction(tx)
                .await
                .unwrap_err()
                .unwrap(),
        );
    }

    pub async fn get_clock(&mut self) -> Clock {
        deserialize::<Clock>(
            &self
                .context
                .banks_client
                .get_account(sysvar::clock::ID)
                .await
                .unwrap()
                .unwrap()
                .data,
        )
        .unwrap()
    }
}