-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathlib.rs
More file actions
5252 lines (4784 loc) · 176 KB
/
lib.rs
File metadata and controls
5252 lines (4784 loc) · 176 KB
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::config::{
get_default_ledger_path, BootstrapMode, BuildConfig, Config, ConfigOverride, HookType,
Manifest, PackageManager, ProgramDeployment, ProgramWorkspace, ScriptsConfig,
SurfnetInfoResponse, SurfpoolConfig, TestValidator, ValidatorType, WithPath, SHUTDOWN_WAIT,
STARTUP_WAIT, SURFPOOL_HOST,
};
use anchor_client::Cluster;
use anchor_lang::prelude::UpgradeableLoaderState;
use anchor_lang::solana_program::bpf_loader_upgradeable;
use anchor_lang::AnchorDeserialize;
use anchor_lang_idl::convert::convert_idl;
use anchor_lang_idl::types::{Idl, IdlArrayLen, IdlDefinedFields, IdlType, IdlTypeDefTy};
use anyhow::{anyhow, bail, Context, Result};
use checks::{check_anchor_version, check_deps, check_idl_build_feature, check_overflow};
use clap::{CommandFactory, Parser};
use dirs::home_dir;
use heck::{ToKebabCase, ToLowerCamelCase, ToPascalCase, ToSnakeCase};
use regex::{Regex, RegexBuilder};
use rust_template::{ProgramTemplate, TestTemplate};
use semver::{Version, VersionReq};
use serde::Deserialize;
use serde_json::{json, Map, Value as JsonValue};
use solana_cli_config::Config as SolanaCliConfig;
use solana_commitment_config::CommitmentConfig;
use solana_compute_budget_interface::ComputeBudgetInstruction;
use solana_instruction::Instruction;
use solana_keypair::Keypair;
use solana_pubkey::Pubkey;
use solana_pubsub_client::pubsub_client::{PubsubClient, PubsubClientSubscription};
use solana_rpc_client::rpc_client::RpcClient;
use solana_rpc_client_api::config::{RpcTransactionLogsConfig, RpcTransactionLogsFilter};
use solana_rpc_client_api::request::RpcRequest;
use solana_rpc_client_api::response::{Response as RpcResponse, RpcLogsResponse};
use solana_signer::{EncodableKey, Signer};
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::ffi::OsString;
use std::fs::{self, File};
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::process::{Child, Stdio};
use std::string::ToString;
use std::sync::LazyLock;
mod account;
mod checks;
pub mod config;
mod keygen;
mod metadata;
mod program;
pub mod rust_template;
// Version of the docker image.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const DOCKER_BUILDER_VERSION: &str = VERSION;
/// Default RPC port
pub const DEFAULT_RPC_PORT: u16 = 8899;
/// WebSocket port offset for solana-test-validator (RPC port + 1)
pub const WEBSOCKET_PORT_OFFSET: u16 = 1;
pub static AVM_HOME: LazyLock<PathBuf> = LazyLock::new(|| {
if let Ok(avm_home) = std::env::var("AVM_HOME") {
PathBuf::from(avm_home)
} else {
let mut user_home = dirs::home_dir().expect("Could not find home directory");
user_home.push(".avm");
user_home
}
});
#[derive(Debug, Parser)]
#[clap(version = VERSION)]
pub struct Opts {
#[clap(flatten)]
pub cfg_override: ConfigOverride,
#[clap(subcommand)]
pub command: Command,
}
#[derive(Debug, Parser)]
pub enum Command {
/// Initializes a workspace.
Init {
/// Workspace name
name: String,
/// Use JavaScript instead of TypeScript
#[clap(short, long)]
javascript: bool,
/// Don't install JavaScript dependencies
#[clap(long)]
no_install: bool,
/// Package Manager to use
#[clap(value_enum, long, default_value = "yarn")]
package_manager: PackageManager,
/// Don't initialize git
#[clap(long)]
no_git: bool,
/// Rust program template to use
#[clap(value_enum, short, long, default_value = "multiple")]
template: ProgramTemplate,
/// Test template to use
#[clap(value_enum, long, default_value = "mocha")]
test_template: TestTemplate,
/// Initialize even if there are files
#[clap(long, action)]
force: bool,
},
/// Builds the workspace.
#[clap(name = "build", alias = "b")]
Build {
/// True if the build should not fail even if there are no "CHECK" comments
#[clap(long)]
skip_lint: bool,
/// Skip checking for program ID mismatch between keypair and declare_id
#[clap(long)]
ignore_keys: bool,
/// Do not build the IDL
#[clap(long)]
no_idl: bool,
/// Output directory for the IDL.
#[clap(short, long)]
idl: Option<String>,
/// Output directory for the TypeScript IDL.
#[clap(short = 't', long)]
idl_ts: Option<String>,
/// True if the build artifact needs to be deterministic and verifiable.
#[clap(short, long)]
verifiable: bool,
/// Name of the program to build
#[clap(short, long)]
program_name: Option<String>,
/// Version of the Solana toolchain to use. For --verifiable builds
/// only.
#[clap(short, long)]
solana_version: Option<String>,
/// Docker image to use. For --verifiable builds only.
#[clap(short, long)]
docker_image: Option<String>,
/// Bootstrap docker image from scratch, installing all requirements for
/// verifiable builds. Only works for debian-based images.
#[clap(value_enum, short, long, default_value = "none")]
bootstrap: BootstrapMode,
/// Environment variables to pass into the docker container
#[clap(short, long, required = false)]
env: Vec<String>,
/// Arguments to pass to the underlying `cargo build-sbf` command
#[clap(required = false, last = true)]
cargo_args: Vec<String>,
/// Suppress doc strings in IDL output
#[clap(long)]
no_docs: bool,
},
/// Expands macros (wrapper around cargo expand)
///
/// Use it in a program folder to expand program
///
/// Use it in a workspace but outside a program
/// folder to expand the entire workspace
Expand {
/// Expand only this program
#[clap(short, long)]
program_name: Option<String>,
/// Arguments to pass to the underlying `cargo expand` command
#[clap(required = false, last = true)]
cargo_args: Vec<String>,
},
/// Verifies the on-chain bytecode matches the locally compiled artifact.
/// Run this command inside a program subdirectory, i.e., in the dir
/// containing the program's Cargo.toml.
Verify {
/// The program ID to verify.
program_id: Pubkey,
/// The URL of the repository to verify against. Conflicts with `--current-dir`.
#[clap(long, conflicts_with = "current_dir")]
repo_url: Option<String>,
/// The commit hash to verify against. Requires `--repo-url`.
#[clap(long, requires = "repo_url")]
commit_hash: Option<String>,
/// Verify against the source code in the current directory. Conflicts with `--repo-url`.
#[clap(long)]
current_dir: bool,
/// Name of the program to run the command on. Defaults to the package name.
#[clap(long)]
program_name: Option<String>,
/// Any additional arguments to pass to `solana-verify`.
#[clap(raw = true)]
args: Vec<String>,
},
#[clap(name = "test", alias = "t")]
/// Runs integration tests.
Test {
/// Build and test only this program
#[clap(short, long)]
program_name: Option<String>,
/// Use this flag if you want to run tests against previously deployed
/// programs.
#[clap(long)]
skip_deploy: bool,
/// True if the build should not fail even if there are
/// no "CHECK" comments where normally required
#[clap(long)]
skip_lint: bool,
/// Flag to skip starting a local validator, if the configured cluster
/// url is a localnet.
#[clap(long)]
skip_local_validator: bool,
/// Flag to skip building the program in the workspace,
/// use this to save time when running test and the program code is not altered.
#[clap(long)]
skip_build: bool,
/// Do not build the IDL
#[clap(long)]
no_idl: bool,
/// Flag to keep the local validator running after tests
/// to be able to check the transactions.
#[clap(long)]
detach: bool,
/// Run the test suites under the specified path
#[clap(long)]
run: Vec<String>,
/// Validator type to use for local testing
#[clap(value_enum, long, default_value = "surfpool")]
validator: ValidatorType,
args: Vec<String>,
/// Environment variables to pass into the docker container
#[clap(short, long, required = false)]
env: Vec<String>,
/// Arguments to pass to the underlying `cargo build-sbf` command.
#[clap(required = false, last = true)]
cargo_args: Vec<String>,
},
/// Creates a new program.
New {
/// Program name
name: String,
/// Rust program template to use
#[clap(value_enum, short, long, default_value = "multiple")]
template: ProgramTemplate,
/// Create new program even if there is already one
#[clap(long, action)]
force: bool,
},
/// Commands for interacting with interface definitions.
Idl {
#[clap(subcommand)]
subcmd: IdlCommand,
},
/// Remove all artifacts from the generated directories except program keypairs.
Clean,
/// Deploys each program in the workspace.
#[clap(hide = true)]
#[deprecated(since = "0.32.0", note = "use `anchor program deploy` instead")]
Deploy {
/// Only deploy this program
#[clap(short, long)]
program_name: Option<String>,
/// Keypair of the program (filepath) (requires program-name)
#[clap(long, requires = "program_name")]
program_keypair: Option<String>,
/// If true, deploy from path target/verifiable
#[clap(short, long)]
verifiable: bool,
/// Don't upload IDL during deployment (IDL is uploaded by default)
#[clap(long)]
no_idl: bool,
/// Arguments to pass to the underlying `solana program deploy` command.
#[clap(required = false, last = true)]
solana_args: Vec<String>,
},
/// Runs the deploy migration script.
Migrate,
/// Deploys, initializes an IDL, and migrates all in one command.
/// Upgrades a single program. The configured wallet must be the upgrade
/// authority.
#[clap(hide = true)]
#[deprecated(since = "0.32.0", note = "use `anchor program upgrade` instead")]
Upgrade {
/// The program to upgrade.
#[clap(short, long)]
program_id: Pubkey,
/// Filepath to the new program binary.
program_filepath: String,
/// Max times to retry on failure.
#[clap(long, default_value = "0")]
max_retries: u32,
/// Arguments to pass to the underlying `solana program deploy` command.
#[clap(required = false, last = true)]
solana_args: Vec<String>,
},
/// Request an airdrop of SOL
Airdrop {
/// Amount of SOL to airdrop
amount: f64,
/// Recipient address (defaults to configured wallet)
pubkey: Option<Pubkey>,
},
/// Cluster commands.
Cluster {
#[clap(subcommand)]
subcmd: ClusterCommand,
},
/// Configuration management commands.
Config {
#[clap(subcommand)]
subcmd: ConfigCommand,
},
/// Starts a node shell with an Anchor client setup according to the local
/// config.
Shell,
/// Runs the script defined by the current workspace's Anchor.toml.
Run {
/// The name of the script to run.
script: String,
/// Argument to pass to the underlying script.
#[clap(required = false, last = true)]
script_args: Vec<String>,
},
/// Program keypair commands.
Keys {
#[clap(subcommand)]
subcmd: KeysCommand,
},
/// Localnet commands.
Localnet {
/// Flag to skip building the program in the workspace,
/// use this to save time when running test and the program code is not altered.
#[clap(long)]
skip_build: bool,
/// Use this flag if you want to run tests against previously deployed
/// programs.
#[clap(long)]
skip_deploy: bool,
/// True if the build should not fail even if there are
/// no "CHECK" comments where normally required
#[clap(long)]
skip_lint: bool,
/// Skip checking for program ID mismatch between keypair and declare_id
#[clap(long)]
ignore_keys: bool,
/// Validator type to use for local testing
#[clap(value_enum, long, default_value = "surfpool")]
validator: ValidatorType,
/// Environment variables to pass into the docker container
#[clap(short, long, required = false)]
env: Vec<String>,
/// Arguments to pass to the underlying `cargo build-sbf` command.
#[clap(required = false, last = true)]
cargo_args: Vec<String>,
},
/// Fetch and deserialize an account using the IDL provided.
Account {
/// Account struct to deserialize (format: <program_name>.<Account>)
account_type: String,
/// Address of the account to deserialize
address: Pubkey,
/// IDL to use (defaults to workspace IDL)
#[clap(long)]
idl: Option<String>,
},
/// Generates shell completions.
Completions {
#[clap(value_enum)]
shell: clap_complete::Shell,
},
/// Get your public key
Address,
/// Get your balance
Balance {
/// Account to check balance for (defaults to configured wallet)
pubkey: Option<Pubkey>,
/// Display balance in lamports instead of SOL
#[clap(long)]
lamports: bool,
},
/// Get current epoch
Epoch,
/// Get information about the current epoch
#[clap(name = "epoch-info")]
EpochInfo,
/// Stream transaction logs
Logs {
/// Include vote transactions when monitoring all transactions
#[clap(long)]
include_votes: bool,
/// Addresses to filter logs by
#[clap(long)]
address: Option<Vec<Pubkey>>,
},
/// Show the contents of an account
ShowAccount {
#[clap(flatten)]
cmd: account::ShowAccountCommand,
},
/// Keypair generation and management
Keygen {
#[clap(subcommand)]
subcmd: KeygenCommand,
},
/// Program deployment and management commands
Program {
#[clap(subcommand)]
subcmd: ProgramCommand,
},
}
#[derive(Debug, Parser)]
pub enum KeygenCommand {
/// Generate a new keypair
New {
/// Path to generated keypair file
#[clap(short = 'o', long)]
outfile: Option<String>,
/// Overwrite the output file if it exists
#[clap(short, long)]
force: bool,
/// Do not prompt for a passphrase
#[clap(long)]
no_passphrase: bool,
/// Do not display the generated pubkey
#[clap(long)]
silent: bool,
/// Number of words in the mnemonic phrase [possible values: 12, 15, 18, 21, 24]
#[clap(short = 'w', long, default_value = "12")]
word_count: usize,
},
/// Display the pubkey for a given keypair
Pubkey {
/// Keypair filepath
keypair: Option<String>,
},
/// Recover a keypair from a seed phrase
Recover {
/// Path to recovered keypair file
#[clap(short = 'o', long)]
outfile: Option<String>,
/// Overwrite the output file if it exists
#[clap(short, long)]
force: bool,
/// Skip seed phrase validation
#[clap(long)]
skip_seed_phrase_validation: bool,
/// Do not prompt for a passphrase
#[clap(long)]
no_passphrase: bool,
},
/// Verify a keypair can sign and verify a message
Verify {
/// Public key to verify
pubkey: Pubkey,
/// Keypair filepath (defaults to configured wallet)
keypair: Option<String>,
},
}
#[derive(Debug, Parser)]
pub enum KeysCommand {
/// List all of the program keys.
List,
/// Sync program `declare_id!` pubkeys with the program's actual pubkey.
Sync {
/// Only sync the given program instead of all programs
#[clap(short, long)]
program_name: Option<String>,
},
}
#[derive(Debug, Parser)]
pub enum ProgramCommand {
/// Deploy an upgradeable program
Deploy {
/// Program filepath (e.g., target/deploy/my_program.so).
/// If not provided, discovers programs from workspace
program_filepath: Option<String>,
/// Program name to deploy (from workspace). Used when program_filepath is not provided
#[clap(short, long)]
program_name: Option<String>,
/// Program keypair filepath (defaults to target/deploy/{program_name}-keypair.json)
#[clap(long)]
program_keypair: Option<String>,
/// Upgrade authority keypair (defaults to configured wallet)
#[clap(long)]
upgrade_authority: Option<String>,
/// Program id to deploy to (derived from program-keypair if not specified)
#[clap(long)]
program_id: Option<Pubkey>,
/// Buffer account to use for deployment
#[clap(long)]
buffer: Option<Pubkey>,
/// Maximum transaction length (BPF loader upgradeable limit)
#[clap(long)]
max_len: Option<usize>,
/// Don't upload IDL during deployment (IDL is uploaded by default)
#[clap(long)]
no_idl: bool,
/// Make the program immutable after deployment (cannot be upgraded)
#[clap(long = "final")]
make_final: bool,
/// Additional arguments to configure deployment (e.g., --with-compute-unit-price 1000)
#[clap(required = false, last = true)]
solana_args: Vec<String>,
},
/// Write a program into a buffer account
WriteBuffer {
/// Program filepath (e.g., target/deploy/my_program.so).
/// If not provided, discovers program from workspace using program_name
program_filepath: Option<String>,
/// Program name to write (from workspace). Used when program_filepath is not provided
#[clap(short, long)]
program_name: Option<String>,
/// Buffer account keypair (defaults to new keypair)
#[clap(long)]
buffer: Option<String>,
/// Buffer authority (defaults to configured wallet)
#[clap(long)]
buffer_authority: Option<String>,
/// Maximum transaction length
#[clap(long)]
max_len: Option<usize>,
},
/// Set a new buffer authority
SetBufferAuthority {
/// Buffer account address
buffer: Pubkey,
/// New buffer authority
new_buffer_authority: Pubkey,
},
/// Set a new program authority
SetUpgradeAuthority {
/// Program id
program_id: Pubkey,
/// New upgrade authority pubkey
#[clap(long)]
new_upgrade_authority: Option<Pubkey>,
/// New upgrade authority signer (keypair file). Required unless --skip-new-upgrade-authority-signer-check is used.
/// When provided, both current and new authority will sign (checked mode, recommended)
#[clap(long)]
new_upgrade_authority_signer: Option<String>,
/// Skip new upgrade authority signer check. Allows setting authority with only current authority signature.
/// WARNING: Less safe - use only if you're confident the pubkey is correct
#[clap(long)]
skip_new_upgrade_authority_signer_check: bool,
/// Make the program immutable (cannot be upgraded)
#[clap(long = "final")]
make_final: bool,
/// Current upgrade authority keypair (defaults to configured wallet)
#[clap(long)]
upgrade_authority: Option<String>,
},
/// Display information about a buffer or program
Show {
/// Account address (buffer or program)
account: Pubkey,
/// Get account information from the Solana config file
#[clap(long)]
get_programs: bool,
/// Get account information from the Solana config file
#[clap(long)]
get_buffers: bool,
/// Show all accounts
#[clap(long)]
all: bool,
},
/// Upgrade an upgradeable program
Upgrade {
/// Program id to upgrade
program_id: Pubkey,
/// Program filepath (e.g., target/deploy/my_program.so). If not provided, discovers from workspace
#[clap(long)]
program_filepath: Option<String>,
/// Program name to upgrade (from workspace). Used when program_filepath is not provided
#[clap(short, long)]
program_name: Option<String>,
/// Existing buffer account to upgrade from. If not provided, auto-discovers program from workspace
#[clap(long)]
buffer: Option<Pubkey>,
/// Upgrade authority (defaults to configured wallet)
#[clap(long)]
upgrade_authority: Option<String>,
/// Max times to retry on failure
#[clap(long, default_value = "0")]
max_retries: u32,
/// Additional arguments to configure deployment (e.g., --with-compute-unit-price 1000)
#[clap(required = false, last = true)]
solana_args: Vec<String>,
},
/// Write the program data to a file
Dump {
/// Program account address
account: Pubkey,
/// Output file path
output_file: String,
},
/// Close a program or buffer account and withdraw all lamports
Close {
/// Account address to close (buffer or program).
/// If not provided, discovers program from workspace using program_name
account: Option<Pubkey>,
/// Program name to close (from workspace). Used when account is not provided
#[clap(short, long)]
program_name: Option<String>,
/// Authority keypair (defaults to configured wallet)
#[clap(long)]
authority: Option<String>,
/// Recipient address for reclaimed lamports (defaults to authority)
#[clap(long)]
recipient: Option<Pubkey>,
/// Bypass warning prompts
#[clap(long)]
bypass_warning: bool,
},
/// Extend the length of an upgradeable program
Extend {
/// Program id to extend.
/// If not provided, discovers program from workspace using program_name
program_id: Option<Pubkey>,
/// Program name to extend (from workspace). Used when program_id is not provided
#[clap(short, long)]
program_name: Option<String>,
/// Additional bytes to allocate
additional_bytes: usize,
},
}
#[derive(Debug, Parser)]
pub enum IdlCommand {
/// Initializes a program's IDL account. Can only be run once.
Init {
/// Program id to initialize IDL for.
/// If not provided, discovers program ID from IDL.
program_id: Option<Pubkey>,
#[clap(short, long)]
filepath: String,
#[clap(long)]
priority_fee: Option<u64>,
/// Create non-canonical metadata account (third-party metadata)
#[clap(long)]
non_canonical: bool,
/// Allow running against a localnet cluster (disabled by default)
#[clap(long)]
#[cfg(feature = "idl-localnet-testing")]
allow_localnet: bool,
},
/// Upgrades the IDL to the new file. An alias for first writing and then
/// then setting the idl buffer account.
Upgrade {
/// Program id to upgrade IDL for.
/// If not provided, discovers program ID from IDL.
program_id: Option<Pubkey>,
#[clap(short, long)]
filepath: String,
#[clap(long)]
priority_fee: Option<u64>,
/// Allow running against a localnet cluster (disabled by default)
#[clap(long)]
#[cfg(feature = "idl-localnet-testing")]
allow_localnet: bool,
},
/// Generates the IDL for the program using the compilation method.
#[clap(alias = "b")]
Build {
// Program name to build the IDL of(current dir's program if not specified)
#[clap(short, long)]
program_name: Option<String>,
/// Output file for the IDL (stdout if not specified)
#[clap(short, long)]
out: Option<String>,
/// Output file for the TypeScript IDL
#[clap(short = 't', long)]
out_ts: Option<String>,
/// Suppress doc strings in output
#[clap(long)]
no_docs: bool,
/// Do not check for safety comments
#[clap(long)]
skip_lint: bool,
/// Arguments to pass to the underlying `cargo test` command
#[clap(required = false, last = true)]
cargo_args: Vec<String>,
},
/// Fetches an IDL for the given program from a cluster.
Fetch {
program_id: Pubkey,
/// Output file for the IDL (stdout if not specified).
#[clap(short, long)]
out: Option<String>,
/// Fetch non-canonical metadata account (third-party metadata)
#[clap(long)]
non_canonical: bool,
},
/// Convert legacy IDLs (pre Anchor 0.30) to the new IDL spec
Convert {
/// Path to the IDL file
path: String,
/// Output file for the IDL (stdout if not specified)
#[clap(short, long)]
out: Option<String>,
/// Program id to initialize IDL for.
/// If not provided, discovers program ID from IDL.
#[clap(short, long)]
program_id: Option<Pubkey>,
},
/// Generate TypeScript type for the IDL
Type {
/// Path to the IDL file
path: String,
/// Output file for the IDL (stdout if not specified)
#[clap(short, long)]
out: Option<String>,
},
/// Close a metadata account and recover rent
Close {
/// The program ID
program_id: Pubkey,
/// The seed used for the metadata account (default: "idl")
#[clap(long, default_value = "idl")]
seed: String,
/// Priority fees in micro-lamports per compute unit
#[clap(long)]
priority_fee: Option<u64>,
},
/// Create a buffer account for metadata
CreateBuffer {
/// Path to the metadata file
#[clap(short, long)]
filepath: String,
/// Priority fees in micro-lamports per compute unit
#[clap(long)]
priority_fee: Option<u64>,
},
/// Set a new authority on a buffer account
SetBufferAuthority {
/// The buffer account address
buffer: Pubkey,
/// The new authority
#[clap(short, long)]
new_authority: Pubkey,
/// Priority fees in micro-lamports per compute unit
#[clap(long)]
priority_fee: Option<u64>,
},
/// Write metadata using a buffer account
WriteBuffer {
/// The program ID
program_id: Pubkey,
/// The buffer account address
#[clap(short, long)]
buffer: Pubkey,
/// The seed to use for the metadata account (default: "idl")
#[clap(long, default_value = "idl")]
seed: String,
/// Close the buffer after writing
#[clap(long)]
close_buffer: bool,
/// Priority fees in micro-lamports per compute unit
#[clap(long)]
priority_fee: Option<u64>,
},
}
#[derive(Debug, Parser)]
pub enum ClusterCommand {
/// Prints common cluster urls.
List,
}
#[derive(Debug, Parser)]
pub enum ConfigCommand {
/// Get configuration settings from the local Anchor.toml
Get,
/// Set configuration settings in the local Anchor.toml
Set {
/// Cluster to connect to (custom URL). Use -um, -ud, -ut, -ul for standard clusters
#[clap(short = 'u', long = "url")]
url: Option<String>,
/// Path to wallet keypair file to update the Anchor.toml file with
#[clap(short = 'k', long = "keypair")]
keypair: Option<String>,
},
}
fn get_keypair(path: &str) -> Result<Keypair> {
solana_keypair::read_keypair_file(path)
.map_err(|_| anyhow!("Unable to read keypair file ({path})"))
}
/// Format lamports as SOL with trailing zeros removed
fn format_sol(lamports: u64) -> String {
let sol = lamports as f64 / 1_000_000_000.0;
let formatted = format!("{:.8}", sol);
// Remove trailing zeros and decimal point if not needed
let trimmed = formatted.trim_end_matches('0').trim_end_matches('.');
format!("{} SOL", trimmed)
}
/// Get cluster URL and wallet path from Anchor config, CLI overrides, or Solana CLI config
fn get_cluster_and_wallet(cfg_override: &ConfigOverride) -> Result<(String, String)> {
// Try to get from Anchor workspace config first
if let Ok(Some(cfg)) = Config::discover(cfg_override) {
return Ok((
cfg.provider.cluster.url().to_string(),
cfg.provider.wallet.to_string(),
));
}
// Try to load Solana CLI config
let (cluster_url, wallet_path) =
if let Some(config_file) = solana_cli_config::CONFIG_FILE.as_ref() {
match SolanaCliConfig::load(config_file) {
Ok(cli_config) => (
cli_config.json_rpc_url.clone(),
cli_config.keypair_path.clone(),
),
Err(_) => {
// Fallback to defaults if Solana CLI config doesn't exist
(
"https://api.mainnet-beta.solana.com".to_string(),
dirs::home_dir()
.map(|home| {
home.join(".config/solana/id.json")
.to_string_lossy()
.to_string()
})
.unwrap_or_else(|| "~/.config/solana/id.json".to_string()),
)
}
}
} else {
// If CONFIG_FILE is None, use defaults
(
"https://api.mainnet-beta.solana.com".to_string(),
dirs::home_dir()
.map(|home| {
home.join(".config/solana/id.json")
.to_string_lossy()
.to_string()
})
.unwrap_or_else(|| "~/.config/solana/id.json".to_string()),
)
};
// Apply cluster override if provided
let final_cluster = if let Some(cluster) = &cfg_override.cluster {
cluster.url().to_string()
} else {
cluster_url
};
Ok((final_cluster, wallet_path))
}
/// Get the recommended priority fee from the RPC client
pub fn get_recommended_micro_lamport_fee(client: &RpcClient) -> Result<u64> {
let mut fees = client.get_recent_prioritization_fees(&[])?;
if fees.is_empty() {
// Fees may be empty, e.g. on localnet
return Ok(0);
}
// Get the median fee from the most recent 150 slots' prioritization fee
fees.sort_unstable_by_key(|fee| fee.prioritization_fee);
let median_index = fees.len() / 2;
let median_priority_fee = if fees.len() % 2 == 0 {
(fees[median_index - 1].prioritization_fee + fees[median_index].prioritization_fee) / 2
} else {
fees[median_index].prioritization_fee
};
Ok(median_priority_fee)
}
/// Prepend a compute unit ix, if the priority fee is greater than 0.
pub fn prepend_compute_unit_ix(
instructions: Vec<Instruction>,
client: &RpcClient,
priority_fee: Option<u64>,
) -> Result<Vec<Instruction>> {
let priority_fee = match priority_fee {
Some(fee) => fee,
None => get_recommended_micro_lamport_fee(client)?,
};
if priority_fee > 0 {
let mut instructions_appended = instructions.clone();
instructions_appended.insert(
0,
ComputeBudgetInstruction::set_compute_unit_price(priority_fee),
);
Ok(instructions_appended)
} else {
Ok(instructions)
}
}
pub fn entry(opts: Opts) -> Result<()> {
let restore_cbs = override_toolchain(&opts.cfg_override)?;
let result = process_command(opts);
restore_toolchain(restore_cbs)?;
result
}
/// Functions to restore toolchain entries
type RestoreToolchainCallbacks = Vec<Box<dyn FnOnce() -> Result<()>>>;
/// Override the toolchain from `Anchor.toml`.
///
/// Returns the previous versions to restore back to.
fn override_toolchain(cfg_override: &ConfigOverride) -> Result<RestoreToolchainCallbacks> {
let mut restore_cbs: RestoreToolchainCallbacks = vec![];
let cfg = Config::discover(cfg_override)?;
if let Some(cfg) = cfg {
fn parse_version(text: &str) -> Option<String> {
Some(
Regex::new(r"(\d+\.\d+\.\S+)")
.unwrap()
.captures_iter(text)
.next()?
.get(0)?
.as_str()
.to_string(),
)
}
fn get_current_version(cmd_name: &str) -> Result<String> {
let output = std::process::Command::new(cmd_name)
.arg("--version")
.output()?;
if !output.status.success() {
return Err(anyhow!("Failed to run `{cmd_name} --version`"));
}
let output_version = std::str::from_utf8(&output.stdout)?;
parse_version(output_version)
.ok_or_else(|| anyhow!("Failed to parse the version of `{cmd_name}`"))
}
if let Some(solana_version) = &cfg.toolchain.solana_version {
let current_version = get_current_version("solana")?;
if solana_version != ¤t_version {
// We are overriding with `solana-install` command instead of using the binaries
// from `~/.local/share/solana/install/releases` because we use multiple Solana
// binaries in various commands.
fn override_solana_version(version: String) -> Result<bool> {
// There is a deprecation warning message starting with `1.18.19` which causes
// parsing problems https://github.com/coral-xyz/anchor/issues/3147
let (cmd_name, domain) =
if Version::parse(&version)? < Version::parse("1.18.19")? {
("solana-install", "solana.com")
} else {
("agave-install", "anza.xyz")
};
// Install the command if it's not installed
if get_current_version(cmd_name).is_err() {
// `solana-install` and `agave-install` are not usable at the same time i.e.
// using one of them makes the other unusable with the default installation,
// causing the installation process to run each time users switch between
// `agave` supported versions. For example, if the user's active Solana
// version is `1.18.17`, and he specifies `solana_version = "2.0.6"`, this
// code path will run each time an Anchor command gets executed.
eprintln!(
"Command not installed: `{cmd_name}`. \
See https://github.com/anza-xyz/agave/wiki/Agave-Transition, \
installing..."
);
let install_script = std::process::Command::new("curl")
.args([
"-sSfL",
&format!("https://release.{domain}/v{version}/install"),
])
.output()?;
let is_successful = std::process::Command::new("sh")
.args(["-c", std::str::from_utf8(&install_script.stdout)?])
.spawn()?
.wait_with_output()?
.status
.success();
if !is_successful {
return Err(anyhow!("Failed to install `{cmd_name}`"));
}
}
let output = std::process::Command::new(cmd_name).arg("list").output()?;
if !output.status.success() {
return Err(anyhow!("Failed to list installed `solana` versions"));
}
// Hide the installation progress if the version is already installed
let is_installed = std::str::from_utf8(&output.stdout)?
.lines()
.filter_map(parse_version)
.any(|line_version| line_version == version);
let (stderr, stdout) = if is_installed {
(Stdio::null(), Stdio::null())
} else {