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
#![cfg_attr(doc_cfg, feature(doc_cfg))]

//!  The Solana Randomness Service uses a Switchboard SGX enabled oracle to provide randomness to any Solana program using a callback instruction.
//!
//!  **Program ID:** `RANDMo5gFnqnXJW5Z52KNmd24sAo95KAd5VbiCtq5Rh`
//!
//!  # Accounts:
//!
//!  - [State](State): The program state account. Stores the cost per byte of randomness, the Switchboard service, and the wallet that will accrue rewards for fulfilling randomness requests.
//!  - [SimpleRandomnessV1Account](SimpleRandomnessV1Account): Stores the user's request for randomness. This account is created on-chain and used by the off-chain oracle to fulfill the request. This account is automatically closed upon successful fulfillment.
//!
//!  # Admin Instructions:
//!
//!  - [initialize](initialize): init the program state and set the program authority permitted to make global config changes.
//!  - [set_fees](set_fees): Sets the randomness fee per byte of randomness requested. Doesnt include the 10_000 lamport base fee or the priority fees.
//!  - [set_switchboard_service](set_switchboard_service): Sets the SwitchboardService that will fulfill the request.
//!  - [program_authority_withdraw](program_authority_withdraw): Allows the program authority to withdraw from the reward escrow.
//!  - [switchboard_service_withdraw](switchboard_service_withdraw): Allows the Switchboard service to withdraw funds to pay for future requests
//!
//!  # Simple Randomness V1 Instructions:
//!
//!  - [simple_randomness_v1](simple_randomness_v1): Request randomness from the Switchboard service. This is the main instruction you will need to integrate.
//!  - [simple_randomness_v1_settle](simple_randomness_v1_settle): Settles a randomness request and invokes the user's callback.
//!  - [simple_randomness_v1_callback_error](simple_randomness_v1_callback_error): Sets the error message for a randomness request. This provides visibility to the user that the request failed off-chain.
//!  - [simple_randomness_v1_callback_close](simple_randomness_v1_callback_close): Allows the user to acknowledge the error message and close the request.
//!
//!  # Example Program
//!
//!  ```
//!   use solana_randomness_service::SimpleRandomnessV1Account;
//!   use solana_randomness_service::{
//!       program::SolanaRandomnessService, ID as SolanaRandomnessServiceID,
//!   };
//!   use switchboard_solana::prelude::*;
//!   use switchboard_solana::utils::get_ixn_discriminator;
//!
//!   declare_id!("39hMZgeiesFXMRFt8svuKVsdCW5geiYueSRx7dxhXN4f");
//!
//!   #[program]
//!   pub mod solana_randomness_consumer {
//!       use super::*;
//!
//!       pub fn request_randomness(ctx: Context<RequestRandomness>) -> anchor_lang::prelude::Result<()> {
//!           msg!("Requesting randomness...");
//!
//!           // 1. Call the randomness service and request a new value
//!           solana_randomness_service::cpi::simple_randomness_v1(
//!               CpiContext::new(
//!                   ctx.accounts.randomness_service.to_account_info(),
//!                   solana_randomness_service::cpi::accounts::SimpleRandomnessV1Request {
//!                       request: ctx.accounts.randomness_request.to_account_info(),
//!                       escrow: ctx.accounts.randomness_escrow.to_account_info(),
//!                       state: ctx.accounts.randomness_state.to_account_info(),
//!                       mint: ctx.accounts.randomness_mint.to_account_info(),
//!                       payer: ctx.accounts.payer.to_account_info(),
//!                       system_program: ctx.accounts.system_program.to_account_info(),
//!                       token_program: ctx.accounts.token_program.to_account_info(),
//!                       associated_token_program: ctx
//!                           .accounts
//!                           .associated_token_program
//!                           .to_account_info(),
//!                   },
//!               ),
//!               8, // Request 8 bytes of randomness
//!               solana_randomness_service::Callback {
//!                   program_id: ID,
//!                   accounts: vec![
//!                       AccountMeta::new_readonly(ctx.accounts.randomness_state.key(), true).into(),
//!                       AccountMeta::new_readonly(ctx.accounts.randomness_request.key(), false).into(),
//!                   ],
//!                   ix_data: get_ixn_discriminator("consume_randomness").to_vec(), // TODO: hardcode this discriminator [190,217,49,162,99,26,73,234]
//!               },
//!               Some(use solana_randomness_service::TransactionOptions {
//!                   compute_units: Some(1_000_000),
//!                   compute_unit_price: Some(100),
//!               }),
//!           )?;
//!
//!           // Here we can emit some event to index our requests
//!
//!           Ok(())
//!       }
//!
//!       // 2. Build the instruction that will be called with the randomness bytes. The randomness bytes Vec will be appended to the end of the ixn data.
//!       pub fn consume_randomness(
//!           _ctx: Context<ConsumeRandomness>,
//!           result: Vec<u8>,
//!       ) -> anchor_lang::prelude::Result<()> {
//!           msg!("Randomness received: {:?}", result);
//!           Ok(())
//!       }
//!   }
//!
//!   // The request_randomness macro breaks IDL generation. So we'll manually implement.
//!   // #[request_randomness]
//!   #[derive(Accounts)]
//!   pub struct RequestRandomness<'info> {
//!       //!  The Solana Randomness Service program.
//!       pub randomness_service: Program<'info, SolanaRandomnessService>,
//!
//!       //!  The account that will be created on-chain to hold the randomness request.
//!       //!  Used by the off-chain oracle to pickup the request and fulfill it.
//!       //!  CHECK: todo
//!       #[account(
//!           mut,
//!           signer,
//!           owner = system_program.key(),
//!           constraint = randomness_request.data_len() == 0 && randomness_request.lamports() == 0,
//!       )]
//!       pub randomness_request: AccountInfo<'info>,
//!
//!       //!  The TokenAccount that will store the funds for the randomness request.
//!       //!  CHECK: todo
//!       #[account(
//!           mut,
//!           owner = system_program.key(),
//!           constraint = randomness_escrow.data_len() == 0 && randomness_escrow.lamports() == 0,
//!       )]
//!       pub randomness_escrow: AccountInfo<'info>,
//!
//!       //!  The randomness service's state account. Responsible for storing the
//!       //!  reward escrow and the cost per random byte.
//!       #[account(
//!           seeds = [b"STATE"],
//!           bump = randomness_state.bump,
//!           seeds::program = randomness_service.key(),
//!       )]
//!       pub randomness_state: Box<Account<'info, solana_randomness_service::State>>,
//!
//!       //!  The token mint to use for paying for randomness requests.
//!       #[account(address = NativeMint::ID)]
//!       pub randomness_mint: Account<'info, Mint>,
//!
//!       //!  The account that will pay for the randomness request.
//!       #[account(mut)]
//!       pub payer: Signer<'info>,
//!
//!       //!  The Solana System program. Used to allocate space on-chain for the randomness_request account.
//!       pub system_program: Program<'info, System>,
//!
//!       //!  The Solana Token program. Used to transfer funds to the randomness escrow.
//!       pub token_program: Program<'info, Token>,
//!
//!       //!  The Solana Associated Token program. Used to create the TokenAccount for the randomness escrow.
//!       pub associated_token_program: Program<'info, AssociatedToken>,
//!   }
//!
//!   #[derive(Accounts)]
//!   pub struct ConsumeRandomness<'info> {
//!       //!  We need to make sure the randomness service signed this requests so it can only be invoked by a PDA and not a user.
//!       #[account(
//!           signer,
//!           seeds = [b"STATE"],
//!           seeds::program = SolanaRandomnessServiceID,
//!           bump = randomness_state.bump,
//!       )]
//!       pub randomness_state: Box<Account<'info, solana_randomness_service::State>>,
//!
//!       pub request: Box<Account<'info, SimpleRandomnessV1Account>>,
//!   }
//!  ```
use switchboard_solana::prelude::*;

pub use anchor_spl::token::CloseAccount;
pub use anchor_spl::token::{spl_token::instruction::AuthorityType, SetAuthority};
pub use solana_program::sysvar::instructions::ID as SYSVAR_INSTRUCTIONS_ID;
pub use switchboard_solana::prelude::NativeMint;

pub mod types;
pub use types::{AccountMetaBorsh, Callback, TransactionOptions};

mod errors;
pub use errors::*;

mod events;
pub use events::*;

mod utils;
pub use utils::*;

pub mod impls;
pub use impls::*;

pub mod actions;
pub use actions::*;

declare_id!("RANDMo5gFnqnXJW5Z52KNmd24sAo95KAd5VbiCtq5Rh");

pub type Ctx<'a, 'info, T> = Context<'a, 'a, 'a, 'info, T>;

#[program]
pub mod solana_randomness_service {

    use super::*;

    /// Initializes the program state and sets the:
    /// - program authority
    /// - Switchboard service that is used to fulfill requests
    /// - The cost per randomness byte, in addition to 5000 lamports for the txn fee
    /// - The wallet that will accrue rewards for fulfilling randomness
    pub fn initialize(
        ctx: Context<Initialize>,
        cost_per_byte: u64,
    ) -> anchor_lang::prelude::Result<()> {
        ctx.accounts.state.bump = ctx.bumps.state;
        ctx.accounts.state.authority = ctx.accounts.payer.key();
        ctx.accounts.state.mint = ctx.accounts.mint.key();
        ctx.accounts.state.switchboard_service = ctx.accounts.switchboard_service.key();
        ctx.accounts.state.wallet = ctx.accounts.wallet.key();
        ctx.accounts.state.cost_per_byte = cost_per_byte;

        Ok(())
    }

    /// Sets the fees for requesting randomness
    pub fn set_fees(
        ctx: Context<SetFeeConfig>,
        cost_per_byte: u64,
    ) -> anchor_lang::prelude::Result<()> {
        // TODO: this may cause in-flight requests to fail

        ctx.accounts.state.cost_per_byte = cost_per_byte;
        ctx.accounts.state.last_updated = Clock::get()?.unix_timestamp;

        Ok(())
    }

    /// Sets the Switchboard service that will be used to fulfill requests.
    pub fn set_switchboard_service(
        ctx: Context<SetSwitchboardService>,
    ) -> anchor_lang::prelude::Result<()> {
        ctx.accounts.state.switchboard_service = ctx.accounts.switchboard_service.key();
        Ok(())
    }

    /// Allows the program authority to withdraw from the reward escrow.
    pub fn program_authority_withdraw(
        ctx: Context<ProgramAuthorityWithdraw>,
        amount: u64,
    ) -> anchor_lang::prelude::Result<()> {
        assert_not_cpi_call(&ctx.accounts.instructions_sysvar)?;

        if ctx.accounts.wallet.amount < amount {
            return Err(error!(RandomnessError::ProgramWalletInsufficientFunds));
        }

        // Transfer funds to our destination wallet
        transfer(
            &ctx.accounts.token_program.to_account_info(),
            &ctx.accounts.wallet,
            &ctx.accounts.ephemeral_wallet,
            &ctx.accounts.state.to_account_info(),
            &[&[b"STATE", &[ctx.accounts.state.bump]]],
            amount,
        )?;

        // Close the token account
        anchor_spl::token::close_account(CpiContext::new(
            ctx.accounts.token_program.to_account_info(),
            CloseAccount {
                account: ctx.accounts.ephemeral_wallet.to_account_info(),
                destination: ctx.accounts.authority.to_account_info(),
                authority: ctx.accounts.authority.to_account_info(),
            },
        ))?;

        Ok(())
    }

    /// Allows the Switchboard service to withdraw funds to pay for future requests
    pub fn switchboard_service_withdraw(
        ctx: Context<SwitchboardServiceWithdraw>,
        amount: u64,
    ) -> anchor_lang::prelude::Result<()> {
        assert_not_cpi_call(&ctx.accounts.instructions_sysvar)?;

        if ctx.accounts.wallet.amount < amount {
            return Err(error!(RandomnessError::ProgramWalletInsufficientFunds));
        }

        // Transfer funds to our destination wallet
        transfer(
            &ctx.accounts.token_program.to_account_info(),
            &ctx.accounts.wallet,
            &ctx.accounts.ephemeral_wallet,
            &ctx.accounts.state.to_account_info(),
            &[&[b"STATE", &[ctx.accounts.state.bump]]],
            amount,
        )?;

        // Close the token account
        anchor_spl::token::close_account(CpiContext::new(
            ctx.accounts.token_program.to_account_info(),
            CloseAccount {
                account: ctx.accounts.ephemeral_wallet.to_account_info(),
                destination: ctx.accounts.payer.to_account_info(),
                authority: ctx.accounts.payer.to_account_info(),
            },
        ))?;

        Ok(())
    }

    ////////////////////////////////////////////////////////////////////////
    /// Simple Randomness V1
    ////////////////////////////////////////////////////////////////////////

    /// Request randomness from the Switchboard service.
    #[access_control(ctx.accounts.validate(&ctx, num_bytes, &callback, &options))]
    pub fn simple_randomness_v1<'a>(
        mut ctx: Ctx<'_, 'a, SimpleRandomnessV1Request<'a>>,
        num_bytes: u8,
        callback: Callback,
        options: Option<TransactionOptions>,
    ) -> anchor_lang::prelude::Result<()> {
        SimpleRandomnessV1Request::actuate(&mut ctx, num_bytes, &callback, &options)
    }

    /// Settles a randomness request and invokes the user's callback.
    #[access_control(ctx.accounts.validate(&ctx,  &randomness))]
    pub fn simple_randomness_v1_settle<'a>(
        mut ctx: Ctx<'_, 'a, SimpleRandomnessV1Settle<'a>>,
        randomness: Vec<u8>,
    ) -> anchor_lang::prelude::Result<()> {
        SimpleRandomnessV1Settle::actuate(&mut ctx, randomness)
    }

    /// Sets the error message for a randomness request. This provides visibility to the user that the request failed off-chain.
    #[access_control(ctx.accounts.validate(&ctx,  &error_message))]
    pub fn simple_randomness_v1_callback_error<'a>(
        mut ctx: Ctx<'_, 'a, SimpleRandomnessV1CallbackError<'a>>,
        error_message: String,
    ) -> anchor_lang::prelude::Result<()> {
        SimpleRandomnessV1CallbackError::actuate(&mut ctx, &error_message)
    }

    /// Allows the user to acknowledge the error message and close the request.
    #[access_control(ctx.accounts.validate(&ctx,  ))]
    pub fn simple_randomness_v1_callback_close<'a>(
        mut ctx: Ctx<'_, 'a, SimpleRandomnessV1Close<'a>>,
    ) -> anchor_lang::prelude::Result<()> {
        SimpleRandomnessV1Close::actuate(&mut ctx)
    }
}

/////////////////////////////////////////////////////////////
/// Initialize
/////////////////////////////////////////////////////////////

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(mut)]
    pub payer: Signer<'info>,

    #[account(
        init,
        payer = payer,
        space = State::size(),
        seeds = [b"STATE"],
        bump,
    )]
    pub state: Box<Account<'info, State>>,

    #[account(
        init,
        payer = payer,
        associated_token::mint = mint,
        associated_token::authority = state
    )]
    pub wallet: Box<Account<'info, TokenAccount>>,

    #[account(address = NativeMint::ID)]
    pub mint: Account<'info, Mint>,

    #[account(
        constraint = switchboard_function.load()?.services_enabled.to_bool() &&
            switchboard_service.function == switchboard_function.key()
    )]
    pub switchboard_function: AccountLoader<'info, FunctionAccountData>,
    pub switchboard_service: Box<Account<'info, FunctionServiceAccountData>>,

    pub system_program: Program<'info, System>,

    pub token_program: Program<'info, Token>,

    pub associated_token_program: Program<'info, AssociatedToken>,
}

#[derive(Accounts)]
pub struct SetFeeConfig<'info> {
    #[account(
        mut,
        seeds = [b"STATE"],
        bump = state.bump,
        has_one = authority,
    )]
    pub state: Box<Account<'info, State>>,

    pub authority: Signer<'info>,
}

#[derive(Accounts)]
pub struct SetSwitchboardService<'info> {
    #[account(
        mut,
        seeds = [b"STATE"],
        bump = state.bump,
        has_one = authority,
    )]
    pub state: Box<Account<'info, State>>,

    pub authority: Signer<'info>,

    #[account(
        constraint = switchboard_function.load()?.services_enabled.to_bool() &&
            switchboard_service.function == switchboard_function.key()
    )]
    pub switchboard_function: AccountLoader<'info, FunctionAccountData>,
    pub switchboard_service: Box<Account<'info, FunctionServiceAccountData>>,
}

#[derive(Accounts)]
pub struct ProgramAuthorityWithdraw<'info> {
    #[account(
        seeds = [b"STATE"],
        bump = state.bump,
        has_one = wallet,
        has_one = authority,
        has_one = mint,
    )]
    pub state: Box<Account<'info, State>>,

    #[account(mut)]
    pub wallet: Box<Account<'info, TokenAccount>>,

    #[account(mut)]
    pub authority: Signer<'info>,

    #[account(
        init,
        payer = authority,
        token::mint = mint,
        token::authority = authority,
    )]
    pub ephemeral_wallet: Box<Account<'info, TokenAccount>>,

    #[account(address = NativeMint::ID)]
    pub mint: Account<'info, Mint>,

    pub system_program: Program<'info, System>,
    pub token_program: Program<'info, Token>,

    /// CHECK: todo
    #[account(
        address = SYSVAR_INSTRUCTIONS_ID,
    )]
    pub instructions_sysvar: AccountInfo<'info>,
}

// This ixn a
#[derive(Accounts)]
pub struct SwitchboardServiceWithdraw<'info> {
    #[account(mut)]
    pub payer: Signer<'info>,

    #[account(
        seeds = [b"STATE"],
        bump = state.bump,
        has_one = wallet,
        has_one = mint,
    )]
    pub state: Box<Account<'info, State>>,

    #[account(mut)]
    pub wallet: Box<Account<'info, TokenAccount>>,

    // SWITCHBOARD VALIDATION
    #[account(
        constraint = switchboard_function.load()?.validate_service(
            &switchboard_service,
            &enclave_signer.to_account_info(),
        )?
    )]
    pub switchboard_function: AccountLoader<'info, FunctionAccountData>,
    pub switchboard_service: Box<Account<'info, FunctionServiceAccountData>>,
    pub enclave_signer: Signer<'info>,

    #[account(
        init,
        payer = payer,
        token::mint = mint,
        token::authority = payer,
    )]
    pub ephemeral_wallet: Box<Account<'info, TokenAccount>>,

    #[account(address = NativeMint::ID)]
    pub mint: Account<'info, Mint>,

    pub system_program: Program<'info, System>,
    pub token_program: Program<'info, Token>,

    /// CHECK: todo
    #[account(
        address = SYSVAR_INSTRUCTIONS_ID,
    )]
    pub instructions_sysvar: AccountInfo<'info>,
}