trdelnik-client 0.1.5

The trdelnik_client crate helps you build and deploy an Anchor program to a local cluster and run a test suite against it.
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
//! The `idl` module contains structs and functions for Anchor program code parsing.
//!
//! [Idl] example:
//!
//! ```rust,ignore
//! Idl {
//!     programs: [
//!         IdlProgram {
//!             name: IdlName {
//!                 snake_case: "turnstile",
//!                 upper_camel_case: "Turnstile",
//!             },
//!             id: "[216u8 , 55u8 , 200u8 , 93u8 , 189u8 , 81u8 , 94u8 , 109u8 , 14u8 , 249u8 , 244u8 , 106u8 , 68u8 , 214u8 , 222u8 , 190u8 , 9u8 , 25u8 , 199u8 , 75u8 , 79u8 , 230u8 , 94u8 , 137u8 , 51u8 , 187u8 , 193u8 , 48u8 , 87u8 , 222u8 , 175u8 , 163u8]",
//!             instruction_account_pairs: [
//!                 (
//!                     IdlInstruction {
//!                         name: IdlName {
//!                             snake_case: "initialize",
//!                             upper_camel_case: "Initialize",
//!                         },
//!                         parameters: [],
//!                     },
//!                     IdlAccountGroup {
//!                         name: IdlName {
//!                             snake_case: "initialize",
//!                             upper_camel_case: "Initialize",
//!                         },
//!                         accounts: [
//!                             (
//!                                 "state",
//!                                 "anchor_lang :: solana_program :: pubkey :: Pubkey",
//!                             ),
//!                             (
//!                                 "user",
//!                                 "anchor_lang :: solana_program :: pubkey :: Pubkey",
//!                             ),
//!                             (
//!                                 "system_program",
//!                                 "anchor_lang :: solana_program :: pubkey :: Pubkey",
//!                             ),
//!                         ],
//!                     },
//!                 ),
//!                 (
//!                     IdlInstruction {
//!                         name: IdlName {
//!                             snake_case: "coin",
//!                             upper_camel_case: "Coin",
//!                         },
//!                         parameters: [
//!                             (
//!                                 "dummy_arg",
//!                                 "String",
//!                             ),
//!                         ],
//!                     },
//!                     IdlAccountGroup {
//!                         name: IdlName {
//!                             snake_case: "update_state",
//!                             upper_camel_case: "UpdateState",
//!                         },
//!                         accounts: [
//!                             (
//!                                 "state",
//!                                 "anchor_lang :: solana_program :: pubkey :: Pubkey",
//!                             ),
//!                         ],
//!                     },
//!                 ),
//!                 (
//!                     IdlInstruction {
//!                         name: IdlName {
//!                             snake_case: "push",
//!                             upper_camel_case: "Push",
//!                         },
//!                         parameters: [],
//!                     },
//!                     IdlAccountGroup {
//!                         name: IdlName {
//!                             snake_case: "update_state",
//!                             upper_camel_case: "UpdateState",
//!                         },
//!                         accounts: [
//!                             (
//!                                 "state",
//!                                 "anchor_lang :: solana_program :: pubkey :: Pubkey",
//!                             ),
//!                         ],
//!                     },
//!                 ),
//!             ],
//!         },
//!     ],
//! }
//! ```

use heck::{ToSnakeCase, ToUpperCamelCase};
use quote::ToTokens;
use thiserror::Error;

static ACCOUNT_MOD_PREFIX: &str = "__client_accounts_";

#[derive(Error, Debug)]
pub enum Error {
    #[error("{0:?}")]
    RustParsingError(#[from] syn::Error),
    #[error("missing or invalid program item: '{0}'")]
    MissingOrInvalidProgramItems(&'static str),
}

#[derive(Debug)]
pub struct Idl {
    pub programs: Vec<IdlProgram>,
}

#[derive(Debug)]
pub struct IdlName {
    pub snake_case: String,
    pub upper_camel_case: String,
}

#[derive(Debug)]
pub struct IdlProgram {
    pub name: IdlName,
    pub id: String,
    pub instruction_account_pairs: Vec<(IdlInstruction, IdlAccountGroup)>,
}

#[derive(Debug)]
pub struct IdlInstruction {
    pub name: IdlName,
    pub parameters: Vec<(String, String)>,
}

#[derive(Debug)]
pub struct IdlAccountGroup {
    pub name: IdlName,
    pub accounts: Vec<(String, String)>,
}

pub async fn parse_to_idl_program(name: String, code: &str) -> Result<IdlProgram, Error> {
    let mut static_program_id = None::<syn::ItemStatic>;
    let mut mod_private = None::<syn::ItemMod>;
    let mut mod_instruction = None::<syn::ItemMod>;
    let mut account_mods = Vec::<syn::ItemMod>::new();

    for item in syn::parse_file(code)?.items.into_iter() {
        match item {
            syn::Item::Static(item_static) if item_static.ident == "ID" => {
                static_program_id = Some(item_static);
            }
            syn::Item::Mod(item_mod) => match item_mod.ident.to_string().as_str() {
                "__private" => mod_private = Some(item_mod),
                "instruction" => mod_instruction = Some(item_mod),
                _ => set_account_modules(&mut account_mods, item_mod),
            },
            _ => (),
        }
    }

    let static_program_id =
        static_program_id.ok_or(Error::MissingOrInvalidProgramItems("missing static ID"))?;
    let mod_private =
        mod_private.ok_or(Error::MissingOrInvalidProgramItems("missing mod private"))?;
    let mod_instruction = mod_instruction.ok_or(Error::MissingOrInvalidProgramItems(
        "missing mod instruction",
    ))?;

    // ------ get program id ------

    // input example:
    // ```
    // pub static ID: anchor_lang::solana_program::pubkey::Pubkey =
    //     anchor_lang::solana_program::pubkey::Pubkey::new_from_array([216u8, 55u8,
    //                                                                  200u8, 93u8,
    //                                                                  189u8, 81u8,
    //                                                                  94u8, 109u8,
    //                                                                  14u8, 249u8,
    //                                                                  244u8, 106u8,
    //                                                                  68u8, 214u8,
    //                                                                  222u8, 190u8,
    //                                                                  9u8, 25u8,
    //                                                                  199u8, 75u8,
    //                                                                  79u8, 230u8,
    //                                                                  94u8, 137u8,
    //                                                                  51u8, 187u8,
    //                                                                  193u8, 48u8,
    //                                                                  87u8, 222u8,
    //                                                                  175u8,
    //                                                                  163u8]);
    // ```

    let program_id_bytes = {
        let new_pubkey_call = match *static_program_id.expr {
            syn::Expr::Call(new_pubkey_call) => new_pubkey_call,
            _ => {
                return Err(Error::MissingOrInvalidProgramItems(
                    "static ID: new pubkey call not found",
                ))
            }
        };
        match new_pubkey_call.args.into_iter().next() {
            Some(syn::Expr::Array(pubkey_bytes)) => pubkey_bytes,
            _ => {
                return Err(Error::MissingOrInvalidProgramItems(
                    "static ID: pubkey bytes not found",
                ))
            }
        }
    };

    // ------ get instruction_item_fns ------

    // input example:
    // ```
    // mod __private {
    //     pub mod __global {
    //         use super::*;
    //         #[inline(never)]
    //         pub fn initialize(program_id: &Pubkey, accounts: &[AccountInfo],
    //                           ix_data: &[u8]) -> ProgramResult {
    //             let ix =
    //                 instruction::Initialize::deserialize(&mut &ix_data[..]).map_err(|_|
    //                                                                                     anchor_lang::__private::ErrorCode::InstructionDidNotDeserialize)?;
    //             let instruction::Initialize = ix;
    //             let mut remaining_accounts: &[AccountInfo] = accounts;
    //             let mut accounts =
    //                 Initialize::try_accounts(program_id, &mut remaining_accounts,
    //                                          ix_data)?;
    //             turnstile::initialize(Context::new(program_id, &mut accounts,
    //                                                remaining_accounts))?;
    //             accounts.exit(program_id)
    //         }
    // ```

    let instruction_item_fns = {
        let items = mod_private
            .content
            .map(|(_, items)| items)
            .unwrap_or_default();
        let item_mod_global = items
            .into_iter()
            .find_map(|item| match item {
                syn::Item::Mod(item_mod) if item_mod.ident == "__global" => Some(item_mod),
                _ => None?,
            })
            .ok_or(Error::MissingOrInvalidProgramItems(
                "mod private: mod global not found",
            ))?;
        let items = item_mod_global
            .content
            .map(|(_, items)| items)
            .unwrap_or_default();
        items.into_iter().filter_map(|item| match item {
            syn::Item::Fn(item_fn) => Some(item_fn),
            _ => None,
        })
    };

    // ------ get instruction + account group names ------

    // input example:
    // ```
    //         pub fn initialize(program_id: &Pubkey, accounts: &[AccountInfo],
    //                           ix_data: &[u8]) -> ProgramResult {
    //             let ix =
    //                 instruction::Initialize::deserialize(&mut &ix_data[..]).map_err(|_|
    //                                                                                     anchor_lang::__private::ErrorCode::InstructionDidNotDeserialize)?;
    //             let instruction::Initialize = ix;
    //             let mut remaining_accounts: &[AccountInfo] = accounts;
    //             let mut accounts =
    //                 Initialize::try_accounts(program_id, &mut remaining_accounts,
    //                                          ix_data)?;
    //             turnstile::initialize(Context::new(program_id, &mut accounts,
    //                                                remaining_accounts))?;
    //             accounts.exit(program_id)
    //         }
    // ```

    let mut instruction_account_pairs = Vec::new();
    instruction_item_fns
        .into_iter()
        .map(|item_fn| {
            // stmt example: `let mut accounts = UpdateState::try_accounts(program_id, &mut remaining_accounts, ix_data)?;`
            let account_group_name = item_fn.block.stmts.into_iter().find_map(|stmt| {
            let local = if let syn::Stmt::Local(local) = stmt {
                local
            } else {
                None?
            };
            if !matches!(&local.pat, syn::Pat::Ident(pat_ident) if pat_ident.ident == "accounts") {
                None?
            }
            let init_expr = *local.init?.1;
            let expr_try_expr = match init_expr {
                syn::Expr::Try(expr_try) => *expr_try.expr,
                _ => None?
            };
            let expr_call_func = match expr_try_expr {
                syn::Expr::Call(expr_call) => *expr_call.func,
                _ => None?
            };
            let account_group_name = match expr_call_func {
                syn::Expr::Path(expr_path) => expr_path.path.segments.into_iter().next()?.ident,
                _ => None?
            };
            Some(account_group_name.to_string())
        })?;

            let instruction_name = item_fn.sig.ident.to_string();
            let idl_instruction = IdlInstruction {
                name: IdlName {
                    upper_camel_case: instruction_name.to_upper_camel_case(),
                    snake_case: instruction_name,
                },
                parameters: Vec::new(),
            };
            let idl_account = IdlAccountGroup {
                name: IdlName {
                    snake_case: account_group_name.to_snake_case(),
                    upper_camel_case: account_group_name,
                },
                accounts: Vec::new(),
            };
            Some((idl_instruction, idl_account))
        })
        .try_for_each(|pair| {
            if let Some(pair) = pair {
                instruction_account_pairs.push(pair);
                Ok(())
            } else {
                Err(Error::MissingOrInvalidProgramItems(
                    "statement with `accounts` not found",
                ))
            }
        })?;

    // ------ get instruction parameters ------

    // input example:
    // ```
    // pub mod instruction {
    //     use super::*;
    //     pub mod state {
    //         use super::*;
    //     }
    // // **
    //     pub struct Initialize;
    // // **
    //     pub struct Coin {
    //         pub dummy_arg: String,
    //     }
    // ```

    let mut instruction_mod_items = mod_instruction
        .content
        .ok_or(Error::MissingOrInvalidProgramItems(
            "instruction mod: empty content",
        ))?
        .1
        .into_iter();

    for (idl_instruction, _) in &mut instruction_account_pairs {
        let instruction_struct_name = &idl_instruction.name.upper_camel_case;

        let instruction_item_struct_fields = instruction_mod_items
            .find_map(|item| {
                let instruction_item_struct = match item {
                    syn::Item::Struct(item_struct)
                        if item_struct.ident == instruction_struct_name =>
                    {
                        item_struct
                    }
                    _ => None?,
                };
                let fields = match instruction_item_struct.fields {
                    syn::Fields::Named(fields_named) => fields_named.named,
                    syn::Fields::Unit => syn::punctuated::Punctuated::new(),
                    syn::Fields::Unnamed(_) => None?,
                };
                Some(fields.into_iter())
            })
            .ok_or(Error::MissingOrInvalidProgramItems("instruction struct"))?;

        idl_instruction.parameters = instruction_item_struct_fields
            .map(|field| {
                let parameter_name = field.ident.unwrap().to_string();
                let parameter_id_type = field.ty.into_token_stream().to_string();
                (parameter_name, parameter_id_type)
            })
            .collect();
    }

    // ------ get accounts ------

    // input example:
    // ```
    // pub(crate) mod __client_accounts_initialize {
    //     use super::*;
    //     use anchor_lang::prelude::borsh;
    //     pub struct Initialize {
    //         pub state: anchor_lang::solana_program::pubkey::Pubkey,
    //         pub user: anchor_lang::solana_program::pubkey::Pubkey,
    //         pub system_program: anchor_lang::solana_program::pubkey::Pubkey,
    //     }
    // ```

    for account_mod_item in account_mods {
        let account_struct_name = account_mod_item
            .ident
            .to_string()
            .strip_prefix(ACCOUNT_MOD_PREFIX)
            .unwrap()
            .to_upper_camel_case();

        let account_item_struct = account_mod_item
            .content
            .ok_or(Error::MissingOrInvalidProgramItems(
                "account mod: empty content",
            ))?
            .1
            .into_iter()
            .find_map(|item| match item {
                syn::Item::Struct(item_struct) if item_struct.ident == account_struct_name => {
                    Some(item_struct)
                }
                _ => None?,
            })
            .ok_or(Error::MissingOrInvalidProgramItems(
                "account mod: struct not found",
            ))?;

        let account_item_struct_fields = match account_item_struct.fields {
            syn::Fields::Named(fields_named) => fields_named.named,
            syn::Fields::Unit => syn::punctuated::Punctuated::new(),
            syn::Fields::Unnamed(_) => {
                return Err(Error::MissingOrInvalidProgramItems(
                    "account struct: unnamed fields not allowed",
                ))
            }
        };

        let accounts = account_item_struct_fields
            .into_iter()
            .map(|field| {
                let account_name = field.ident.unwrap().to_string();
                let account_id_type = field.ty.into_token_stream().to_string();
                (account_name, account_id_type)
            })
            .collect::<Vec<_>>();

        for (_, idl_account_group) in &mut instruction_account_pairs {
            if idl_account_group.name.upper_camel_case == account_struct_name {
                idl_account_group.accounts = accounts.clone();
            }
        }
    }

    // ------ // ------

    Ok(IdlProgram {
        name: IdlName {
            upper_camel_case: name.to_upper_camel_case(),
            snake_case: name,
        },
        id: program_id_bytes.into_token_stream().to_string(),
        instruction_account_pairs,
    })
}

fn set_account_modules(account_modules: &mut Vec<syn::ItemMod>, item_module: syn::ItemMod) {
    if item_module
        .ident
        .to_string()
        .starts_with(ACCOUNT_MOD_PREFIX)
    {
        account_modules.push(item_module);
        return;
    }
    let modules = item_module
        .content
        .ok_or(Error::MissingOrInvalidProgramItems(
            "account mod: empty content",
        ))
        .unwrap()
        .1;
    for module in modules {
        if let syn::Item::Mod(nested_module) = module {
            set_account_modules(account_modules, nested_module);
        }
    }
}