Skip to main content

anchor_cli/
config.rs

1use {
2    crate::{get_keypair, is_hidden, keys_sync, target_dir, AbsolutePath, DEFAULT_RPC_PORT},
3    anchor_client::Cluster,
4    anchor_lang_idl::types::Idl,
5    anyhow::{anyhow, bail, Context, Error, Result},
6    clap::{Parser, ValueEnum},
7    dirs::home_dir,
8    heck::ToSnakeCase,
9    reqwest::Url,
10    serde::{
11        de::{self, MapAccess, Visitor},
12        ser::SerializeMap,
13        Deserialize, Deserializer, Serialize, Serializer,
14    },
15    solana_cli_config::{Config as SolanaConfig, CONFIG_FILE},
16    solana_clock::Slot,
17    solana_commitment_config::CommitmentLevel,
18    solana_keypair::Keypair,
19    solana_pubkey::Pubkey,
20    solana_signer::Signer,
21    std::{
22        collections::{BTreeMap, HashMap},
23        convert::TryFrom,
24        fmt,
25        fs::{self, File},
26        io::{self, prelude::*},
27        marker::PhantomData,
28        ops::Deref,
29        path::{Path, PathBuf},
30        process::Command,
31        str::FromStr,
32    },
33    walkdir::WalkDir,
34};
35
36pub const SURFPOOL_HOST: &str = "127.0.0.1";
37/// Wrapper around CommitmentLevel to support case-insensitive parsing
38#[derive(Debug, Clone, Copy, PartialEq, Eq, AbsolutePath)]
39pub struct CaseInsensitiveCommitmentLevel(pub CommitmentLevel);
40
41impl FromStr for CaseInsensitiveCommitmentLevel {
42    type Err = String;
43
44    fn from_str(s: &str) -> Result<Self, Self::Err> {
45        // Convert to lowercase for case-insensitive matching
46        let lowercase = s.to_lowercase();
47        let commitment = CommitmentLevel::from_str(&lowercase).map_err(|_| {
48            format!(
49                "Invalid commitment level '{}'. Valid values are: processed, confirmed, finalized",
50                s
51            )
52        })?;
53        Ok(CaseInsensitiveCommitmentLevel(commitment))
54    }
55}
56
57impl From<CaseInsensitiveCommitmentLevel> for CommitmentLevel {
58    fn from(val: CaseInsensitiveCommitmentLevel) -> Self {
59        val.0
60    }
61}
62
63pub trait Merge: Sized {
64    fn merge(&mut self, _other: Self) {}
65}
66
67#[derive(Default, Debug, Parser, AbsolutePath)]
68pub struct ConfigOverride {
69    /// Cluster override.
70    #[clap(global = true, long = "provider.cluster")]
71    pub cluster: Option<Cluster>,
72    /// Wallet override.
73    #[clap(global = true, long = "provider.wallet")]
74    pub wallet: Option<WalletPath>,
75    /// Commitment override (valid values: processed, confirmed, finalized).
76    #[clap(global = true, long = "commitment")]
77    pub commitment: Option<CaseInsensitiveCommitmentLevel>,
78}
79
80#[derive(Debug)]
81pub struct WithPath<T> {
82    inner: T,
83    path: PathBuf,
84}
85
86impl<T> WithPath<T> {
87    pub fn new(inner: T, path: PathBuf) -> Self {
88        Self { inner, path }
89    }
90
91    pub fn path(&self) -> &PathBuf {
92        &self.path
93    }
94
95    pub fn into_inner(self) -> T {
96        self.inner
97    }
98}
99
100impl<T> std::convert::AsRef<T> for WithPath<T> {
101    fn as_ref(&self) -> &T {
102        &self.inner
103    }
104}
105
106#[derive(Debug, Clone, PartialEq)]
107pub struct Manifest(cargo_toml::Manifest);
108
109impl Manifest {
110    pub fn from_path(p: impl AsRef<Path>) -> Result<Self> {
111        cargo_toml::Manifest::from_path(&p)
112            .map(Manifest)
113            .map_err(anyhow::Error::from)
114            .with_context(|| format!("Error reading manifest from path: {}", p.as_ref().display()))
115    }
116
117    pub fn lib_name(&self) -> Result<String> {
118        match &self.lib {
119            Some(cargo_toml::Product {
120                name: Some(name), ..
121            }) => Ok(name.to_owned()),
122            _ => self
123                .package
124                .as_ref()
125                .ok_or_else(|| anyhow!("package section not provided"))
126                .map(|pkg| pkg.name.to_snake_case()),
127        }
128    }
129
130    pub fn version(&self) -> String {
131        match &self.package {
132            Some(package) => package.version().to_string(),
133            _ => "0.0.0".to_string(),
134        }
135    }
136
137    // Climbs each parent directory from the current dir until we find a Cargo.toml
138    pub fn discover() -> Result<Option<WithPath<Manifest>>> {
139        Manifest::discover_from_path(std::env::current_dir()?)
140    }
141
142    // Climbs each parent directory from a given starting directory until we find a Cargo.toml.
143    pub fn discover_from_path(start_from: PathBuf) -> Result<Option<WithPath<Manifest>>> {
144        let mut cwd_opt = Some(start_from.as_path());
145
146        while let Some(cwd) = cwd_opt {
147            let mut anchor_toml = false;
148
149            for f in fs::read_dir(cwd).with_context(|| {
150                format!("Error reading the directory with path: {}", cwd.display())
151            })? {
152                let p = f
153                    .with_context(|| {
154                        format!("Error reading the directory with path: {}", cwd.display())
155                    })?
156                    .path();
157                if let Some(filename) = p.file_name().and_then(|name| name.to_str()) {
158                    if filename == "Cargo.toml" {
159                        return Ok(Some(WithPath::new(Manifest::from_path(&p)?, p)));
160                    }
161                    if filename == "Anchor.toml" {
162                        anchor_toml = true;
163                    }
164                }
165            }
166
167            // Not found. Go up a directory level, but don't go up from Anchor.toml
168            if anchor_toml {
169                break;
170            }
171
172            cwd_opt = cwd.parent();
173        }
174
175        Ok(None)
176    }
177}
178
179impl Deref for Manifest {
180    type Target = cargo_toml::Manifest;
181
182    fn deref(&self) -> &Self::Target {
183        &self.0
184    }
185}
186
187impl WithPath<Config> {
188    pub fn get_program_list(&self) -> Result<Vec<PathBuf>> {
189        // Canonicalize the workspace filepaths to compare with relative paths.
190        let (members, exclude) = self.canonicalize_workspace()?;
191
192        // Get all candidate programs.
193        //
194        // If [workspace.members] exists, then use that.
195        // Otherwise, default to `programs/*`.
196        let program_paths: Vec<PathBuf> = {
197            if members.is_empty() {
198                let path = self.path().parent().unwrap().join("programs");
199                if let Ok(entries) = fs::read_dir(path) {
200                    entries
201                        .filter(|entry| entry.as_ref().map(|e| e.path().is_dir()).unwrap_or(false))
202                        .map(|dir| dir.map(|d| d.path().canonicalize().unwrap()))
203                        .collect::<Vec<Result<PathBuf, std::io::Error>>>()
204                        .into_iter()
205                        .collect::<Result<Vec<PathBuf>, std::io::Error>>()?
206                } else {
207                    Vec::new()
208                }
209            } else {
210                members
211            }
212        };
213
214        // Filter out everything part of the exclude array.
215        Ok(program_paths
216            .into_iter()
217            .filter(|m| !exclude.contains(m))
218            .collect())
219    }
220
221    pub fn read_all_programs(&self) -> Result<Vec<Program>> {
222        let mut r = vec![];
223        for path in self.get_program_list()? {
224            let cargo = Manifest::from_path(path.join("Cargo.toml"))?;
225            let lib_name = cargo.lib_name()?;
226
227            let idl_filepath = target_dir()?
228                .join("idl")
229                .join(&lib_name)
230                .with_extension("json");
231            let idl = fs::read(idl_filepath)
232                .ok()
233                .map(|bytes| serde_json::from_reader(&*bytes))
234                .transpose()?;
235
236            r.push(Program {
237                lib_name,
238                path,
239                idl,
240            });
241        }
242        Ok(r)
243    }
244
245    /// Read and get all the programs from the workspace.
246    ///
247    /// This method will only return the given program if `name` exists.
248    pub fn get_programs(&self, name: Option<String>) -> Result<Vec<Program>> {
249        let programs = self.read_all_programs()?;
250        let programs = match name {
251            Some(name) => vec![programs
252                .iter()
253                .find(|program| {
254                    program.lib_name == name
255                        || program
256                            .path
257                            .file_name()
258                            .and_then(|f| f.to_str())
259                            .map(|f| f == name)
260                            .unwrap_or(false)
261                })
262                .cloned()
263                .ok_or_else(|| {
264                    let mut available_programs: Vec<String> =
265                        programs.iter().map(|p| p.lib_name.clone()).collect();
266                    available_programs.sort();
267
268                    if available_programs.is_empty() {
269                        anyhow!("Program '{name}' not found. No programs available in workspace.")
270                    } else {
271                        anyhow!(
272                            "Program '{name}' not found.\n\nAvailable programs:\n  {}",
273                            available_programs.join("\n  ")
274                        )
275                    }
276                })?],
277            None => programs,
278        };
279
280        Ok(programs)
281    }
282
283    /// Get the specified program from the workspace.
284    pub fn get_program(&self, name: &str) -> Result<Program> {
285        self.get_programs(Some(name.to_owned()))?
286            .into_iter()
287            .next()
288            .ok_or_else(|| anyhow!("Expected a program"))
289    }
290
291    pub fn canonicalize_workspace(&self) -> Result<(Vec<PathBuf>, Vec<PathBuf>)> {
292        let members = self.process_paths(&self.workspace.members)?;
293        let exclude = self.process_paths(&self.workspace.exclude)?;
294        Ok((members, exclude))
295    }
296
297    fn process_paths(&self, paths: &[String]) -> Result<Vec<PathBuf>, Error> {
298        let base_path = self.path().parent().unwrap();
299        paths
300            .iter()
301            .flat_map(|m| {
302                let path = base_path.join(m);
303                if m.ends_with("/*") {
304                    let dir = path.parent().unwrap();
305                    match fs::read_dir(dir) {
306                        Ok(entries) => entries
307                            .filter_map(|entry| entry.ok())
308                            .map(|entry| self.process_single_path(&entry.path()))
309                            .collect(),
310                        Err(e) => vec![Err(Error::new(io::Error::other(format!(
311                            "Error reading directory {dir:?}: {e}"
312                        ))))],
313                    }
314                } else {
315                    vec![self.process_single_path(&path)]
316                }
317            })
318            .collect()
319    }
320
321    fn process_single_path(&self, path: &PathBuf) -> Result<PathBuf, Error> {
322        path.canonicalize().map_err(|e| {
323            Error::new(io::Error::other(format!(
324                "Error canonicalizing path {path:?}: {e}"
325            )))
326        })
327    }
328}
329
330impl WalletPath {
331    fn resolve_relative_to(self, base: &Path) -> Self {
332        if self.0.is_relative() {
333            Self(base.join(self.0))
334        } else {
335            self
336        }
337    }
338}
339
340impl<T> std::ops::Deref for WithPath<T> {
341    type Target = T;
342    fn deref(&self) -> &Self::Target {
343        &self.inner
344    }
345}
346
347impl<T> std::ops::DerefMut for WithPath<T> {
348    fn deref_mut(&mut self) -> &mut Self::Target {
349        &mut self.inner
350    }
351}
352
353#[derive(Debug, Default)]
354pub struct Config {
355    pub toolchain: ToolchainConfig,
356    pub features: FeaturesConfig,
357    pub provider: ProviderConfig,
358    pub programs: ProgramsConfig,
359    pub scripts: ScriptsConfig,
360    pub hooks: HooksConfig,
361    pub workspace: WorkspaceConfig,
362    pub clients: ClientsConfig,
363    // Separate entry next to test_config because
364    // "anchor localnet" only has access to the Anchor.toml,
365    // not the Test.toml files
366    pub validator: Option<ValidatorType>,
367    pub test_validator: Option<TestValidator>,
368    pub test_config: Option<TestConfig>,
369    pub surfpool_config: Option<SurfpoolConfig>,
370    /// If `Some(true)`, `anchor test` won't auto-start a validator for this
371    /// workspace. Emitted by `anchor init` for in-process test templates
372    /// (litesvm / mollusk) where the test harness never opens an RPC.
373    pub skip_local_validator: Option<bool>,
374}
375
376#[derive(ValueEnum, Parser, Clone, Copy, PartialEq, Eq, Debug, AbsolutePath)]
377pub enum ValidatorType {
378    /// Use Surfpool validator (default)
379    Surfpool,
380    /// Use Solana test validator
381    Legacy,
382}
383#[derive(Default, Clone, Debug, Serialize, Deserialize)]
384pub struct ToolchainConfig {
385    pub anchor_version: Option<String>,
386    pub solana_version: Option<String>,
387    pub package_manager: Option<PackageManager>,
388}
389
390/// Package manager to use for the project.
391///
392/// No `Default` impl; this enum represents an explicit user choice. Call sites
393/// that need a concrete package manager should go through `resolve_package_manager`
394/// so fallback behavior and missing-binary diagnostics stay centralized.
395#[derive(Clone, Debug, Eq, PartialEq, Parser, ValueEnum, Serialize, Deserialize, AbsolutePath)]
396#[serde(rename_all = "lowercase")]
397pub enum PackageManager {
398    /// Use npm as the package manager.
399    NPM,
400    /// Use yarn as the package manager.
401    Yarn,
402    /// Use pnpm as the package manager.
403    PNPM,
404    /// Use bun as the package manager.
405    Bun,
406}
407
408impl std::fmt::Display for PackageManager {
409    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
410        let pkg_manager_str = match self {
411            PackageManager::NPM => "npm",
412            PackageManager::Yarn => "yarn",
413            PackageManager::PNPM => "pnpm",
414            PackageManager::Bun => "bun",
415        };
416
417        write!(f, "{pkg_manager_str}")
418    }
419}
420
421#[derive(Clone, Debug, Serialize, Deserialize)]
422pub struct FeaturesConfig {
423    /// Enable account resolution.
424    ///
425    /// Not able to specify default bool value: https://github.com/serde-rs/serde/issues/368
426    #[serde(default = "FeaturesConfig::get_default_resolution")]
427    pub resolution: bool,
428    /// Disable safety comment checks
429    #[serde(default, rename = "skip-lint")]
430    pub skip_lint: bool,
431}
432
433impl FeaturesConfig {
434    fn get_default_resolution() -> bool {
435        true
436    }
437}
438
439impl Default for FeaturesConfig {
440    fn default() -> Self {
441        Self {
442            resolution: Self::get_default_resolution(),
443            skip_lint: false,
444        }
445    }
446}
447
448#[derive(Debug, Default)]
449pub struct ProviderConfig {
450    pub cluster: Cluster,
451    pub wallet: WalletPath,
452}
453
454pub type ScriptsConfig = BTreeMap<String, String>;
455
456pub type ProgramsConfig = BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>;
457
458#[derive(Default, Clone, Debug, Serialize, Deserialize)]
459#[serde(deny_unknown_fields)]
460pub struct HooksConfig {
461    #[serde(alias = "pre-build")]
462    pre_build: Option<Hook>,
463    #[serde(alias = "post-build")]
464    post_build: Option<Hook>,
465    #[serde(alias = "pre-test")]
466    pre_test: Option<Hook>,
467    #[serde(alias = "post-test")]
468    post_test: Option<Hook>,
469    #[serde(alias = "pre-deploy")]
470    pre_deploy: Option<Hook>,
471    #[serde(alias = "post-deploy")]
472    post_deploy: Option<Hook>,
473}
474
475#[derive(Clone, Debug, Serialize, Deserialize)]
476#[serde(untagged)]
477enum Hook {
478    Single(String),
479    List(Vec<String>),
480}
481
482impl Hook {
483    pub fn hooks(&self) -> &[String] {
484        match self {
485            Self::Single(h) => std::slice::from_ref(h),
486            Self::List(l) => l.as_slice(),
487        }
488    }
489}
490
491#[derive(Clone, Copy, Debug, PartialEq, Eq)]
492pub enum HookType {
493    PreBuild,
494    PostBuild,
495    PreTest,
496    PostTest,
497    PreDeploy,
498    PostDeploy,
499}
500
501/// `[clients]` section of `Anchor.toml`.
502///
503/// Declares which Codama-generated client SDKs the workspace ships, where
504/// they live on disk, and whether they should be regenerated automatically.
505///
506/// TOML shape:
507///
508/// ```toml
509/// [clients]
510/// auto = true
511/// rust = true
512/// js = { enable = true }
513/// go = { enable = true, path = "go-client" }
514/// js-umi = false
515/// ```
516#[derive(Debug, Default, Clone, Serialize, Deserialize)]
517pub struct ClientsConfig {
518    /// Regenerate clients automatically on `anchor build`.
519    #[serde(default, skip_serializing_if = "is_false")]
520    pub auto: bool,
521    #[serde(default, skip_serializing_if = "Option::is_none")]
522    pub js: Option<ClientLanguageConfig>,
523    #[serde(
524        default,
525        rename = "js-umi",
526        alias = "js_umi",
527        skip_serializing_if = "Option::is_none"
528    )]
529    pub js_umi: Option<ClientLanguageConfig>,
530    #[serde(default, skip_serializing_if = "Option::is_none")]
531    pub rust: Option<ClientLanguageConfig>,
532    #[serde(default, skip_serializing_if = "Option::is_none")]
533    pub go: Option<ClientLanguageConfig>,
534}
535
536/// Per-language client entry. Accepts either a bare `bool` (`rust = true`)
537/// or a table with explicit `enable` and optional `path` keys.
538#[derive(Debug, Clone, Serialize, Deserialize)]
539#[serde(untagged)]
540pub enum ClientLanguageConfig {
541    /// `lang = true` / `lang = false`.
542    Enabled(bool),
543    /// `lang = { enable = bool, path = "..." }`.
544    Detailed {
545        #[serde(default = "ClientLanguageConfig::default_enable")]
546        enable: bool,
547        #[serde(default, skip_serializing_if = "Option::is_none")]
548        path: Option<String>,
549    },
550}
551
552impl ClientLanguageConfig {
553    fn default_enable() -> bool {
554        true
555    }
556
557    pub fn is_enabled(&self) -> bool {
558        match self {
559            Self::Enabled(enabled) => *enabled,
560            Self::Detailed { enable, .. } => *enable,
561        }
562    }
563
564    pub fn path(&self) -> Option<&str> {
565        match self {
566            Self::Enabled(_) => None,
567            Self::Detailed { path, .. } => path.as_deref(),
568        }
569    }
570}
571
572/// Stable identifiers used both as TOML keys and as Codama script names.
573pub const CLIENT_LANGUAGES: &[&str] = &["js", "js-umi", "rust", "go"];
574
575impl ClientsConfig {
576    /// Look up a language entry by its [`CLIENT_LANGUAGES`] id.
577    pub fn get(&self, language: &str) -> Option<&ClientLanguageConfig> {
578        match language {
579            "js" => self.js.as_ref(),
580            "js-umi" => self.js_umi.as_ref(),
581            "rust" => self.rust.as_ref(),
582            "go" => self.go.as_ref(),
583            _ => None,
584        }
585    }
586
587    /// Languages the user has explicitly enabled, paired with the resolved
588    /// output directory (`<workspace>/clients/<lang>` if no `path` was set on
589    /// the entry). Relative custom paths are resolved from the workspace root,
590    /// not the process cwd.
591    pub fn enabled(&self, workspace_dir: &Path) -> Vec<(&'static str, PathBuf)> {
592        let base = workspace_dir.join("clients");
593        CLIENT_LANGUAGES
594            .iter()
595            .filter_map(|&lang| {
596                let entry = self.get(lang)?;
597                if !entry.is_enabled() {
598                    return None;
599                }
600                let path = entry
601                    .path()
602                    .map(|path| resolve_client_path(workspace_dir, path))
603                    .unwrap_or_else(|| base.join(lang));
604                Some((lang, path))
605            })
606            .collect()
607    }
608}
609
610fn resolve_client_path(workspace_dir: &Path, path: &str) -> PathBuf {
611    let path = PathBuf::from(path);
612    if path.is_absolute() {
613        path
614    } else {
615        workspace_dir.join(path)
616    }
617}
618
619fn is_false(b: &bool) -> bool {
620    !*b
621}
622
623#[derive(Debug, Default, Clone, Serialize, Deserialize)]
624pub struct WorkspaceConfig {
625    #[serde(default, skip_serializing_if = "Vec::is_empty")]
626    pub members: Vec<String>,
627    #[serde(default, skip_serializing_if = "Vec::is_empty")]
628    pub exclude: Vec<String>,
629    #[serde(default, skip_serializing_if = "String::is_empty")]
630    pub idls: String,
631    #[serde(default, skip_serializing_if = "String::is_empty")]
632    pub types: String,
633}
634
635#[derive(ValueEnum, Parser, Clone, PartialEq, Eq, Debug, AbsolutePath)]
636pub enum BootstrapMode {
637    None,
638    Debian,
639}
640
641#[derive(Debug, Clone)]
642pub struct BuildConfig {
643    pub verifiable: bool,
644    pub solana_version: Option<String>,
645    pub docker_image: String,
646    pub bootstrap: BootstrapMode,
647}
648
649impl Config {
650    pub fn add_test_config(
651        &mut self,
652        root: impl AsRef<Path>,
653        test_paths: Vec<PathBuf>,
654    ) -> Result<()> {
655        self.test_config = TestConfig::discover(root, test_paths)?;
656        Ok(())
657    }
658
659    pub fn docker(&self) -> String {
660        let version = self
661            .toolchain
662            .anchor_version
663            .as_deref()
664            .unwrap_or(crate::DOCKER_BUILDER_VERSION);
665        format!("quay.io/ottersec/anchor:v{version}")
666    }
667
668    pub fn discover(cfg_override: &ConfigOverride) -> Result<Option<WithPath<Config>>> {
669        Config::_discover().map(|opt| {
670            opt.map(|mut cfg| {
671                if let Some(cluster) = cfg_override.cluster.clone() {
672                    cfg.provider.cluster = cluster;
673                }
674                if let Some(wallet) = cfg_override.wallet.clone() {
675                    cfg.provider.wallet = wallet;
676                }
677                cfg
678            })
679        })
680    }
681
682    // Climbs each parent directory until we find an Anchor.toml.
683    fn _discover() -> Result<Option<WithPath<Config>>> {
684        let _cwd = std::env::current_dir()?;
685        let mut cwd_opt = Some(_cwd.as_path());
686
687        while let Some(cwd) = cwd_opt {
688            for f in fs::read_dir(cwd).with_context(|| {
689                format!("Error reading the directory with path: {}", cwd.display())
690            })? {
691                let p = f
692                    .with_context(|| {
693                        format!("Error reading the directory with path: {}", cwd.display())
694                    })?
695                    .path();
696                if let Some(filename) = p.file_name() {
697                    if filename.to_str() == Some("Anchor.toml") {
698                        let config_dir = p.parent().unwrap();
699                        // Make sure the program id is correct (only on the initial build)
700                        let mut cfg = Config::from_path(&p)?;
701                        let deploy_dir = target_dir()?.join("deploy");
702                        if !deploy_dir.exists() && !cfg.programs.contains_key(&Cluster::Localnet) {
703                            println!("Updating program ids...");
704                            fs::create_dir_all(deploy_dir)?;
705                            keys_sync(&ConfigOverride::default(), None)?;
706                            cfg = Config::from_path(&p)?;
707                        }
708                        cfg.provider.wallet = cfg.provider.wallet.resolve_relative_to(config_dir);
709
710                        return Ok(Some(WithPath::new(cfg, p)));
711                    }
712                }
713            }
714
715            cwd_opt = cwd.parent();
716        }
717
718        Ok(None)
719    }
720
721    fn from_path(p: impl AsRef<Path>) -> Result<Self> {
722        fs::read_to_string(&p)
723            .with_context(|| format!("Error reading the file with path: {}", p.as_ref().display()))?
724            .parse::<Self>()
725    }
726
727    pub fn wallet_kp(&self) -> Result<Keypair> {
728        get_keypair(Path::new(&self.provider.wallet.0))
729    }
730
731    pub fn run_hooks(&self, hook_type: HookType) -> Result<()> {
732        let hooks = match hook_type {
733            HookType::PreBuild => &self.hooks.pre_build,
734            HookType::PostBuild => &self.hooks.post_build,
735            HookType::PreTest => &self.hooks.pre_test,
736            HookType::PostTest => &self.hooks.post_test,
737            HookType::PreDeploy => &self.hooks.pre_deploy,
738            HookType::PostDeploy => &self.hooks.post_deploy,
739        };
740        let cmds = hooks.as_ref().map(Hook::hooks).unwrap_or_default();
741        for cmd in cmds {
742            let status = Command::new("bash")
743                .arg("-c")
744                .arg(cmd)
745                .status()
746                .with_context(|| format!("failed to execute `{cmd}`"))?;
747            if !status.success() {
748                match status.code() {
749                    Some(code) => bail!("`{cmd}` failed with exit code {code}"),
750                    None => bail!("`{cmd}` killed by signal"),
751                }
752            }
753        }
754        Ok(())
755    }
756}
757
758#[derive(Debug, Serialize, Deserialize)]
759struct _Config {
760    toolchain: Option<ToolchainConfig>,
761    features: Option<FeaturesConfig>,
762    programs: Option<BTreeMap<String, BTreeMap<String, serde_json::Value>>>,
763    provider: Provider,
764    workspace: Option<WorkspaceConfig>,
765    scripts: Option<ScriptsConfig>,
766    hooks: Option<HooksConfig>,
767    test: Option<_TestValidator>,
768    surfpool: Option<_SurfpoolConfig>,
769    #[serde(skip_serializing_if = "Option::is_none")]
770    skip_local_validator: Option<bool>,
771    #[serde(skip_serializing_if = "Option::is_none")]
772    clients: Option<ClientsConfig>,
773}
774
775#[derive(Debug, Serialize, Deserialize)]
776struct Provider {
777    #[serde(serialize_with = "ser_cluster", deserialize_with = "des_cluster")]
778    cluster: Cluster,
779    wallet: String,
780}
781
782fn ser_cluster<S: Serializer>(cluster: &Cluster, s: S) -> Result<S::Ok, S::Error> {
783    match cluster {
784        Cluster::Custom(http, ws) => {
785            match (Url::parse(http), Url::parse(ws)) {
786                // If `ws` was derived from `http`, serialize `http` as string
787                (Ok(h), Ok(w)) if h.domain() == w.domain() => s.serialize_str(http),
788                _ => {
789                    let mut map = s.serialize_map(Some(2))?;
790                    map.serialize_entry("http", http)?;
791                    map.serialize_entry("ws", ws)?;
792                    map.end()
793                }
794            }
795        }
796        _ => s.serialize_str(&cluster.to_string()),
797    }
798}
799
800fn des_cluster<'de, D>(deserializer: D) -> Result<Cluster, D::Error>
801where
802    D: Deserializer<'de>,
803{
804    struct StringOrCustomCluster(PhantomData<fn() -> Cluster>);
805
806    impl<'de> Visitor<'de> for StringOrCustomCluster {
807        type Value = Cluster;
808
809        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
810            formatter.write_str("string or map")
811        }
812
813        fn visit_str<E>(self, value: &str) -> Result<Cluster, E>
814        where
815            E: de::Error,
816        {
817            value.parse().map_err(de::Error::custom)
818        }
819
820        fn visit_map<M>(self, mut map: M) -> Result<Cluster, M::Error>
821        where
822            M: MapAccess<'de>,
823        {
824            // Gets keys
825            if let (Some((http_key, http_value)), Some((ws_key, ws_value))) = (
826                map.next_entry::<String, String>()?,
827                map.next_entry::<String, String>()?,
828            ) {
829                // Checks keys
830                if http_key != "http" || ws_key != "ws" {
831                    return Err(de::Error::custom("Invalid key"));
832                }
833
834                // Checks urls
835                Url::parse(&http_value).map_err(de::Error::custom)?;
836                Url::parse(&ws_value).map_err(de::Error::custom)?;
837
838                Ok(Cluster::Custom(http_value, ws_value))
839            } else {
840                Err(de::Error::custom("Invalid entry"))
841            }
842        }
843    }
844    deserializer.deserialize_any(StringOrCustomCluster(PhantomData))
845}
846
847impl fmt::Display for Config {
848    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849        let programs = {
850            let c = ser_programs(&self.programs);
851            if c.is_empty() {
852                None
853            } else {
854                Some(c)
855            }
856        };
857        let cfg = _Config {
858            toolchain: Some(self.toolchain.clone()),
859            features: Some(self.features.clone()),
860            provider: Provider {
861                cluster: self.provider.cluster.clone(),
862                wallet: self.provider.wallet.stringify_with_tilde(),
863            },
864            test: self.test_validator.clone().map(Into::into),
865            scripts: match self.scripts.is_empty() {
866                true => None,
867                false => Some(self.scripts.clone()),
868            },
869            hooks: Some(self.hooks.clone()),
870            programs,
871            workspace: (!self.workspace.members.is_empty() || !self.workspace.exclude.is_empty())
872                .then(|| self.workspace.clone()),
873            surfpool: self.surfpool_config.clone().map(Into::into),
874            skip_local_validator: self.skip_local_validator,
875            clients: {
876                let clients = &self.clients;
877                let empty = !clients.auto
878                    && clients.js.is_none()
879                    && clients.js_umi.is_none()
880                    && clients.rust.is_none()
881                    && clients.go.is_none();
882                (!empty).then(|| clients.clone())
883            },
884        };
885
886        let cfg = toml::to_string(&cfg).expect("Must be well formed");
887        write!(f, "{cfg}")
888    }
889}
890
891impl FromStr for Config {
892    type Err = Error;
893
894    fn from_str(s: &str) -> Result<Self, Self::Err> {
895        let cfg: _Config =
896            toml::from_str(s).map_err(|e| anyhow!("Unable to deserialize config: {e}"))?;
897        Ok(Config {
898            toolchain: cfg.toolchain.unwrap_or_default(),
899            features: cfg.features.unwrap_or_default(),
900            provider: ProviderConfig {
901                cluster: cfg.provider.cluster,
902                wallet: shellexpand::tilde(&cfg.provider.wallet).parse()?,
903            },
904            scripts: cfg.scripts.unwrap_or_default(),
905            hooks: cfg.hooks.unwrap_or_default(),
906            validator: None, // Will be set based on CLI flags
907            test_validator: cfg.test.map(Into::into),
908            test_config: None,
909            programs: cfg.programs.map_or(Ok(BTreeMap::new()), deser_programs)?,
910            workspace: cfg.workspace.unwrap_or_default(),
911            surfpool_config: cfg.surfpool.map(Into::into),
912            skip_local_validator: cfg.skip_local_validator,
913            clients: cfg.clients.unwrap_or_default(),
914        })
915    }
916}
917
918pub fn get_solana_cfg_url() -> Result<String, io::Error> {
919    let config_file = CONFIG_FILE.as_ref().ok_or_else(|| {
920        io::Error::new(
921            io::ErrorKind::NotFound,
922            "Default Solana config was not found",
923        )
924    })?;
925    SolanaConfig::load(config_file).map(|config| config.json_rpc_url)
926}
927
928fn ser_programs(
929    programs: &BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>,
930) -> BTreeMap<String, BTreeMap<String, serde_json::Value>> {
931    programs
932        .iter()
933        .map(|(cluster, programs)| {
934            let cluster = cluster.to_string();
935            let programs = programs
936                .iter()
937                .map(|(name, deployment)| {
938                    (
939                        name.clone(),
940                        to_value(&_ProgramDeployment::from(deployment)),
941                    )
942                })
943                .collect::<BTreeMap<String, serde_json::Value>>();
944            (cluster, programs)
945        })
946        .collect::<BTreeMap<String, BTreeMap<String, serde_json::Value>>>()
947}
948
949fn to_value(dep: &_ProgramDeployment) -> serde_json::Value {
950    if dep.path.is_none() && dep.idl.is_none() {
951        return serde_json::Value::String(dep.address.to_string());
952    }
953    serde_json::to_value(dep).unwrap()
954}
955
956fn deser_programs(
957    programs: BTreeMap<String, BTreeMap<String, serde_json::Value>>,
958) -> Result<BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>> {
959    programs
960        .iter()
961        .map(|(cluster, programs)| {
962            let cluster: Cluster = cluster.parse()?;
963            let programs = programs
964                .iter()
965                .map(|(name, program_id)| {
966                    Ok((
967                        name.clone(),
968                        ProgramDeployment::try_from(match &program_id {
969                            serde_json::Value::String(address) => _ProgramDeployment {
970                                address: address.parse()?,
971                                path: None,
972                                idl: None,
973                            },
974
975                            serde_json::Value::Object(_) => {
976                                serde_json::from_value(program_id.clone())
977                                    .map_err(|_| anyhow!("Unable to read toml"))?
978                            }
979                            _ => return Err(anyhow!("Invalid toml type")),
980                        })?,
981                    ))
982                })
983                .collect::<Result<BTreeMap<String, ProgramDeployment>>>()?;
984            Ok((cluster, programs))
985        })
986        .collect::<Result<BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>>>()
987}
988
989#[derive(Default, Debug, Clone, Serialize, Deserialize)]
990pub struct TestValidator {
991    pub genesis: Option<Vec<GenesisEntry>>,
992    pub validator: Option<Validator>,
993    pub startup_wait: i32,
994    pub shutdown_wait: i32,
995    pub upgradeable: bool,
996}
997
998#[derive(Default, Debug, Clone, Serialize, Deserialize)]
999pub struct SurfpoolConfig {
1000    pub startup_wait: i32,
1001    pub shutdown_wait: i32,
1002    pub rpc_port: u16,
1003    pub ws_port: Option<u16>,
1004    pub host: String,
1005    pub online: Option<bool>,
1006    pub datasource_rpc_url: Option<String>,
1007    pub airdrop_addresses: Option<Vec<String>>,
1008    pub manifest_file_path: Option<String>,
1009    pub runbooks: Option<Vec<String>>,
1010    pub slot_time: Option<u16>,
1011    pub log_level: Option<String>,
1012    pub block_production_mode: Option<String>,
1013}
1014
1015#[derive(Default, Debug, Clone, Serialize, Deserialize)]
1016pub struct _TestValidator {
1017    #[serde(skip_serializing_if = "Option::is_none")]
1018    pub genesis: Option<Vec<GenesisEntry>>,
1019    #[serde(skip_serializing_if = "Option::is_none")]
1020    pub validator: Option<_Validator>,
1021    #[serde(skip_serializing_if = "Option::is_none")]
1022    pub startup_wait: Option<i32>,
1023    #[serde(skip_serializing_if = "Option::is_none")]
1024    pub shutdown_wait: Option<i32>,
1025    #[serde(skip_serializing_if = "Option::is_none")]
1026    pub upgradeable: Option<bool>,
1027}
1028
1029#[derive(Default, Debug, Clone, Serialize, Deserialize)]
1030pub struct _SurfpoolConfig {
1031    #[serde(skip_serializing_if = "Option::is_none")]
1032    pub startup_wait: Option<i32>,
1033    #[serde(skip_serializing_if = "Option::is_none")]
1034    pub shutdown_wait: Option<i32>,
1035    #[serde(skip_serializing_if = "Option::is_none")]
1036    pub rpc_port: Option<u16>,
1037    #[serde(skip_serializing_if = "Option::is_none")]
1038    pub ws_port: Option<u16>,
1039    #[serde(skip_serializing_if = "Option::is_none")]
1040    pub host: Option<String>,
1041    #[serde(skip_serializing_if = "Option::is_none")]
1042    pub online: Option<bool>,
1043    #[serde(skip_serializing_if = "Option::is_none")]
1044    pub datasource_rpc_url: Option<String>,
1045    #[serde(skip_serializing_if = "Option::is_none")]
1046    pub airdrop_addresses: Option<Vec<String>>,
1047    #[serde(skip_serializing_if = "Option::is_none")]
1048    pub manifest_file_path: Option<String>,
1049    #[serde(skip_serializing_if = "Option::is_none")]
1050    pub runbooks: Option<Vec<String>>,
1051    #[serde(skip_serializing_if = "Option::is_none")]
1052    pub slot_time: Option<u16>,
1053    #[serde(skip_serializing_if = "Option::is_none")]
1054    pub log_level: Option<String>,
1055    #[serde(skip_serializing_if = "Option::is_none")]
1056    pub block_production_mode: Option<String>,
1057}
1058
1059impl From<_SurfpoolConfig> for SurfpoolConfig {
1060    fn from(_surfpool_config: _SurfpoolConfig) -> Self {
1061        Self {
1062            startup_wait: _surfpool_config.startup_wait.unwrap_or(STARTUP_WAIT),
1063            shutdown_wait: _surfpool_config.shutdown_wait.unwrap_or(SHUTDOWN_WAIT),
1064            rpc_port: _surfpool_config.rpc_port.unwrap_or(DEFAULT_RPC_PORT),
1065            host: _surfpool_config.host.unwrap_or(SURFPOOL_HOST.to_string()),
1066            ws_port: _surfpool_config.ws_port,
1067            online: _surfpool_config.online,
1068            datasource_rpc_url: _surfpool_config.datasource_rpc_url,
1069            airdrop_addresses: _surfpool_config.airdrop_addresses,
1070            manifest_file_path: _surfpool_config.manifest_file_path,
1071            runbooks: _surfpool_config.runbooks,
1072            slot_time: _surfpool_config.slot_time,
1073            log_level: _surfpool_config.log_level,
1074            block_production_mode: _surfpool_config.block_production_mode,
1075        }
1076    }
1077}
1078
1079impl From<SurfpoolConfig> for _SurfpoolConfig {
1080    fn from(surfpool_config: SurfpoolConfig) -> Self {
1081        Self {
1082            startup_wait: Some(surfpool_config.startup_wait),
1083            shutdown_wait: Some(surfpool_config.shutdown_wait),
1084            rpc_port: Some(surfpool_config.rpc_port),
1085            ws_port: surfpool_config.ws_port,
1086            host: Some(surfpool_config.host),
1087            online: surfpool_config.online,
1088            datasource_rpc_url: surfpool_config.datasource_rpc_url,
1089            airdrop_addresses: surfpool_config.airdrop_addresses,
1090            manifest_file_path: surfpool_config.manifest_file_path,
1091            runbooks: surfpool_config.runbooks,
1092            slot_time: surfpool_config.slot_time,
1093            log_level: surfpool_config.log_level,
1094            block_production_mode: surfpool_config.block_production_mode,
1095        }
1096    }
1097}
1098pub const STARTUP_WAIT: i32 = 5000;
1099pub const SHUTDOWN_WAIT: i32 = 2000;
1100
1101impl From<_TestValidator> for TestValidator {
1102    fn from(_test_validator: _TestValidator) -> Self {
1103        Self {
1104            shutdown_wait: _test_validator.shutdown_wait.unwrap_or(SHUTDOWN_WAIT),
1105            startup_wait: _test_validator.startup_wait.unwrap_or(STARTUP_WAIT),
1106            genesis: _test_validator.genesis,
1107            validator: _test_validator.validator.map(Into::into),
1108            upgradeable: _test_validator.upgradeable.unwrap_or(false),
1109        }
1110    }
1111}
1112
1113impl From<TestValidator> for _TestValidator {
1114    fn from(test_validator: TestValidator) -> Self {
1115        Self {
1116            shutdown_wait: Some(test_validator.shutdown_wait),
1117            startup_wait: Some(test_validator.startup_wait),
1118            genesis: test_validator.genesis,
1119            validator: test_validator.validator.map(Into::into),
1120            upgradeable: Some(test_validator.upgradeable),
1121        }
1122    }
1123}
1124
1125#[derive(Debug, Clone)]
1126pub struct TestConfig {
1127    pub test_suite_configs: HashMap<PathBuf, TestToml>,
1128}
1129
1130impl Deref for TestConfig {
1131    type Target = HashMap<PathBuf, TestToml>;
1132
1133    fn deref(&self) -> &Self::Target {
1134        &self.test_suite_configs
1135    }
1136}
1137
1138impl TestConfig {
1139    pub fn discover(root: impl AsRef<Path>, test_paths: Vec<PathBuf>) -> Result<Option<Self>> {
1140        let walker = WalkDir::new(root).into_iter();
1141        let mut test_suite_configs = HashMap::new();
1142        for entry in walker.filter_entry(|e| !is_hidden(e)) {
1143            let entry = entry?;
1144            if entry.file_name() == "Test.toml" {
1145                let entry_path = entry.path();
1146                let test_toml = TestToml::from_path(entry_path)?;
1147                if test_paths.is_empty() || test_paths.iter().any(|p| entry_path.starts_with(p)) {
1148                    test_suite_configs.insert(entry.path().into(), test_toml);
1149                }
1150            }
1151        }
1152
1153        Ok(match test_suite_configs.is_empty() {
1154            true => None,
1155            false => Some(Self { test_suite_configs }),
1156        })
1157    }
1158}
1159
1160// This file needs to have the same (sub)structure as Anchor.toml
1161// so it can be parsed as a base test file from an Anchor.toml
1162#[derive(Debug, Clone, Serialize, Deserialize)]
1163pub struct _TestToml {
1164    pub extends: Option<Vec<String>>,
1165    pub test: Option<_TestValidator>,
1166    pub scripts: Option<ScriptsConfig>,
1167}
1168
1169impl _TestToml {
1170    fn from_path(path: impl AsRef<Path>) -> Result<Self, Error> {
1171        let s = fs::read_to_string(&path)?;
1172        let parsed_toml: Self = toml::from_str(&s)?;
1173        let mut current_toml = _TestToml {
1174            extends: None,
1175            test: None,
1176            scripts: None,
1177        };
1178        if let Some(bases) = &parsed_toml.extends {
1179            for base in bases {
1180                let mut canonical_base = base.clone();
1181                canonical_base = canonicalize_filepath_from_origin(&canonical_base, &path)?;
1182                current_toml.merge(_TestToml::from_path(&canonical_base)?);
1183            }
1184        }
1185        current_toml.merge(parsed_toml);
1186
1187        if let Some(test) = &mut current_toml.test {
1188            if let Some(genesis_programs) = &mut test.genesis {
1189                for entry in genesis_programs {
1190                    entry.program = canonicalize_filepath_from_origin(&entry.program, &path)?;
1191                }
1192            }
1193            if let Some(validator) = &mut test.validator {
1194                if let Some(accounts) = &mut validator.account {
1195                    for entry in accounts {
1196                        entry.filename = canonicalize_filepath_from_origin(&entry.filename, &path)?;
1197                    }
1198                }
1199                if let Some(account_dirs) = &mut validator.account_dir {
1200                    for entry in account_dirs {
1201                        entry.directory =
1202                            canonicalize_filepath_from_origin(&entry.directory, &path)?;
1203                    }
1204                }
1205            }
1206        }
1207        Ok(current_toml)
1208    }
1209}
1210
1211/// canonicalizes the `file_path` arg.
1212/// uses the `path` arg as the current dir
1213/// from which to turn the relative path
1214/// into a canonical one
1215fn canonicalize_filepath_from_origin(
1216    file_path: impl AsRef<Path>,
1217    origin: impl AsRef<Path>,
1218) -> Result<String> {
1219    let previous_dir = std::env::current_dir()?;
1220    std::env::set_current_dir(origin.as_ref().parent().unwrap())?;
1221    let result = fs::canonicalize(&file_path)
1222        .with_context(|| {
1223            format!(
1224                "Error reading (possibly relative) path: {}. If relative, this is the path that \
1225                 was used as the current path: {}",
1226                &file_path.as_ref().display(),
1227                &origin.as_ref().display()
1228            )
1229        })?
1230        .display()
1231        .to_string();
1232    std::env::set_current_dir(previous_dir)?;
1233    Ok(result)
1234}
1235
1236#[derive(Debug, Clone, Serialize, Deserialize)]
1237pub struct TestToml {
1238    #[serde(skip_serializing_if = "Option::is_none")]
1239    pub test: Option<TestValidator>,
1240    pub scripts: ScriptsConfig,
1241}
1242
1243impl TestToml {
1244    pub fn from_path(p: impl AsRef<Path>) -> Result<Self> {
1245        WithPath::new(_TestToml::from_path(&p)?, p.as_ref().into()).try_into()
1246    }
1247}
1248
1249impl Merge for _TestToml {
1250    fn merge(&mut self, other: Self) {
1251        let mut my_scripts = self.scripts.take();
1252        match &mut my_scripts {
1253            None => my_scripts = other.scripts,
1254            Some(my_scripts) => {
1255                if let Some(other_scripts) = other.scripts {
1256                    for (name, script) in other_scripts {
1257                        my_scripts.insert(name, script);
1258                    }
1259                }
1260            }
1261        }
1262
1263        let mut my_test = self.test.take();
1264        match &mut my_test {
1265            Some(my_test) => {
1266                if let Some(other_test) = other.test {
1267                    if let Some(startup_wait) = other_test.startup_wait {
1268                        my_test.startup_wait = Some(startup_wait);
1269                    }
1270                    if let Some(other_genesis) = other_test.genesis {
1271                        match &mut my_test.genesis {
1272                            Some(my_genesis) => {
1273                                for other_entry in other_genesis {
1274                                    match my_genesis
1275                                        .iter()
1276                                        .position(|g| *g.address == other_entry.address)
1277                                    {
1278                                        None => my_genesis.push(other_entry),
1279                                        Some(i) => my_genesis[i] = other_entry,
1280                                    }
1281                                }
1282                            }
1283                            None => my_test.genesis = Some(other_genesis),
1284                        }
1285                    }
1286                    let mut my_validator = my_test.validator.take();
1287                    match &mut my_validator {
1288                        None => my_validator = other_test.validator,
1289                        Some(my_validator) => {
1290                            if let Some(other_validator) = other_test.validator {
1291                                my_validator.merge(other_validator)
1292                            }
1293                        }
1294                    }
1295
1296                    my_test.validator = my_validator;
1297                }
1298            }
1299            None => my_test = other.test,
1300        };
1301
1302        // Instantiating a new Self object here ensures that
1303        // this function will fail to compile if new fields get added
1304        // to Self. This is useful as a reminder if they also require merging
1305        *self = Self {
1306            test: my_test,
1307            scripts: my_scripts,
1308            extends: self.extends.take(),
1309        };
1310    }
1311}
1312
1313impl TryFrom<WithPath<_TestToml>> for TestToml {
1314    type Error = Error;
1315
1316    fn try_from(mut value: WithPath<_TestToml>) -> Result<Self, Self::Error> {
1317        Ok(Self {
1318            test: value.test.take().map(Into::into),
1319            scripts: value
1320                .scripts
1321                .take()
1322                .ok_or_else(|| anyhow!("Missing 'scripts' section in Test.toml file."))?,
1323        })
1324    }
1325}
1326
1327#[derive(Debug, Clone, Serialize, Deserialize)]
1328pub struct GenesisEntry {
1329    // Base58 pubkey string.
1330    pub address: String,
1331    // Filepath to the compiled program to embed into the genesis.
1332    pub program: String,
1333    // Whether the genesis program is upgradeable.
1334    pub upgradeable: Option<bool>,
1335}
1336
1337#[derive(Debug, Clone, Serialize, Deserialize)]
1338pub struct CloneEntry {
1339    // Base58 pubkey string.
1340    pub address: String,
1341}
1342
1343#[derive(Debug, Clone, Serialize, Deserialize)]
1344pub struct AccountEntry {
1345    // Base58 pubkey string.
1346    pub address: String,
1347    // Name of JSON file containing the account data.
1348    pub filename: String,
1349}
1350
1351#[derive(Debug, Clone, Serialize, Deserialize)]
1352pub struct AccountDirEntry {
1353    // Directory containing account JSON files
1354    pub directory: String,
1355}
1356
1357#[derive(Debug, Clone, Serialize, Deserialize)]
1358pub struct FundedAccount {
1359    // Base58 pubkey string of the account to fund, or "new" to generate a random keypair
1360    pub address: String,
1361    // Amount of lamports to fund the account with (default: 1 SOL = 1_000_000_000 lamports)
1362    #[serde(skip_serializing_if = "Option::is_none")]
1363    pub lamports: Option<u64>,
1364}
1365
1366#[derive(Debug, Clone, Serialize, Deserialize)]
1367pub struct TokenMint {
1368    // Base58 pubkey string of the mint account, or "new" to generate a random keypair
1369    pub address: String,
1370    // Number of base 10 digits to the right of the decimal place (required)
1371    pub decimals: u8,
1372    // Initial supply of tokens (default: 0)
1373    #[serde(skip_serializing_if = "Option::is_none")]
1374    pub supply: Option<u64>,
1375    // Optional mint authority (default: None = fixed supply)
1376    #[serde(skip_serializing_if = "Option::is_none")]
1377    pub mint_authority: Option<String>,
1378    // Optional freeze authority (default: None = no freeze authority)
1379    #[serde(skip_serializing_if = "Option::is_none")]
1380    pub freeze_authority: Option<String>,
1381}
1382
1383#[derive(Debug, Clone, Serialize, Deserialize)]
1384pub struct TokenAccount {
1385    // Reference to mint (pubkey string or "new" to use the most recently created mint)
1386    pub mint: String,
1387    // Owner of the token account ("new" to generate random keypair, or specific pubkey)
1388    pub owner: String,
1389    // Amount of tokens to fund the account with
1390    pub amount: u64,
1391    // Optional: specific token account address (default: generate new)
1392    #[serde(skip_serializing_if = "Option::is_none")]
1393    pub address: Option<String>,
1394}
1395
1396#[derive(Debug, Default, Clone, Serialize, Deserialize)]
1397pub struct _Validator {
1398    // Load an account from the provided JSON file
1399    #[serde(skip_serializing_if = "Option::is_none")]
1400    pub account: Option<Vec<AccountEntry>>,
1401    // Load all the accounts from the JSON files found in the specified DIRECTORY
1402    #[serde(skip_serializing_if = "Option::is_none")]
1403    pub account_dir: Option<Vec<AccountDirEntry>>,
1404    // Generate and fund accounts with lamports
1405    #[serde(skip_serializing_if = "Option::is_none")]
1406    pub fund_accounts: Option<Vec<FundedAccount>>,
1407    // Create SPL token mints
1408    #[serde(skip_serializing_if = "Option::is_none")]
1409    pub mints: Option<Vec<TokenMint>>,
1410    // Create and fund SPL token accounts
1411    #[serde(skip_serializing_if = "Option::is_none")]
1412    pub token_accounts: Option<Vec<TokenAccount>>,
1413    // IP address to bind the validator ports. [default: 127.0.0.1]
1414    #[serde(skip_serializing_if = "Option::is_none")]
1415    pub bind_address: Option<String>,
1416    // Copy an account from the cluster referenced by the url argument.
1417    #[serde(skip_serializing_if = "Option::is_none")]
1418    pub clone: Option<Vec<CloneEntry>>,
1419    // Range to use for dynamically assigned ports. [default: 1024-65535]
1420    #[serde(skip_serializing_if = "Option::is_none")]
1421    pub dynamic_port_range: Option<String>,
1422    // Enable the faucet on this port [default: 9900].
1423    #[serde(skip_serializing_if = "Option::is_none")]
1424    pub faucet_port: Option<u16>,
1425    // Give the faucet address this much SOL in genesis. [default: 1000000]
1426    #[serde(skip_serializing_if = "Option::is_none")]
1427    pub faucet_sol: Option<String>,
1428    // Geyser plugin config location
1429    #[serde(skip_serializing_if = "Option::is_none")]
1430    pub geyser_plugin_config: Option<String>,
1431    // Gossip DNS name or IP address for the validator to advertise in gossip. [default: 127.0.0.1]
1432    #[serde(skip_serializing_if = "Option::is_none")]
1433    pub gossip_host: Option<String>,
1434    // Gossip port number for the validator
1435    #[serde(skip_serializing_if = "Option::is_none")]
1436    pub gossip_port: Option<u16>,
1437    // URL for Solana's JSON RPC or moniker.
1438    #[serde(skip_serializing_if = "Option::is_none")]
1439    pub url: Option<String>,
1440    // Use DIR as ledger location
1441    #[serde(skip_serializing_if = "Option::is_none")]
1442    pub ledger: Option<String>,
1443    // Keep this amount of shreds in root slots. [default: 10000]
1444    #[serde(skip_serializing_if = "Option::is_none")]
1445    pub limit_ledger_size: Option<String>,
1446    // Enable JSON RPC on this port, and the next port for the RPC websocket. [default: 8899]
1447    #[serde(skip_serializing_if = "Option::is_none")]
1448    pub rpc_port: Option<u16>,
1449    // Override the number of slots in an epoch.
1450    #[serde(skip_serializing_if = "Option::is_none")]
1451    pub slots_per_epoch: Option<String>,
1452    // The number of ticks in a slot
1453    #[serde(skip_serializing_if = "Option::is_none")]
1454    pub ticks_per_slot: Option<u16>,
1455    // Warp the ledger to WARP_SLOT after starting the validator.
1456    #[serde(skip_serializing_if = "Option::is_none")]
1457    pub warp_slot: Option<Slot>,
1458    // Deactivate one or more features.
1459    #[serde(skip_serializing_if = "Option::is_none")]
1460    pub deactivate_feature: Option<Vec<String>>,
1461    // Extra arguments to pass through to solana-test-validator.
1462    #[serde(skip_serializing_if = "Option::is_none")]
1463    pub extra_args: Option<Vec<String>>,
1464}
1465
1466#[derive(Debug, Default, Clone, Serialize, Deserialize)]
1467pub struct Validator {
1468    #[serde(skip_serializing_if = "Option::is_none")]
1469    pub account: Option<Vec<AccountEntry>>,
1470    #[serde(skip_serializing_if = "Option::is_none")]
1471    pub account_dir: Option<Vec<AccountDirEntry>>,
1472    #[serde(skip_serializing_if = "Option::is_none")]
1473    pub fund_accounts: Option<Vec<FundedAccount>>,
1474    #[serde(skip_serializing_if = "Option::is_none")]
1475    pub mints: Option<Vec<TokenMint>>,
1476    #[serde(skip_serializing_if = "Option::is_none")]
1477    pub token_accounts: Option<Vec<TokenAccount>>,
1478    pub bind_address: String,
1479    #[serde(skip_serializing_if = "Option::is_none")]
1480    pub clone: Option<Vec<CloneEntry>>,
1481    #[serde(skip_serializing_if = "Option::is_none")]
1482    pub dynamic_port_range: Option<String>,
1483    #[serde(skip_serializing_if = "Option::is_none")]
1484    pub faucet_port: Option<u16>,
1485    #[serde(skip_serializing_if = "Option::is_none")]
1486    pub faucet_sol: Option<String>,
1487    #[serde(skip_serializing_if = "Option::is_none")]
1488    pub geyser_plugin_config: Option<String>,
1489    #[serde(skip_serializing_if = "Option::is_none")]
1490    pub gossip_host: Option<String>,
1491    #[serde(skip_serializing_if = "Option::is_none")]
1492    pub gossip_port: Option<u16>,
1493    #[serde(skip_serializing_if = "Option::is_none")]
1494    pub url: Option<String>,
1495    pub ledger: String,
1496    #[serde(skip_serializing_if = "Option::is_none")]
1497    pub limit_ledger_size: Option<String>,
1498    pub rpc_port: u16,
1499    #[serde(skip_serializing_if = "Option::is_none")]
1500    pub slots_per_epoch: Option<String>,
1501    #[serde(skip_serializing_if = "Option::is_none")]
1502    pub ticks_per_slot: Option<u16>,
1503    #[serde(skip_serializing_if = "Option::is_none")]
1504    pub warp_slot: Option<Slot>,
1505    #[serde(skip_serializing_if = "Option::is_none")]
1506    pub deactivate_feature: Option<Vec<String>>,
1507    #[serde(skip_serializing_if = "Option::is_none")]
1508    pub extra_args: Option<Vec<String>>,
1509}
1510
1511impl From<_Validator> for Validator {
1512    fn from(_validator: _Validator) -> Self {
1513        Self {
1514            account: _validator.account,
1515            account_dir: _validator.account_dir,
1516            fund_accounts: _validator.fund_accounts,
1517            mints: _validator.mints,
1518            token_accounts: _validator.token_accounts,
1519            bind_address: _validator
1520                .bind_address
1521                .unwrap_or_else(|| DEFAULT_BIND_ADDRESS.to_string()),
1522            clone: _validator.clone,
1523            dynamic_port_range: _validator.dynamic_port_range,
1524            faucet_port: _validator.faucet_port,
1525            faucet_sol: _validator.faucet_sol,
1526            geyser_plugin_config: _validator.geyser_plugin_config,
1527            gossip_host: _validator.gossip_host,
1528            gossip_port: _validator.gossip_port,
1529            url: _validator.url,
1530            ledger: _validator
1531                .ledger
1532                .unwrap_or_else(|| get_default_ledger_path().display().to_string()),
1533            limit_ledger_size: _validator.limit_ledger_size,
1534            rpc_port: _validator.rpc_port.unwrap_or(DEFAULT_RPC_PORT),
1535            slots_per_epoch: _validator.slots_per_epoch,
1536            ticks_per_slot: _validator.ticks_per_slot,
1537            warp_slot: _validator.warp_slot,
1538            deactivate_feature: _validator.deactivate_feature,
1539            extra_args: _validator.extra_args,
1540        }
1541    }
1542}
1543
1544impl From<Validator> for _Validator {
1545    fn from(validator: Validator) -> Self {
1546        Self {
1547            account: validator.account,
1548            account_dir: validator.account_dir,
1549            fund_accounts: validator.fund_accounts,
1550            mints: validator.mints,
1551            token_accounts: validator.token_accounts,
1552            bind_address: Some(validator.bind_address),
1553            clone: validator.clone,
1554            dynamic_port_range: validator.dynamic_port_range,
1555            faucet_port: validator.faucet_port,
1556            faucet_sol: validator.faucet_sol,
1557            geyser_plugin_config: validator.geyser_plugin_config,
1558            gossip_host: validator.gossip_host,
1559            gossip_port: validator.gossip_port,
1560            url: validator.url,
1561            ledger: Some(validator.ledger),
1562            limit_ledger_size: validator.limit_ledger_size,
1563            rpc_port: Some(validator.rpc_port),
1564            slots_per_epoch: validator.slots_per_epoch,
1565            ticks_per_slot: validator.ticks_per_slot,
1566            warp_slot: validator.warp_slot,
1567            deactivate_feature: validator.deactivate_feature,
1568            extra_args: validator.extra_args,
1569        }
1570    }
1571}
1572
1573pub fn get_default_ledger_path() -> PathBuf {
1574    Path::new(".anchor").join("test-ledger")
1575}
1576
1577const DEFAULT_BIND_ADDRESS: &str = "127.0.0.1";
1578
1579fn is_generated_address(address: &str) -> bool {
1580    address.eq_ignore_ascii_case("new")
1581}
1582
1583fn explicit_token_account_address(address: Option<&str>) -> Option<&str> {
1584    match address {
1585        Some(address) if !is_generated_address(address) => Some(address),
1586        _ => None,
1587    }
1588}
1589
1590impl Merge for _Validator {
1591    fn merge(&mut self, other: Self) {
1592        // Instantiating a new Self object here ensures that
1593        // this function will fail to compile if new fields get added
1594        // to Self. This is useful as a reminder if they also require merging
1595        *self = Self {
1596            account: match self.account.take() {
1597                None => other.account,
1598                Some(mut entries) => match other.account {
1599                    None => Some(entries),
1600                    Some(other_entries) => {
1601                        for other_entry in other_entries {
1602                            match entries
1603                                .iter()
1604                                .position(|my_entry| *my_entry.address == other_entry.address)
1605                            {
1606                                None => entries.push(other_entry),
1607                                Some(i) => entries[i] = other_entry,
1608                            };
1609                        }
1610                        Some(entries)
1611                    }
1612                },
1613            },
1614            account_dir: match self.account_dir.take() {
1615                None => other.account_dir,
1616                Some(mut entries) => match other.account_dir {
1617                    None => Some(entries),
1618                    Some(other_entries) => {
1619                        for other_entry in other_entries {
1620                            match entries
1621                                .iter()
1622                                .position(|my_entry| *my_entry.directory == other_entry.directory)
1623                            {
1624                                None => entries.push(other_entry),
1625                                Some(i) => entries[i] = other_entry,
1626                            };
1627                        }
1628                        Some(entries)
1629                    }
1630                },
1631            },
1632            fund_accounts: match self.fund_accounts.take() {
1633                None => other.fund_accounts,
1634                Some(mut entries) => match other.fund_accounts {
1635                    None => Some(entries),
1636                    Some(other_entries) => {
1637                        for other_entry in other_entries {
1638                            match entries.iter().position(|my_entry| {
1639                                !is_generated_address(&my_entry.address)
1640                                    && !is_generated_address(&other_entry.address)
1641                                    && *my_entry.address == other_entry.address
1642                            }) {
1643                                None => entries.push(other_entry),
1644                                Some(i) => entries[i] = other_entry,
1645                            };
1646                        }
1647                        Some(entries)
1648                    }
1649                },
1650            },
1651            mints: match self.mints.take() {
1652                None => other.mints,
1653                Some(mut entries) => match other.mints {
1654                    None => Some(entries),
1655                    Some(other_entries) => {
1656                        for other_entry in other_entries {
1657                            match entries.iter().position(|my_entry| {
1658                                !is_generated_address(&my_entry.address)
1659                                    && !is_generated_address(&other_entry.address)
1660                                    && *my_entry.address == other_entry.address
1661                            }) {
1662                                None => entries.push(other_entry),
1663                                Some(i) => entries[i] = other_entry,
1664                            };
1665                        }
1666                        Some(entries)
1667                    }
1668                },
1669            },
1670            token_accounts: match self.token_accounts.take() {
1671                None => other.token_accounts,
1672                Some(mut entries) => match other.token_accounts {
1673                    None => Some(entries),
1674                    Some(other_entries) => {
1675                        // Generated token accounts do not have a stable merge key.
1676                        // Only explicitly addressed accounts override inherited entries.
1677                        for other_entry in other_entries {
1678                            match entries.iter().position(|my_entry| {
1679                                explicit_token_account_address(my_entry.address.as_deref())
1680                                    .zip(explicit_token_account_address(
1681                                        other_entry.address.as_deref(),
1682                                    ))
1683                                    .is_some_and(|(my_address, other_address)| {
1684                                        my_address == other_address
1685                                    })
1686                            }) {
1687                                None => entries.push(other_entry),
1688                                Some(i) => entries[i] = other_entry,
1689                            };
1690                        }
1691                        Some(entries)
1692                    }
1693                },
1694            },
1695            bind_address: other.bind_address.or_else(|| self.bind_address.take()),
1696            clone: match self.clone.take() {
1697                None => other.clone,
1698                Some(mut entries) => match other.clone {
1699                    None => Some(entries),
1700                    Some(other_entries) => {
1701                        for other_entry in other_entries {
1702                            match entries
1703                                .iter()
1704                                .position(|my_entry| *my_entry.address == other_entry.address)
1705                            {
1706                                None => entries.push(other_entry),
1707                                Some(i) => entries[i] = other_entry,
1708                            };
1709                        }
1710                        Some(entries)
1711                    }
1712                },
1713            },
1714            dynamic_port_range: other
1715                .dynamic_port_range
1716                .or_else(|| self.dynamic_port_range.take()),
1717            faucet_port: other.faucet_port.or_else(|| self.faucet_port.take()),
1718            faucet_sol: other.faucet_sol.or_else(|| self.faucet_sol.take()),
1719            geyser_plugin_config: other
1720                .geyser_plugin_config
1721                .or_else(|| self.geyser_plugin_config.take()),
1722            gossip_host: other.gossip_host.or_else(|| self.gossip_host.take()),
1723            gossip_port: other.gossip_port.or_else(|| self.gossip_port.take()),
1724            url: other.url.or_else(|| self.url.take()),
1725            ledger: other.ledger.or_else(|| self.ledger.take()),
1726            limit_ledger_size: other
1727                .limit_ledger_size
1728                .or_else(|| self.limit_ledger_size.take()),
1729            rpc_port: other.rpc_port.or_else(|| self.rpc_port.take()),
1730            slots_per_epoch: other
1731                .slots_per_epoch
1732                .or_else(|| self.slots_per_epoch.take()),
1733            ticks_per_slot: other.ticks_per_slot.or_else(|| self.ticks_per_slot.take()),
1734            warp_slot: other.warp_slot.or_else(|| self.warp_slot.take()),
1735            deactivate_feature: other
1736                .deactivate_feature
1737                .or_else(|| self.deactivate_feature.take()),
1738            extra_args: match self.extra_args.take() {
1739                None => other.extra_args,
1740                Some(mut args) => {
1741                    if let Some(other_args) = other.extra_args {
1742                        args.extend(other_args);
1743                    }
1744                    Some(args)
1745                }
1746            },
1747        };
1748    }
1749}
1750
1751#[derive(Debug, Clone)]
1752pub struct Program {
1753    pub lib_name: String,
1754    // Canonicalized path to the program directory
1755    pub path: PathBuf,
1756    pub idl: Option<Idl>,
1757}
1758
1759impl Program {
1760    pub fn pubkey(&self) -> Result<Pubkey> {
1761        self.keypair().map(|kp| kp.pubkey())
1762    }
1763
1764    pub fn keypair(&self) -> Result<Keypair> {
1765        let file = self.keypair_file()?;
1766        get_keypair(file.path())
1767    }
1768
1769    // Lazily initializes the keypair file with a new key if it doesn't exist.
1770    pub fn keypair_file(&self) -> Result<WithPath<File>> {
1771        let deploy_dir_path = target_dir()?.join("deploy");
1772        fs::create_dir_all(&deploy_dir_path)
1773            .with_context(|| format!("Error creating directory with path: {deploy_dir_path:?}"))?;
1774        let path = std::env::current_dir()
1775            .expect("Must have current dir")
1776            .join(deploy_dir_path.join(format!("{}-keypair.json", self.lib_name)));
1777        if path.exists() {
1778            return Ok(WithPath::new(
1779                File::open(&path)
1780                    .with_context(|| format!("Error opening file with path: {}", path.display()))?,
1781                path,
1782            ));
1783        }
1784        let program_kp = Keypair::new();
1785        let mut file = File::create(&path)
1786            .with_context(|| format!("Error creating file with path: {}", path.display()))?;
1787        file.write_all(format!("{:?}", &program_kp.to_bytes()).as_bytes())?;
1788        Ok(WithPath::new(file, path))
1789    }
1790
1791    pub fn binary_path(&self, verifiable: bool) -> Result<PathBuf> {
1792        let path = target_dir()?
1793            .join(if verifiable { "verifiable" } else { "deploy" })
1794            .join(&self.lib_name)
1795            .with_extension("so");
1796
1797        Ok(std::env::current_dir()
1798            .expect("Must have current dir")
1799            .join(path))
1800    }
1801}
1802
1803#[derive(Debug, Default)]
1804pub struct ProgramDeployment {
1805    pub address: Pubkey,
1806    pub path: Option<String>,
1807    pub idl: Option<String>,
1808}
1809
1810impl TryFrom<_ProgramDeployment> for ProgramDeployment {
1811    type Error = anyhow::Error;
1812    fn try_from(pd: _ProgramDeployment) -> Result<Self, Self::Error> {
1813        Ok(ProgramDeployment {
1814            address: pd.address.parse()?,
1815            path: pd.path,
1816            idl: pd.idl,
1817        })
1818    }
1819}
1820
1821#[derive(Debug, Default, Serialize, Deserialize)]
1822pub struct _ProgramDeployment {
1823    pub address: String,
1824    pub path: Option<String>,
1825    pub idl: Option<String>,
1826}
1827
1828impl From<&ProgramDeployment> for _ProgramDeployment {
1829    fn from(pd: &ProgramDeployment) -> Self {
1830        Self {
1831            address: pd.address.to_string(),
1832            path: pd.path.clone(),
1833            idl: pd.idl.clone(),
1834        }
1835    }
1836}
1837
1838pub struct ProgramWorkspace {
1839    pub name: String,
1840    pub program_id: Pubkey,
1841    pub idl: Idl,
1842}
1843
1844#[derive(Debug, Serialize, Deserialize)]
1845pub struct AnchorPackage {
1846    pub name: String,
1847    pub address: String,
1848    pub idl: Option<String>,
1849}
1850
1851impl AnchorPackage {
1852    pub fn from(name: String, cfg: &WithPath<Config>) -> Result<Self> {
1853        let cluster = &cfg.provider.cluster;
1854        if cluster != &Cluster::Mainnet {
1855            return Err(anyhow!("Publishing requires the mainnet cluster"));
1856        }
1857        let program_details = cfg
1858            .programs
1859            .get(cluster)
1860            .ok_or_else(|| anyhow!("Program not provided in Anchor.toml"))?
1861            .get(&name)
1862            .ok_or_else(|| anyhow!("Program not provided in Anchor.toml"))?;
1863        let idl = program_details.idl.clone();
1864        let address = program_details.address.to_string();
1865        Ok(Self { name, address, idl })
1866    }
1867}
1868
1869#[derive(Debug, Serialize, Deserialize)]
1870#[serde(rename_all = "camelCase")]
1871pub struct SurfnetInfoResponse {
1872    pub runbook_executions: Vec<RunbookExecution>,
1873}
1874#[derive(Debug, Serialize, Deserialize)]
1875#[serde(rename_all = "camelCase")]
1876pub struct RunbookExecution {
1877    #[serde(rename = "startedAt")]
1878    pub started_at: u32,
1879    #[serde(rename = "completedAt")]
1880    pub completed_at: Option<u32>,
1881    #[serde(rename = "runbookId")]
1882    pub runbook_id: String,
1883    pub errors: Option<Vec<String>>,
1884}
1885
1886#[macro_export]
1887macro_rules! home_path {
1888    ($my_struct:ident, $path:literal) => {
1889        #[derive(Clone, Debug, AbsolutePath)]
1890        pub struct $my_struct(::std::path::PathBuf);
1891
1892        impl Default for $my_struct {
1893            fn default() -> Self {
1894                $my_struct(home_dir().unwrap().join($path))
1895            }
1896        }
1897
1898        impl $my_struct {
1899            fn stringify_with_tilde(&self) -> String {
1900                self.0
1901                    .display()
1902                    .to_string()
1903                    .replacen(home_dir().unwrap().to_str().unwrap(), "~", 1)
1904            }
1905        }
1906
1907        impl FromStr for $my_struct {
1908            type Err = anyhow::Error;
1909
1910            fn from_str(s: &str) -> Result<Self, Self::Err> {
1911                Ok(Self(::std::path::PathBuf::from(s)))
1912            }
1913        }
1914
1915        impl fmt::Display for $my_struct {
1916            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1917                write!(f, "{}", self.0.display())
1918            }
1919        }
1920    };
1921}
1922
1923home_path!(WalletPath, ".config/solana/id.json");
1924
1925#[cfg(test)]
1926mod tests {
1927    use super::*;
1928
1929    const BASE_CONFIG: &str = "
1930        [provider]
1931        cluster = \"localnet\"
1932        wallet = \"id.json\"
1933    ";
1934
1935    #[test]
1936    fn parse_custom_cluster_str() {
1937        let config = Config::from_str(
1938            "
1939        [provider]
1940        cluster = \"http://my-url.com\"
1941        wallet = \"id.json\"
1942    ",
1943        )
1944        .unwrap();
1945        assert!(!config.features.skip_lint);
1946
1947        // Make sure the layout of `provider.cluster` stays the same after serialization
1948        assert!(config
1949            .to_string()
1950            .contains(r#"cluster = "http://my-url.com""#));
1951    }
1952
1953    #[test]
1954    fn parse_custom_cluster_map() {
1955        let config = Config::from_str(
1956            "
1957        [provider]
1958        cluster = { http = \"http://my-url.com\", ws = \"ws://my-url.com\" }
1959        wallet = \"id.json\"
1960    ",
1961        )
1962        .unwrap();
1963        assert!(!config.features.skip_lint);
1964    }
1965
1966    #[test]
1967    fn parse_skip_lint_no_section() {
1968        let config = Config::from_str(BASE_CONFIG).unwrap();
1969        assert!(!config.features.skip_lint);
1970    }
1971
1972    #[test]
1973    fn parse_fund_accounts_config() {
1974        let config_str = r#"
1975        [provider]
1976        cluster = "localnet"
1977        wallet = "id.json"
1978
1979        [test.validator]
1980        [[test.validator.fund_accounts]]
1981        address = "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM"
1982        lamports = 2000000000
1983
1984        [[test.validator.fund_accounts]]
1985        address = "GjJyeC1rB1hL8ZkLqKqJzJzJzJzJzJzJzJzJzJzJzJzJz"
1986        "#;
1987
1988        let config = Config::from_str(config_str).unwrap();
1989        assert!(config.test_validator.is_some());
1990        let test_validator = config.test_validator.as_ref().unwrap();
1991        assert!(test_validator.validator.is_some());
1992        let validator = test_validator.validator.as_ref().unwrap();
1993        assert!(validator.fund_accounts.is_some());
1994
1995        let fund_accounts = validator.fund_accounts.as_ref().unwrap();
1996        assert_eq!(fund_accounts.len(), 2);
1997        assert_eq!(
1998            fund_accounts[0].address,
1999            "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM"
2000        );
2001        assert_eq!(fund_accounts[0].lamports, Some(2000000000));
2002        assert_eq!(
2003            fund_accounts[1].address,
2004            "GjJyeC1rB1hL8ZkLqKqJzJzJzJzJzJzJzJzJzJzJzJzJz"
2005        );
2006        assert_eq!(fund_accounts[1].lamports, None); // Should default to 1 SOL
2007    }
2008
2009    #[test]
2010    fn parse_fund_accounts_without_lamports() {
2011        let config_str = r#"
2012        [provider]
2013        cluster = "localnet"
2014        wallet = "id.json"
2015
2016        [test.validator]
2017        [[test.validator.fund_accounts]]
2018        address = "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM"
2019        "#;
2020
2021        let config = Config::from_str(config_str).unwrap();
2022        let fund_accounts = config
2023            .test_validator
2024            .as_ref()
2025            .unwrap()
2026            .validator
2027            .as_ref()
2028            .unwrap()
2029            .fund_accounts
2030            .as_ref()
2031            .unwrap();
2032        assert_eq!(fund_accounts.len(), 1);
2033        assert_eq!(fund_accounts[0].lamports, None);
2034    }
2035
2036    #[test]
2037    fn test_toml_extends_preserves_generated_validator_accounts() {
2038        let dir = tempfile::tempdir().unwrap();
2039        let suite_dir = dir.path().join("tests").join("suite");
2040        fs::create_dir_all(&suite_dir).unwrap();
2041
2042        let base_toml = suite_dir.join("Base.toml");
2043        fs::write(
2044            &base_toml,
2045            r#"
2046[scripts]
2047test = "true"
2048
2049[[test.validator.fund_accounts]]
2050address = "new"
2051lamports = 1
2052
2053[[test.validator.mints]]
2054address = "new"
2055decimals = 6
2056
2057[[test.validator.token_accounts]]
2058mint = "new"
2059owner = "new"
2060amount = 1
2061"#,
2062        )
2063        .unwrap();
2064
2065        let test_toml = suite_dir.join("Test.toml");
2066        fs::write(
2067            &test_toml,
2068            r#"
2069extends = ["Base.toml"]
2070
2071[scripts]
2072test = "true"
2073
2074[[test.validator.fund_accounts]]
2075address = "new"
2076lamports = 2
2077
2078[[test.validator.mints]]
2079address = "new"
2080decimals = 9
2081
2082[[test.validator.token_accounts]]
2083mint = "new"
2084owner = "new"
2085amount = 2
2086"#,
2087        )
2088        .unwrap();
2089
2090        let parsed = TestToml::from_path(test_toml).unwrap();
2091        let validator = parsed.test.unwrap().validator.unwrap();
2092
2093        let fund_accounts = validator.fund_accounts.unwrap();
2094        assert_eq!(fund_accounts.len(), 2);
2095        assert_eq!(fund_accounts[0].lamports, Some(1));
2096        assert_eq!(fund_accounts[1].lamports, Some(2));
2097
2098        let mints = validator.mints.unwrap();
2099        assert_eq!(mints.len(), 2);
2100        assert_eq!(mints[0].decimals, 6);
2101        assert_eq!(mints[1].decimals, 9);
2102
2103        let token_accounts = validator.token_accounts.unwrap();
2104        assert_eq!(token_accounts.len(), 2);
2105        assert_eq!(token_accounts[0].amount, 1);
2106        assert_eq!(token_accounts[1].amount, 2);
2107    }
2108
2109    #[test]
2110    fn parse_skip_lint_no_value() {
2111        let string = BASE_CONFIG.to_owned() + "[features]";
2112        let config = Config::from_str(&string).unwrap();
2113        assert!(!config.features.skip_lint);
2114    }
2115
2116    #[test]
2117    fn parse_skip_lint_true() {
2118        let string = BASE_CONFIG.to_owned() + "[features]\nskip-lint = true";
2119        let config = Config::from_str(&string).unwrap();
2120        assert!(config.features.skip_lint);
2121    }
2122
2123    #[test]
2124    fn parse_clients_section() {
2125        let toml = BASE_CONFIG.to_owned()
2126            + r#"
2127[clients]
2128auto = true
2129rust = true
2130js = false
2131js-umi = { enable = true }
2132go = { enable = true, path = "go-client" }
2133"#;
2134        let config = Config::from_str(&toml).unwrap();
2135        let clients = &config.clients;
2136        assert!(clients.auto);
2137        assert!(clients.rust.as_ref().unwrap().is_enabled());
2138        assert!(!clients.js.as_ref().unwrap().is_enabled());
2139        assert!(clients.js_umi.as_ref().unwrap().is_enabled());
2140        let go = clients.go.as_ref().unwrap();
2141        assert!(go.is_enabled());
2142        assert_eq!(go.path(), Some("go-client"));
2143
2144        let workspace_dir = Path::new("workspace");
2145        let resolved = clients.enabled(workspace_dir);
2146        assert_eq!(
2147            resolved,
2148            vec![
2149                ("js-umi", workspace_dir.join("clients/js-umi")),
2150                ("rust", workspace_dir.join("clients/rust")),
2151                ("go", workspace_dir.join("go-client")),
2152            ]
2153        );
2154    }
2155
2156    #[test]
2157    fn clients_custom_paths_resolve_from_workspace_root() {
2158        let workspace_dir = Path::new("workspace-root");
2159        let clients = ClientsConfig {
2160            rust: Some(ClientLanguageConfig::Detailed {
2161                enable: true,
2162                path: Some("sdk/rust".to_owned()),
2163            }),
2164            go: Some(ClientLanguageConfig::Detailed {
2165                enable: true,
2166                path: Some("/tmp/go-client".to_owned()),
2167            }),
2168            ..Default::default()
2169        };
2170
2171        let resolved = clients.enabled(workspace_dir);
2172        assert_eq!(
2173            resolved,
2174            vec![
2175                ("rust", workspace_dir.join("sdk/rust")),
2176                ("go", PathBuf::from("/tmp/go-client")),
2177            ]
2178        );
2179    }
2180
2181    #[test]
2182    fn clients_section_round_trips() {
2183        let toml = BASE_CONFIG.to_owned()
2184            + r#"
2185[clients]
2186auto = true
2187rust = true
2188go = { enable = true, path = "go-client" }
2189"#;
2190        let config = Config::from_str(&toml).unwrap();
2191        let serialized = config.to_string();
2192        let reparsed = Config::from_str(&serialized).unwrap();
2193        assert!(reparsed.clients.auto);
2194        assert!(reparsed.clients.rust.as_ref().unwrap().is_enabled());
2195        assert_eq!(
2196            reparsed.clients.go.as_ref().and_then(|go| go.path()),
2197            Some("go-client"),
2198        );
2199    }
2200
2201    #[test]
2202    fn clients_section_omitted_when_default() {
2203        let config = Config::from_str(BASE_CONFIG).unwrap();
2204        assert!(!config.to_string().contains("[clients]"));
2205    }
2206
2207    #[test]
2208    fn unknown_clients_fields_are_ignored_for_compatibility() {
2209        let toml = BASE_CONFIG.to_owned()
2210            + r#"
2211[clients]
2212python = true
2213metadata = { owner = "sdk-team" }
2214rust = true
2215"#;
2216        let config = Config::from_str(&toml).unwrap();
2217
2218        assert!(config.clients.rust.as_ref().unwrap().is_enabled());
2219    }
2220
2221    #[test]
2222    fn skip_local_validator_round_trips() {
2223        let toml = "skip_local_validator = true\n".to_owned() + BASE_CONFIG;
2224        let config = Config::from_str(&toml).unwrap();
2225        assert_eq!(config.skip_local_validator, Some(true));
2226        let serialized = config.to_string();
2227        assert!(serialized.contains("skip_local_validator = true"));
2228    }
2229
2230    #[test]
2231    fn test_validator_extra_args_round_trips() {
2232        let toml = BASE_CONFIG.to_owned()
2233            + r#"
2234[test.validator]
2235extra_args = [
2236    "--rpc-pubsub-enable-block-subscription",
2237    "--geyser-plugin-config",
2238    "geyser.json",
2239]
2240"#;
2241        let config = Config::from_str(&toml).unwrap();
2242        let extra_args = config
2243            .test_validator
2244            .as_ref()
2245            .and_then(|test| test.validator.as_ref())
2246            .and_then(|validator| validator.extra_args.as_ref())
2247            .unwrap();
2248
2249        assert_eq!(
2250            extra_args,
2251            &vec![
2252                "--rpc-pubsub-enable-block-subscription".to_string(),
2253                "--geyser-plugin-config".to_string(),
2254                "geyser.json".to_string(),
2255            ]
2256        );
2257
2258        let serialized = config.to_string();
2259        let reparsed = Config::from_str(&serialized).unwrap();
2260        let reparsed_extra_args = reparsed
2261            .test_validator
2262            .as_ref()
2263            .and_then(|test| test.validator.as_ref())
2264            .and_then(|validator| validator.extra_args.as_ref())
2265            .unwrap();
2266        assert_eq!(reparsed_extra_args, extra_args);
2267    }
2268
2269    #[test]
2270    fn parse_skip_lint_false() {
2271        let string = BASE_CONFIG.to_owned() + "[features]\nskip-lint = false";
2272        let config = Config::from_str(&string).unwrap();
2273        assert!(!config.features.skip_lint);
2274    }
2275
2276    #[test]
2277    fn test_toml_resolves_account_dir_relative_to_file() {
2278        let dir = tempfile::tempdir().unwrap();
2279        let suite_dir = dir.path().join("tests").join("suite");
2280        let accounts_dir = suite_dir.join("accounts");
2281        fs::create_dir_all(&accounts_dir).unwrap();
2282
2283        let account_file = accounts_dir.join("account.json");
2284        fs::write(&account_file, "{}").unwrap();
2285
2286        let test_toml = suite_dir.join("Test.toml");
2287        fs::write(
2288            &test_toml,
2289            r#"
2290[scripts]
2291test = "true"
2292
2293[[test.validator.account]]
2294address = "3vMPj13emX9JmifYcWc77ekEzV1F37ga36E1YeSr6Mdj"
2295filename = "accounts/account.json"
2296
2297[[test.validator.account_dir]]
2298directory = "accounts"
2299"#,
2300        )
2301        .unwrap();
2302
2303        let parsed = TestToml::from_path(test_toml).unwrap();
2304        let validator = parsed.test.unwrap().validator.unwrap();
2305
2306        assert_eq!(
2307            validator.account.unwrap()[0].filename,
2308            account_file.canonicalize().unwrap().display().to_string()
2309        );
2310        assert_eq!(
2311            validator.account_dir.unwrap()[0].directory,
2312            accounts_dir.canonicalize().unwrap().display().to_string()
2313        );
2314    }
2315
2316    #[test]
2317    fn test_toml_keeps_ledger_path_relative() {
2318        let dir = tempfile::tempdir().unwrap();
2319        let suite_dir = dir.path().join("tests").join("suite");
2320        fs::create_dir_all(&suite_dir).unwrap();
2321
2322        let test_toml = suite_dir.join("Test.toml");
2323        fs::write(
2324            &test_toml,
2325            r#"
2326[scripts]
2327test = "true"
2328
2329[test.validator]
2330ledger = "ledgers/local"
2331"#,
2332        )
2333        .unwrap();
2334
2335        let parsed = TestToml::from_path(test_toml).unwrap();
2336        let validator = parsed.test.unwrap().validator.unwrap();
2337
2338        assert_eq!(validator.ledger, "ledgers/local");
2339
2340        fs::create_dir_all(suite_dir.join("ledgers").join("local")).unwrap();
2341
2342        let test_toml = suite_dir.join("Test.toml");
2343        let parsed = TestToml::from_path(test_toml).unwrap();
2344        let validator = parsed.test.unwrap().validator.unwrap();
2345
2346        assert_eq!(validator.ledger, "ledgers/local");
2347    }
2348}