solores 0.7.0

Solana IDL to Rust client / CPI interface generator
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
use heck::{ToPascalCase, ToShoutySnakeCase, ToSnakeCase};
use itertools::Itertools;
use proc_macro2::{Ident, Span, TokenStream};
use quote::{format_ident, quote, ToTokens};
use serde::Deserialize;
use syn::{LitBool, LitInt};

use crate::{
    idl_format::shank::typedefs::TypedefField,
    utils::{unique_by_report_dups, UniqueByReportDupsResult},
};

#[derive(Deserialize)]
pub struct NamedInstruction {
    pub name: String,
    pub accounts: Option<Vec<IxAccount>>,
    pub args: Option<Vec<TypedefField>>,
    pub discriminant: Discriminant,
}

impl NamedInstruction {
    pub fn ix_args_ident(&self) -> Ident {
        format_ident!("{}IxArgs", self.name.to_pascal_case())
    }

    pub fn ix_data_ident(&self) -> Ident {
        format_ident!("{}IxData", self.name.to_pascal_case())
    }

    pub fn ix_fn_ident(&self) -> Ident {
        format_ident!("{}_ix", self.name.to_snake_case())
    }

    pub fn ix_fn_with_program_id_ident(&self) -> Ident {
        format_ident!("{}_ix_with_program_id", self.name.to_snake_case())
    }

    pub fn discm_ident(&self) -> Ident {
        format_ident!("{}_IX_DISCM", &self.name.to_shouty_snake_case())
    }

    pub fn accounts_ident(&self) -> Ident {
        format_ident!("{}Accounts", self.name.to_pascal_case())
    }

    pub fn keys_ident(&self) -> Ident {
        format_ident!("{}Keys", self.name.to_pascal_case())
    }

    pub fn accounts_len_ident(&self) -> Ident {
        format_ident!("{}_IX_ACCOUNTS_LEN", self.name.to_shouty_snake_case())
    }

    pub fn has_ix_args(&self) -> bool {
        let args = match &self.args {
            Some(a) => a,
            None => return false,
        };
        !args.is_empty()
    }

    pub fn has_accounts(&self) -> bool {
        let accounts = match &self.accounts {
            Some(a) => a,
            None => return false,
        };
        !accounts.is_empty()
    }

    pub fn args_has_defined_type(&self) -> bool {
        let args = if !self.has_ix_args() {
            return false;
        } else {
            self.args.as_ref().unwrap()
        };
        args.iter().map(|a| a.r#type.is_or_has_defined()).any(|b| b)
    }

    pub fn args_has_pubkeys(&self) -> bool {
        let args = if !self.has_ix_args() {
            return false;
        } else {
            self.args.as_ref().unwrap()
        };
        args.iter().map(|a| a.r#type.is_or_has_pubkey()).any(|b| b)
    }

    pub fn has_privileged_accounts(&self) -> bool {
        let accounts = if !self.has_accounts() {
            return false;
        } else {
            self.accounts.as_ref().unwrap()
        };
        accounts.iter().map(|a| a.is_privileged()).any(|b| b)
    }

    /// export accounts_len as const
    pub fn write_accounts_len(&self, tokens: &mut TokenStream, accounts_len: usize) {
        if !self.has_accounts() {
            return;
        }
        let accounts_len_ident = self.accounts_len_ident();
        let n_accounts_lit = LitInt::new(&accounts_len.to_string(), Span::call_site());
        tokens.extend(quote! {
            pub const #accounts_len_ident: usize = #n_accounts_lit;
        });
    }

    pub fn write_accounts_struct(&self, tokens: &mut TokenStream, accounts: &[IxAccount]) {
        if !self.has_accounts() {
            return;
        }
        let accounts_ident = self.accounts_ident();
        let accounts_fields = accounts.iter().map(|acc| {
            let account_name = format_ident!("{}", &acc.name.to_snake_case());
            let maybe_doc_comment = acc.desc.as_ref().map_or(quote! {}, |desc| {
                quote! {
                    #[doc = #desc]
                }
            });
            quote! {
                #maybe_doc_comment
                pub #account_name: &'me AccountInfo<'info>
            }
        });
        tokens.extend(quote! {
            #[derive(Copy, Clone, Debug)]
            pub struct #accounts_ident<'me, 'info> {
                #(#accounts_fields),*
            }
        });
    }

    pub fn write_keys_struct(&self, tokens: &mut TokenStream, accounts: &[IxAccount]) {
        if !self.has_accounts() {
            return;
        }
        let keys_ident = self.keys_ident();
        let keys_fields = accounts.iter().map(|acc| {
            let account_ident = format_ident!("{}", &acc.name.to_snake_case());
            let maybe_doc_comment = acc.desc.as_ref().map_or(quote! {}, |desc| {
                quote! {
                    #[doc = #desc]
                }
            });
            quote! {
                #maybe_doc_comment
                pub #account_ident: Pubkey
            }
        });
        tokens.extend(quote! {
            #[derive(Copy, Clone, Debug)]
            pub struct #keys_ident {
                #(#keys_fields),*
            }
        });
    }

    /// From<XAccounts> for XKeys
    pub fn write_from_accounts_for_keys(&self, tokens: &mut TokenStream, accounts: &[IxAccount]) {
        if !self.has_accounts() {
            return;
        }
        let accounts_ident = self.accounts_ident();
        let keys_ident = self.keys_ident();
        let from_keys_fields = accounts.iter().map(|acc| {
            let account_ident = format_ident!("{}", &acc.name.to_snake_case());
            quote! {
                #account_ident: *accounts.#account_ident.key
            }
        });
        tokens.extend(quote! {
            impl From<#accounts_ident<'_, '_>> for #keys_ident {
                fn from(accounts: #accounts_ident) -> Self {
                    Self {
                        #(#from_keys_fields),*
                    }
                }
            }
        });
    }

    /// From <&XKeys> for [AccountMeta]
    pub fn write_from_keys_for_meta_arr(&self, tokens: &mut TokenStream, accounts: &[IxAccount]) {
        if !self.has_accounts() {
            return;
        }
        let keys_ident = self.keys_ident();
        let accounts_len_ident = self.accounts_len_ident();
        let from_keys_meta = accounts.iter().map(|acc| acc.to_keys_account_meta_tokens());
        tokens.extend(quote! {
            impl From<#keys_ident> for [AccountMeta; #accounts_len_ident] {
                fn from(keys: #keys_ident) -> Self {
                    [
                        #(#from_keys_meta),*
                    ]
                }
            }
        });
    }

    /// From <[Pubkey]> for XKeys
    pub fn write_from_pubkey_arr_for_keys(&self, tokens: &mut TokenStream, accounts: &[IxAccount]) {
        if !self.has_accounts() {
            return;
        }
        let accounts_len_ident = self.accounts_len_ident();
        let keys_ident = self.keys_ident();
        let from_pubkey_arr_fields = accounts.iter().enumerate().map(|(i, acc)| {
            let account_ident = format_ident!("{}", &acc.name.to_snake_case());
            let index_lit = LitInt::new(&i.to_string(), Span::call_site());
            quote! {
                #account_ident: pubkeys[#index_lit]
            }
        });
        tokens.extend(quote! {
            impl From<[Pubkey; #accounts_len_ident]> for #keys_ident {
                fn from(pubkeys: [Pubkey; #accounts_len_ident]) -> Self {
                    Self {
                        #(#from_pubkey_arr_fields),*
                    }
                }
            }
        });
    }

    /// From <XAccounts> for [AccountInfo]
    pub fn write_from_accounts_for_account_info_arr(
        &self,
        tokens: &mut TokenStream,
        accounts: &[IxAccount],
    ) {
        if !self.has_accounts() {
            return;
        }
        let accounts_ident = self.accounts_ident();
        let accounts_len_ident = self.accounts_len_ident();
        let account_info_clone = accounts.iter().map(|acc| {
            let account_ident = format_ident!("{}", &acc.name.to_snake_case());
            quote! {
               accounts.#account_ident.clone()
            }
        });
        tokens.extend(quote! {
            impl<'info> From<#accounts_ident<'_, 'info>> for [AccountInfo<'info>; #accounts_len_ident] {
                fn from(accounts: #accounts_ident<'_, 'info>) -> Self {
                    [
                        #(#account_info_clone),*
                    ]
                }
            }
        });
    }

    /// From <&[AccountInfo]> for XAccounts
    pub fn write_from_account_info_arr_for_accounts(
        &self,
        tokens: &mut TokenStream,
        accounts: &[IxAccount],
    ) {
        if !self.has_accounts() {
            return;
        }
        let accounts_len_ident = self.accounts_len_ident();
        let accounts_ident = self.accounts_ident();
        let from_account_info_fields = accounts.iter().enumerate().map(|(i, acc)| {
            let account_ident = format_ident!("{}", &acc.name.to_snake_case());
            let index_lit = LitInt::new(&i.to_string(), Span::call_site());
            quote! {
               #account_ident: &arr[#index_lit]
            }
        });
        tokens.extend(quote! {
            impl<'me, 'info> From<&'me [AccountInfo<'info>; #accounts_len_ident]> for #accounts_ident<'me, 'info> {
                fn from(arr: &'me [AccountInfo<'info>; #accounts_len_ident]) -> Self {
                    Self {
                        #(#from_account_info_fields),*
                    }
                }
            }
        });
    }

    pub fn write_ix_args_struct(&self, tokens: &mut TokenStream) {
        let args = if !self.has_ix_args() {
            return;
        } else {
            self.args.as_ref().unwrap()
        };
        let ix_args_ident = self.ix_args_ident();
        let args_fields = args.iter().map(|a| quote! { pub #a });
        tokens.extend(quote! {
            #[derive(BorshDeserialize, BorshSerialize, Clone, Debug, PartialEq)]
            #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
            pub struct #ix_args_ident {
                #(#args_fields),*
            }
        });
    }

    pub fn write_discm(&self, tokens: &mut TokenStream) {
        let discm_ident = self.discm_ident();
        let discm_value = self.discriminant.value;
        tokens.extend(quote! {
            pub const #discm_ident: u8 = #discm_value;
        })
    }
    pub fn write_ix_data_struct(&self, tokens: &mut TokenStream) {
        let ix_data_ident = self.ix_data_ident();
        let struct_decl = if self.has_ix_args() {
            let ix_args_ident = self.ix_args_ident();
            quote! { pub struct #ix_data_ident(pub #ix_args_ident); }
        } else {
            quote! { pub struct #ix_data_ident; }
        };
        tokens.extend(quote! {
            #[derive(Clone, Debug, PartialEq)]
            #struct_decl
        });
    }

    pub fn write_from_ix_args_for_ix_data(&self, tokens: &mut TokenStream) {
        if !self.has_ix_args() {
            return;
        }
        let ix_data_ident = self.ix_data_ident();
        let ix_args_ident = self.ix_args_ident();
        tokens.extend(quote! {
            impl From<#ix_args_ident> for #ix_data_ident {
                fn from(args: #ix_args_ident) -> Self {
                    Self(args)
                }
            }
        });
    }

    pub fn write_ix_data_impl(&self, tokens: &mut TokenStream) {
        let discm_ident = self.discm_ident();
        let ix_data_ident = self.ix_data_ident();
        let mut deserialize_body = quote! {
            let mut reader = buf;
            let mut maybe_discm_buf = [0u8; 1];
            reader.read_exact(&mut maybe_discm_buf)?;
            let maybe_discm = maybe_discm_buf[0];
            if maybe_discm != #discm_ident {
                return Err(
                    std::io::Error::new(
                        std::io::ErrorKind::Other, format!("discm does not match. Expected: {:?}. Received: {:?}", #discm_ident, maybe_discm)
                    )
                );
            }
        };
        if self.has_ix_args() {
            let ix_args_ident = self.ix_args_ident();
            deserialize_body.extend(quote! {
                Ok(Self(#ix_args_ident::deserialize(&mut reader)?))
            })
        } else {
            deserialize_body.extend(quote! {
                Ok(Self)
            })
        }
        let serialize_body = if self.has_ix_args() {
            quote! {
                writer.write_all(&[#discm_ident])?;
                self.0.serialize(&mut writer)
            }
        } else {
            quote! {
                writer.write_all(&[#discm_ident])
            }
        };
        tokens.extend(quote! {
            impl #ix_data_ident {
                pub fn deserialize(buf: &[u8]) -> std::io::Result<Self> {
                    #deserialize_body
                }

                pub fn serialize<W: std::io::Write>(&self, mut writer: W) -> std::io::Result<()> {
                    #serialize_body
                }

                pub fn try_to_vec(&self) -> std::io::Result<Vec<u8>> {
                    let mut data = Vec::new();
                    self.serialize(&mut data)?;
                    Ok(data)
                }
            }
        });
    }

    /// _ix()
    /// _ix_with_program_id()
    pub fn write_ix_fn(&self, tokens: &mut TokenStream) {
        let ix_fn_ident = self.ix_fn_ident();
        let ix_with_program_id_fn_ident = self.ix_fn_with_program_id_ident();
        let keys_ident = self.keys_ident();
        let ix_args_ident = self.ix_args_ident();
        let accounts_len_ident = self.accounts_len_ident();
        let ix_data_ident = self.ix_data_ident();

        let mut fn_params = quote! {};
        let mut fn_args = quote! {};
        if self.has_accounts() {
            fn_params.extend(quote! { keys: #keys_ident, });
            fn_args.extend(quote! { keys, });
        }
        if self.has_ix_args() {
            fn_params.extend(quote! { args: #ix_args_ident, });
            fn_args.extend(quote! { args, });
        }

        let (mut fn_body, accounts_expr) = if self.has_accounts() {
            (
                quote! {
                    let metas: [AccountMeta; #accounts_len_ident] = keys.into();
                },
                quote! {
                    Vec::from(metas)
                },
            )
        } else {
            (
                quote! {},
                quote! {
                    Vec::new()
                },
            )
        };
        if self.has_ix_args() {
            fn_body.extend(quote! {
                let data: #ix_data_ident = args.into();
            })
        }
        let data_expr = if self.has_ix_args() {
            quote! { data.try_to_vec()? }
        } else {
            quote! { #ix_data_ident.try_to_vec()? }
        };

        tokens.extend(quote! {
            pub fn #ix_with_program_id_fn_ident(program_id: Pubkey, #fn_params) -> std::io::Result<Instruction> {
                #fn_body
                Ok(Instruction {
                    program_id,
                    accounts: #accounts_expr,
                    data: #data_expr,
                })
            }

            pub fn #ix_fn_ident(#fn_params) -> std::io::Result<Instruction> {
                #ix_with_program_id_fn_ident(crate::ID, #fn_args)
            }
        });
    }

    fn invoke_fn_params_prefix(&self) -> TokenStream {
        let accounts_ident = self.accounts_ident();
        let ix_args_ident = self.ix_args_ident();
        let mut fn_params = quote! {};
        if self.has_accounts() {
            fn_params.extend(quote! { accounts: #accounts_ident<'_, '_>, });
        }
        if self.has_ix_args() {
            fn_params.extend(quote! { args: #ix_args_ident, })
        }
        fn_params
    }

    fn invoke_fn_args_prefix(&self) -> TokenStream {
        let mut fn_args = quote! {};
        if self.has_accounts() {
            fn_args.extend(quote! { accounts, });
        }
        if self.has_ix_args() {
            fn_args.extend(quote! { args, })
        }
        fn_args
    }

    fn ix_call_assign(&self) -> TokenStream {
        let ix_with_program_id_fn_ident = self.ix_fn_with_program_id_ident();
        let keys_ident = self.keys_ident();
        let mut res = quote! {};
        let mut args = quote! {};
        if self.has_accounts() {
            res.extend(quote! {
                let keys: #keys_ident = accounts.into();
            });
            args.extend(quote! { keys, });
        }
        if self.has_ix_args() {
            args.extend(quote! { args });
        }
        res.extend(quote! {
            let ix = #ix_with_program_id_fn_ident(program_id, #args)?;
        });
        res
    }

    /// _invoke()
    /// _invoke_with_program_id()
    pub fn write_invoke_fn(&self, tokens: &mut TokenStream) {
        let invoke_fn_ident = format_ident!("{}_invoke", self.name.to_snake_case());
        let invoke_with_program_id_fn_ident =
            format_ident!("{}_invoke_with_program_id", self.name.to_snake_case());
        let fn_params = self.invoke_fn_params_prefix();
        let fn_args = self.invoke_fn_args_prefix();
        let call_assign = self.ix_call_assign();
        let invoke = if self.has_accounts() {
            quote! {
                invoke_instruction(&ix, accounts)
            }
        } else {
            quote! {
                invoke(&ix, &[])
            }
        };
        tokens.extend(quote! {
            pub fn #invoke_with_program_id_fn_ident(program_id: Pubkey, #fn_params) -> ProgramResult {
                #call_assign
                #invoke
            }

            pub fn #invoke_fn_ident(#fn_params) -> ProgramResult {
                #invoke_with_program_id_fn_ident(crate::ID, #fn_args)
            }
        });
    }

    /// _invoke_signed()
    /// _invoke_signed_with_program_id()
    pub fn write_invoke_signed_fn(&self, tokens: &mut TokenStream) {
        let invoke_signed_fn_ident = format_ident!("{}_invoke_signed", self.name.to_snake_case());
        let invoke_signed_with_program_id_fn_ident = format_ident!(
            "{}_invoke_signed_with_program_id",
            self.name.to_snake_case()
        );
        let mut fn_params = self.invoke_fn_params_prefix();
        fn_params.extend(quote! { seeds: &[&[&[u8]]], });
        let mut fn_args = self.invoke_fn_args_prefix();
        fn_args.extend(quote! { seeds, });
        let call_assign = self.ix_call_assign();
        let invoke = if self.has_accounts() {
            quote! {
                invoke_instruction_signed(&ix, accounts, seeds)
            }
        } else {
            quote! {
                invoke_signed(&ix, &[], seeds)
            }
        };
        tokens.extend(quote! {
            pub fn #invoke_signed_with_program_id_fn_ident(program_id: Pubkey, #fn_params) -> ProgramResult {
                #call_assign
                #invoke
            }

            pub fn #invoke_signed_fn_ident(#fn_params) -> ProgramResult {
                #invoke_signed_with_program_id_fn_ident(crate::ID, #fn_args)
            }
        });
    }

    /// _verify_account_keys()
    pub fn write_verify_account_keys_fn(&self, tokens: &mut TokenStream, accounts: &[IxAccount]) {
        if !self.has_accounts() {
            return;
        }
        let verify_account_keys_fn_ident =
            format_ident!("{}_verify_account_keys", self.name.to_snake_case());
        let accounts_ident = self.accounts_ident();
        let keys_ident = self.keys_ident();
        let key_tups = accounts.iter().map(IxAccount::to_verify_account_keys_tuple);
        // edge-case of accounts and keys being empty
        let pubkeys_loop_check = if accounts.is_empty() {
            quote! {}
        } else {
            quote! {
                for (actual, expected) in [
                    #(#key_tups),*
                ] {
                    if actual != expected {
                        return Err((*actual, *expected));
                    }
                }
            }
        };
        tokens.extend(quote! {
            pub fn #verify_account_keys_fn_ident(
                accounts: #accounts_ident<'_, '_>,
                keys: #keys_ident
            ) -> Result<(), (Pubkey, Pubkey)> {
                #pubkeys_loop_check
                Ok(())
            }
        });
    }

    // _verify_account_privileges()
    // _verify_writable_privileges()
    // _verify_signer_privileges()
    pub fn write_verify_account_privileges_fns(
        &self,
        tokens: &mut TokenStream,
        accounts: &[IxAccount],
    ) {
        if !self.has_privileged_accounts() {
            return;
        }
        let verify_account_privileges_fn_ident =
            format_ident!("{}_verify_account_privileges", self.name.to_snake_case());
        let verify_writable_privileges_fn_ident =
            format_ident!("{}_verify_writable_privileges", self.name.to_snake_case());
        let verify_signer_privileges_fn_ident =
            format_ident!("{}_verify_signer_privileges", self.name.to_snake_case());
        let accounts_ident = self.accounts_ident();

        let mut verify_fn_body = quote! {};

        let mut writables = accounts
            .iter()
            .filter_map(|a| {
                if a.is_mut {
                    let name = a.field_ident();
                    Some(quote! {
                        accounts.#name
                    })
                } else {
                    None
                }
            })
            .peekable();
        let has_writables = writables.peek().is_some();
        if has_writables {
            tokens.extend(quote! {
                pub fn #verify_writable_privileges_fn_ident<'me, 'info>(
                    accounts: #accounts_ident<'me, 'info>,
                ) -> Result<(), (&'me AccountInfo<'info>, ProgramError)> {
                    for should_be_writable in [
                        #(#writables),*
                    ] {
                        if !should_be_writable.is_writable {
                            return Err((should_be_writable, ProgramError::InvalidAccountData));
                        }
                    }
                    Ok(())
                }
            });
            verify_fn_body.extend(quote! {
                #verify_writable_privileges_fn_ident(accounts)?;
            });
        }

        let mut signers = accounts
            .iter()
            .filter_map(|a| {
                if a.is_signer {
                    let name = a.field_ident();
                    Some(quote! {
                        accounts.#name
                    })
                } else {
                    None
                }
            })
            .peekable();
        let has_signers = signers.peek().is_some();
        if has_signers {
            tokens.extend(quote! {
                pub fn #verify_signer_privileges_fn_ident<'me, 'info>(
                    accounts: #accounts_ident<'me, 'info>,
                ) -> Result<(), (&'me AccountInfo<'info>, ProgramError)> {
                    for should_be_signer in [
                        #(#signers),*
                    ] {
                        if !should_be_signer.is_signer {
                            return Err((should_be_signer, ProgramError::MissingRequiredSignature));
                        }
                    }
                    Ok(())
                }
            });
            verify_fn_body.extend(quote! {
                #verify_signer_privileges_fn_ident(accounts)?;
            });
        }

        tokens.extend(quote! {
            pub fn #verify_account_privileges_fn_ident<'me, 'info>(
                accounts: #accounts_ident<'me, 'info>,
            ) -> Result<(), (&'me AccountInfo<'info>, ProgramError)> {
                #verify_fn_body
                Ok(())
            }
        });
    }
}

impl ToTokens for NamedInstruction {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let accounts: &[IxAccount] = self.accounts.as_ref().map_or(&[], |v| v.as_slice());
        let n_accounts = accounts.len();

        let UniqueByReportDupsResult { duplicates, .. } =
            unique_by_report_dups(accounts.iter(), |acc| acc.name.clone());

        if !duplicates.is_empty() {
            log::error!(
                "Found duplicate accounts for instruction {}: {}",
                &self.name,
                duplicates.iter().map(|acc| &acc.name).format(", ")
            );
            panic!();
        }

        self.write_accounts_len(tokens, n_accounts);
        self.write_accounts_struct(tokens, accounts);
        self.write_keys_struct(tokens, accounts);
        self.write_from_accounts_for_keys(tokens, accounts);
        self.write_from_keys_for_meta_arr(tokens, accounts);
        self.write_from_pubkey_arr_for_keys(tokens, accounts);
        self.write_from_accounts_for_account_info_arr(tokens, accounts);
        self.write_from_account_info_arr_for_accounts(tokens, accounts);

        self.write_discm(tokens);
        self.write_ix_args_struct(tokens);
        self.write_ix_data_struct(tokens);
        self.write_from_ix_args_for_ix_data(tokens);
        self.write_ix_data_impl(tokens);

        self.write_ix_fn(tokens);
        self.write_invoke_fn(tokens);
        self.write_invoke_signed_fn(tokens);

        self.write_verify_account_keys_fn(tokens, accounts);
        self.write_verify_account_privileges_fns(tokens, accounts);
    }
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IxAccount {
    pub name: String,
    pub is_mut: bool,
    pub is_signer: bool,
    pub desc: Option<String>,
}

impl IxAccount {
    pub fn field_ident(&self) -> Ident {
        format_ident!("{}", self.name.to_snake_case())
    }

    pub fn is_privileged(&self) -> bool {
        self.is_mut || self.is_signer
    }

    pub fn to_keys_account_meta_tokens(&self) -> TokenStream {
        let is_writable_arg = LitBool::new(self.is_mut, Span::call_site());
        let is_signer_arg = LitBool::new(self.is_signer, Span::call_site());
        let name = self.field_ident();
        quote! {
            AccountMeta {
                pubkey: keys.#name,
                is_signer: #is_signer_arg,
                is_writable: #is_writable_arg,
            }
        }
    }

    pub fn to_verify_account_keys_tuple(&self) -> TokenStream {
        let name = self.field_ident();
        quote! {
            (accounts.#name.key, &keys.#name)
        }
    }
}

#[derive(Deserialize)]
pub struct Discriminant {
    pub r#type: String,
    pub value: u8,
}