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
use crate::*;

pub use std::collections::HashMap;

#[derive(Accounts)]
pub struct SimpleRandomnessV1Settle<'info> {
    /// CHECK:
    #[account(mut)]
    pub user: AccountInfo<'info>,

    #[account(
        mut,
        close = user,
        has_one = user,
        has_one = escrow,
        constraint = request.callback.program_id == callback_pid.key() @ RandomnessError::IncorrectCallbackProgramId,
    )]
    pub request: Box<Account<'info, SimpleRandomnessV1Account>>,

    #[account(
        mut,
        constraint = escrow.is_native() && escrow.owner == state.key(),
    )]
    pub escrow: Box<Account<'info, TokenAccount>>,

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

    #[account(
        mut,
        constraint = wallet.is_native() && wallet.owner == state.key(),
    )]
    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>,

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

    /// The account that pays for the randomness request
    #[account(mut)]
    pub payer: Signer<'info>,

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

impl<'info> SimpleRandomnessV1Settle<'info> {
    pub fn validate(&self, ctx: &Ctx<Self>, randomness: &[u8]) -> anchor_lang::Result<()> {
        // Verify this method was not called from a CPI
        assert_not_cpi_call(&ctx.accounts.instructions_sysvar)?;

        let num_bytes = randomness.len();
        if num_bytes == 0 || num_bytes > 32 {
            return Err(error!(RandomnessError::InvalidNumberOfBytes));
        }

        Ok(())
    }

    pub fn actuate(ctx: &mut Ctx<'_, 'info, Self>, randomness: Vec<u8>) -> anchor_lang::Result<()> {
        // Need to make sure the payer is not included in the callback as a writeable account. Otherwise, the payer could be drained of funds.
        for account in ctx.accounts.request.callback.accounts
            [..ctx.accounts.request.callback.accounts.len()]
            .iter()
        {
            if account.pubkey == ctx.accounts.payer.key() && account.is_writable {
                // TODO: We should still transfer funds and close the request without invoking the callback. Wasting our time.
                return Err(error!(RandomnessError::InvalidCallback));
            }
        }

        let txn_options = TransactionOptions {
            compute_units: Some(ctx.accounts.request.compute_units),
            compute_unit_price: Some(ctx.accounts.request.priority_fee_micro_lamports),
        };

        // Transfer reward (all funds) to the program_state
        let cost = ctx
            .accounts
            .state
            .request_cost(ctx.accounts.request.num_bytes, &txn_options);

        // verify the escrow has enough funds
        if cost > ctx.accounts.escrow.amount {
            return Err(error!(RandomnessError::InsufficientFunds));
        }

        if ctx.accounts.escrow.amount > 0 {
            transfer(
                &ctx.accounts.token_program.to_account_info(),
                &ctx.accounts.escrow,
                &ctx.accounts.wallet,
                &ctx.accounts.state.to_account_info(),
                &[&[b"STATE", &[ctx.accounts.state.bump]]],
                ctx.accounts.escrow.amount,
            )?;
        }

        // Perform callback into the clients program
        let user_callback = &ctx.accounts.request.callback;
        let mut is_success = false;

        if user_callback.program_id == Pubkey::default() {
            msg!("The user's callback is undefined, skipping callback")
        } else {
            let mut callback_account_metas: Vec<anchor_lang::prelude::AccountMeta> =
                Vec::with_capacity(user_callback.accounts.len() + 1);
            let mut callback_account_infos: Vec<AccountInfo> =
                Vec::with_capacity(user_callback.accounts.len() + 1);

            let remaining_accounts: HashMap<Pubkey, AccountInfo<'info>> = ctx
                .remaining_accounts
                .iter()
                .map(|a| (a.key(), a.clone()))
                .collect();

            for account in user_callback.accounts[..user_callback.accounts.len()].iter() {
                if account.pubkey == ctx.accounts.payer.key() && account.is_writable {
                    // TODO: handle this better
                    continue;
                }

                if account.pubkey == ctx.accounts.enclave_signer.key() {
                    // TODO: handle this better
                    continue;
                }

                if account.pubkey == ctx.accounts.request.key() {
                    callback_account_metas.push(account.into());
                    callback_account_infos.push(ctx.accounts.request.to_account_info());
                    continue;
                }

                if account.pubkey == ctx.accounts.state.key() {
                    if !account.is_signer {
                        return Err(error!(RandomnessError::InvalidCallback));
                    }

                    callback_account_metas.push(account.into());
                    callback_account_infos.push(ctx.accounts.state.to_account_info());
                    continue;
                }

                match remaining_accounts.get(&account.pubkey) {
                    None => {
                        msg!(
                            "Failed to find account in remaining_accounts {}",
                            account.pubkey
                        );
                        return Err(error!(RandomnessError::MissingCallbackAccount));
                    }
                    Some(account_info) => {
                        callback_account_metas.push(account.into());
                        callback_account_infos.push(account_info.clone());
                    }
                }
            }

            callback_account_infos.push(ctx.accounts.callback_pid.clone());

            // drop the HashMap
            drop(remaining_accounts);

            let callback_data = [
                user_callback.ix_data[..user_callback.ix_data.len()].to_vec(),
                (randomness.len() as u32).to_le_bytes().to_vec(),
                randomness.to_vec(),
            ]
            .concat();

            let callback_ix = Instruction {
                program_id: user_callback.program_id,
                data: callback_data,
                accounts: callback_account_metas,
            };

            msg!(">>> Invoking user callback <<<");

            // @DEV - we cannot catch this error. When a CPI fails the whole txn reverts.
            invoke_signed(
                &callback_ix,
                &callback_account_infos,
                &[&[b"STATE", &[ctx.accounts.state.bump]]],
            )?;

            msg!(">>> User callback succeeded <<<");
            is_success = true;
        }

        // Try to close the token account
        ctx.accounts.escrow.reload()?;

        anchor_spl::token::close_account(CpiContext::new_with_signer(
            ctx.accounts.token_program.to_account_info(),
            CloseAccount {
                account: ctx.accounts.escrow.to_account_info(),
                destination: ctx.accounts.user.to_account_info(),
                authority: ctx.accounts.state.to_account_info(),
            },
            &[&[b"STATE", &[ctx.accounts.state.bump]]],
        ))?;

        emit!(SimpleRandomnessV1SettledEvent {
            callback_pid: ctx.accounts.callback_pid.key(),
            request: ctx.accounts.request.key(),
            user: ctx.accounts.user.key(),
            is_success,
            randomness: randomness.to_vec(),
        });

        Ok(())
    }
}