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
//! On-chain program invoke helper to perform on-chain `execute` with correct
//! accounts

use {
    crate::{error::TransferHookError, get_extra_account_metas_address, instruction},
    solana_program::{
        account_info::AccountInfo,
        entrypoint::ProgramResult,
        instruction::{AccountMeta, Instruction},
        program::invoke,
        pubkey::Pubkey,
    },
    spl_tlv_account_resolution::state::ExtraAccountMetaList,
};
/// Helper to CPI into a transfer-hook program on-chain, looking through the
/// additional account infos to create the proper instruction
pub fn invoke_execute<'a>(
    program_id: &Pubkey,
    source_info: AccountInfo<'a>,
    mint_info: AccountInfo<'a>,
    destination_info: AccountInfo<'a>,
    authority_info: AccountInfo<'a>,
    additional_accounts: &[AccountInfo<'a>],
    amount: u64,
) -> ProgramResult {
    let validation_pubkey = get_extra_account_metas_address(mint_info.key, program_id);
    let validation_info = additional_accounts
        .iter()
        .find(|&x| *x.key == validation_pubkey)
        .ok_or(TransferHookError::IncorrectAccount)?;
    let mut cpi_instruction = instruction::execute(
        program_id,
        source_info.key,
        mint_info.key,
        destination_info.key,
        authority_info.key,
        &validation_pubkey,
        amount,
    );

    let mut cpi_account_infos = vec![
        source_info,
        mint_info,
        destination_info,
        authority_info,
        validation_info.clone(),
    ];
    ExtraAccountMetaList::add_to_cpi_instruction::<instruction::ExecuteInstruction>(
        &mut cpi_instruction,
        &mut cpi_account_infos,
        &validation_info.try_borrow_data()?,
        additional_accounts,
    )?;
    invoke(&cpi_instruction, &cpi_account_infos)
}

/// Helper to add accounts required for an `ExecuteInstruction` on-chain,
/// looking through the additional account infos to add the proper accounts.
///
/// Note this helper is designed to add the extra accounts that will be
/// required for a CPI to a transfer hook program. However, the instruction
/// being provided to this helper is for the program that will CPI to the
/// transfer hook program. Because of this, we must resolve the extra accounts
/// for the `ExecuteInstruction` CPI, then add those extra resolved accounts to
/// the provided instruction.
#[allow(clippy::too_many_arguments)]
pub fn add_extra_accounts_for_execute_cpi<'a>(
    cpi_instruction: &mut Instruction,
    cpi_account_infos: &mut Vec<AccountInfo<'a>>,
    program_id: &Pubkey,
    source_info: AccountInfo<'a>,
    mint_info: AccountInfo<'a>,
    destination_info: AccountInfo<'a>,
    authority_info: AccountInfo<'a>,
    amount: u64,
    additional_accounts: &[AccountInfo<'a>],
) -> ProgramResult {
    let validate_state_pubkey = get_extra_account_metas_address(mint_info.key, program_id);
    let validate_state_info = additional_accounts
        .iter()
        .find(|&x| *x.key == validate_state_pubkey)
        .ok_or(TransferHookError::IncorrectAccount)?;

    let program_info = additional_accounts
        .iter()
        .find(|&x| x.key == program_id)
        .ok_or(TransferHookError::IncorrectAccount)?;

    let mut execute_instruction = instruction::execute(
        program_id,
        source_info.key,
        mint_info.key,
        destination_info.key,
        authority_info.key,
        &validate_state_pubkey,
        amount,
    );
    let mut execute_account_infos = vec![
        source_info,
        mint_info,
        destination_info,
        authority_info,
        validate_state_info.clone(),
    ];

    ExtraAccountMetaList::add_to_cpi_instruction::<instruction::ExecuteInstruction>(
        &mut execute_instruction,
        &mut execute_account_infos,
        &validate_state_info.try_borrow_data()?,
        additional_accounts,
    )?;

    // Add only the extra accounts resolved from the validation state
    cpi_instruction
        .accounts
        .extend_from_slice(&execute_instruction.accounts[5..]);
    cpi_account_infos.extend_from_slice(&execute_account_infos[5..]);

    // Add the program id and validation state account
    cpi_instruction
        .accounts
        .push(AccountMeta::new_readonly(*program_id, false));
    cpi_instruction
        .accounts
        .push(AccountMeta::new_readonly(validate_state_pubkey, false));
    cpi_account_infos.push(program_info.clone());
    cpi_account_infos.push(validate_state_info.clone());

    Ok(())
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        crate::instruction::ExecuteInstruction,
        solana_program::{bpf_loader_upgradeable, system_program},
        spl_tlv_account_resolution::{
            account::ExtraAccountMeta, error::AccountResolutionError, seeds::Seed,
        },
    };

    const EXTRA_META_1: Pubkey = Pubkey::new_from_array([2u8; 32]);
    const EXTRA_META_2: Pubkey = Pubkey::new_from_array([3u8; 32]);

    fn setup_validation_data() -> Vec<u8> {
        let extra_metas = vec![
            ExtraAccountMeta::new_with_pubkey(&EXTRA_META_1, true, false).unwrap(),
            ExtraAccountMeta::new_with_pubkey(&EXTRA_META_2, true, false).unwrap(),
            ExtraAccountMeta::new_with_seeds(
                &[
                    Seed::AccountKey { index: 0 }, // source
                    Seed::AccountKey { index: 2 }, // destination
                    Seed::AccountKey { index: 4 }, // validation state
                ],
                false,
                true,
            )
            .unwrap(),
            ExtraAccountMeta::new_with_seeds(
                &[
                    Seed::InstructionData {
                        index: 8,
                        length: 8,
                    }, // amount
                    Seed::AccountKey { index: 2 }, // destination
                    Seed::AccountKey { index: 5 }, // extra meta 1
                    Seed::AccountKey { index: 7 }, // extra meta 3 (PDA)
                ],
                false,
                true,
            )
            .unwrap(),
        ];
        let account_size = ExtraAccountMetaList::size_of(extra_metas.len()).unwrap();
        let mut data = vec![0u8; account_size];
        ExtraAccountMetaList::init::<ExecuteInstruction>(&mut data, &extra_metas).unwrap();
        data
    }

    #[test]
    fn test_add_extra_accounts_for_execute_cpi() {
        let spl_token_2022_program_id = Pubkey::new_unique(); // Mock
        let transfer_hook_program_id = Pubkey::new_unique();

        let amount = 100u64;

        let source_pubkey = Pubkey::new_unique();
        let mut source_data = vec![0; 165]; // Mock
        let mut source_lamports = 0; // Mock
        let source_account_info = AccountInfo::new(
            &source_pubkey,
            false,
            true,
            &mut source_lamports,
            &mut source_data,
            &spl_token_2022_program_id,
            false,
            0,
        );

        let mint_pubkey = Pubkey::new_unique();
        let mut mint_data = vec![0; 165]; // Mock
        let mut mint_lamports = 0; // Mock
        let mint_account_info = AccountInfo::new(
            &mint_pubkey,
            false,
            true,
            &mut mint_lamports,
            &mut mint_data,
            &spl_token_2022_program_id,
            false,
            0,
        );

        let destination_pubkey = Pubkey::new_unique();
        let mut destination_data = vec![0; 165]; // Mock
        let mut destination_lamports = 0; // Mock
        let destination_account_info = AccountInfo::new(
            &destination_pubkey,
            false,
            true,
            &mut destination_lamports,
            &mut destination_data,
            &spl_token_2022_program_id,
            false,
            0,
        );

        let authority_pubkey = Pubkey::new_unique();
        let mut authority_data = vec![]; // Mock
        let mut authority_lamports = 0; // Mock
        let authority_account_info = AccountInfo::new(
            &authority_pubkey,
            false,
            true,
            &mut authority_lamports,
            &mut authority_data,
            &system_program::ID,
            false,
            0,
        );

        let validate_state_pubkey =
            get_extra_account_metas_address(&mint_pubkey, &transfer_hook_program_id);

        let extra_meta_1_pubkey = EXTRA_META_1;
        let mut extra_meta_1_data = vec![]; // Mock
        let mut extra_meta_1_lamports = 0; // Mock
        let extra_meta_1_account_info = AccountInfo::new(
            &extra_meta_1_pubkey,
            true,
            false,
            &mut extra_meta_1_lamports,
            &mut extra_meta_1_data,
            &system_program::ID,
            false,
            0,
        );

        let extra_meta_2_pubkey = EXTRA_META_2;
        let mut extra_meta_2_data = vec![]; // Mock
        let mut extra_meta_2_lamports = 0; // Mock
        let extra_meta_2_account_info = AccountInfo::new(
            &extra_meta_2_pubkey,
            true,
            false,
            &mut extra_meta_2_lamports,
            &mut extra_meta_2_data,
            &system_program::ID,
            false,
            0,
        );

        let extra_meta_3_pubkey = Pubkey::find_program_address(
            &[
                &source_pubkey.to_bytes(),
                &destination_pubkey.to_bytes(),
                &validate_state_pubkey.to_bytes(),
            ],
            &transfer_hook_program_id,
        )
        .0;
        let mut extra_meta_3_data = vec![]; // Mock
        let mut extra_meta_3_lamports = 0; // Mock
        let extra_meta_3_account_info = AccountInfo::new(
            &extra_meta_3_pubkey,
            false,
            true,
            &mut extra_meta_3_lamports,
            &mut extra_meta_3_data,
            &transfer_hook_program_id,
            false,
            0,
        );

        let extra_meta_4_pubkey = Pubkey::find_program_address(
            &[
                &amount.to_le_bytes(),
                &destination_pubkey.to_bytes(),
                &extra_meta_1_pubkey.to_bytes(),
                &extra_meta_3_pubkey.to_bytes(),
            ],
            &transfer_hook_program_id,
        )
        .0;
        let mut extra_meta_4_data = vec![]; // Mock
        let mut extra_meta_4_lamports = 0; // Mock
        let extra_meta_4_account_info = AccountInfo::new(
            &extra_meta_4_pubkey,
            false,
            true,
            &mut extra_meta_4_lamports,
            &mut extra_meta_4_data,
            &transfer_hook_program_id,
            false,
            0,
        );

        let mut validate_state_data = setup_validation_data();
        let mut validate_state_lamports = 0; // Mock
        let validate_state_account_info = AccountInfo::new(
            &validate_state_pubkey,
            false,
            true,
            &mut validate_state_lamports,
            &mut validate_state_data,
            &transfer_hook_program_id,
            false,
            0,
        );

        let mut transfer_hook_program_data = vec![]; // Mock
        let mut transfer_hook_program_lamports = 0; // Mock
        let transfer_hook_program_account_info = AccountInfo::new(
            &transfer_hook_program_id,
            false,
            true,
            &mut transfer_hook_program_lamports,
            &mut transfer_hook_program_data,
            &bpf_loader_upgradeable::ID,
            false,
            0,
        );

        let mut cpi_instruction = Instruction::new_with_bytes(
            spl_token_2022_program_id,
            &[],
            vec![
                AccountMeta::new(source_pubkey, false),
                AccountMeta::new_readonly(mint_pubkey, false),
                AccountMeta::new(destination_pubkey, false),
                AccountMeta::new_readonly(authority_pubkey, true),
            ],
        );
        let mut cpi_account_infos = vec![
            source_account_info.clone(),
            mint_account_info.clone(),
            destination_account_info.clone(),
            authority_account_info.clone(),
        ];
        let additional_account_infos = vec![
            extra_meta_1_account_info.clone(),
            extra_meta_2_account_info.clone(),
            extra_meta_3_account_info.clone(),
            extra_meta_4_account_info.clone(),
            transfer_hook_program_account_info.clone(),
            validate_state_account_info.clone(),
        ];

        // Fail missing validation info from additional account infos
        let additional_account_infos_missing_infos = vec![
            extra_meta_1_account_info.clone(),
            extra_meta_2_account_info.clone(),
            extra_meta_3_account_info.clone(),
            extra_meta_4_account_info.clone(),
            // validate state missing
            transfer_hook_program_account_info.clone(),
        ];
        assert_eq!(
            add_extra_accounts_for_execute_cpi(
                &mut cpi_instruction,
                &mut cpi_account_infos,
                &transfer_hook_program_id,
                source_account_info.clone(),
                mint_account_info.clone(),
                destination_account_info.clone(),
                authority_account_info.clone(),
                amount,
                &additional_account_infos_missing_infos, // Missing account info
            )
            .unwrap_err(),
            TransferHookError::IncorrectAccount.into()
        );

        // Fail missing program info from additional account infos
        let additional_account_infos_missing_infos = vec![
            extra_meta_1_account_info.clone(),
            extra_meta_2_account_info.clone(),
            extra_meta_3_account_info.clone(),
            extra_meta_4_account_info.clone(),
            validate_state_account_info.clone(),
            // transfer hook program missing
        ];
        assert_eq!(
            add_extra_accounts_for_execute_cpi(
                &mut cpi_instruction,
                &mut cpi_account_infos,
                &transfer_hook_program_id,
                source_account_info.clone(),
                mint_account_info.clone(),
                destination_account_info.clone(),
                authority_account_info.clone(),
                amount,
                &additional_account_infos_missing_infos, // Missing account info
            )
            .unwrap_err(),
            TransferHookError::IncorrectAccount.into()
        );

        // Fail missing extra meta info from additional account infos
        let additional_account_infos_missing_infos = vec![
            extra_meta_1_account_info.clone(),
            extra_meta_2_account_info.clone(),
            // extra meta 3 missing
            extra_meta_4_account_info.clone(),
            validate_state_account_info.clone(),
            transfer_hook_program_account_info.clone(),
        ];
        assert_eq!(
            add_extra_accounts_for_execute_cpi(
                &mut cpi_instruction,
                &mut cpi_account_infos,
                &transfer_hook_program_id,
                source_account_info.clone(),
                mint_account_info.clone(),
                destination_account_info.clone(),
                authority_account_info.clone(),
                amount,
                &additional_account_infos_missing_infos, // Missing account info
            )
            .unwrap_err(),
            AccountResolutionError::IncorrectAccount.into() // Note the error
        );

        // Success
        add_extra_accounts_for_execute_cpi(
            &mut cpi_instruction,
            &mut cpi_account_infos,
            &transfer_hook_program_id,
            source_account_info.clone(),
            mint_account_info.clone(),
            destination_account_info.clone(),
            authority_account_info.clone(),
            amount,
            &additional_account_infos,
        )
        .unwrap();

        let check_metas = [
            AccountMeta::new(source_pubkey, false),
            AccountMeta::new_readonly(mint_pubkey, false),
            AccountMeta::new(destination_pubkey, false),
            AccountMeta::new_readonly(authority_pubkey, true),
            AccountMeta::new_readonly(EXTRA_META_1, true),
            AccountMeta::new_readonly(EXTRA_META_2, true),
            AccountMeta::new(extra_meta_3_pubkey, false),
            AccountMeta::new(extra_meta_4_pubkey, false),
            AccountMeta::new_readonly(transfer_hook_program_id, false),
            AccountMeta::new_readonly(validate_state_pubkey, false),
        ];

        let check_account_infos = vec![
            source_account_info,
            mint_account_info,
            destination_account_info,
            authority_account_info,
            extra_meta_1_account_info,
            extra_meta_2_account_info,
            extra_meta_3_account_info,
            extra_meta_4_account_info,
            transfer_hook_program_account_info,
            validate_state_account_info,
        ];

        assert_eq!(cpi_instruction.accounts, check_metas);
        for (a, b) in std::iter::zip(cpi_account_infos, check_account_infos) {
            assert_eq!(a.key, b.key);
            assert_eq!(a.is_signer, b.is_signer);
            assert_eq!(a.is_writable, b.is_writable);
        }
    }
}