From 1f872205e17a3093b1ddb09a873c5f7bc9144b26 Mon Sep 17 00:00:00 2001 From: Paul Schaaf Date: Fri, 17 Dec 2021 19:19:32 +0100 Subject: [PATCH 01/11] cli__working_but_not_optimised_version --- Cargo.lock | 1 + cli/Cargo.toml | 1 + cli/src/lib.rs | 134 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 136 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 5bc25af164..a3128b5f5e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -152,6 +152,7 @@ dependencies = [ "anchor-syn", "anyhow", "cargo_toml", + "chrono", "clap 3.0.0-beta.4", "dirs", "flate2", diff --git a/cli/Cargo.toml b/cli/Cargo.toml index e1f652b1f7..25b8c292d1 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -38,3 +38,4 @@ tokio = "1.0" pathdiff = "0.2.0" cargo_toml = "0.9.2" walkdir = "2" +chrono = "0.4.19" diff --git a/cli/src/lib.rs b/cli/src/lib.rs index 731fba13cd..d3bb2eaf0c 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -33,6 +33,7 @@ use solana_sdk::sysvar; use solana_sdk::transaction::Transaction; use std::collections::BTreeMap; use std::collections::HashMap; +use std::ffi::OsString; use std::fs::{self, File}; use std::io::prelude::*; use std::path::{Path, PathBuf}; @@ -97,6 +98,20 @@ pub enum Command { )] cargo_args: Vec, }, + /// Expands macros (wrapper around cargo expand) + Expand { + /// Only expands this program + #[clap(short, long)] + program_name: Option, + /// Arguments to pass to the underlying `cargo expand` command + #[clap( + required = false, + takes_value = true, + multiple_values = true, + last = true + )] + cargo_args: Vec, + }, /// 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. @@ -370,6 +385,10 @@ pub fn entry(opts: Opts) -> Result<()> { cargo_args, ), Command::Deploy { program_name } => deploy(&opts.cfg_override, program_name), + Command::Expand { + program_name, + cargo_args, + } => expand(&opts.cfg_override, program_name, &cargo_args), Command::Upgrade { program_id, program_filepath, @@ -559,6 +578,121 @@ fn new_program(name: &str) -> Result<()> { Ok(()) } +pub fn expand( + cfg_override: &ConfigOverride, + program_name: Option, + cargo_args: &[String], +) -> Result<()> { + // Change to the workspace member directory, if needed. + if let Some(program_name) = program_name.as_ref() { + cd_member(cfg_override, program_name)?; + } + + println!("current dir: {:?}", std::env::current_dir().unwrap()); + + let workspace_cfg = Config::discover(cfg_override)?.expect("Not in workspace."); + let cfg_parent = workspace_cfg.path().parent().expect("Invalid Anchor.toml"); + let cargo = Manifest::discover()?; + + println!("cargo path: {:?}", cargo.as_ref().unwrap().path()); + + let expansions_path = cfg_parent.join(".anchor/expanded-macros"); + fs::create_dir_all(&expansions_path)?; + + match cargo { + // No Cargo.toml found, expand entire workspace + None => expand_all(&workspace_cfg, cargo_args), + // Cargo.toml is at root of workspace, expand entire workspace + Some(cargo) if cargo.path().parent() == workspace_cfg.path().parent() => { + expand_all(&workspace_cfg, cargo_args) + } + // Reaching this arm means Cargo.toml belongs to a single package. Expand it. + Some(cargo) => { + println!("hello"); + expand_program( + &workspace_cfg, + cargo.path().parent().unwrap().to_path_buf(), + cargo_args, + ) + } + } +} + +fn expand_all(workspace_cfg: &WithPath, cargo_args: &[String]) -> Result<()> { + let cur_dir = std::env::current_dir()?; + let r = match workspace_cfg.path().parent() { + None => Err(anyhow!( + "Invalid Anchor.toml at {}", + workspace_cfg.path().display() + )), + Some(_parent) => { + for p in workspace_cfg.get_program_list()? { + expand_program(workspace_cfg, p, cargo_args)?; + } + Ok(()) + } + }; + std::env::set_current_dir(cur_dir)?; + r +} + +fn expand_program( + workspace_cfg: &WithPath, + program_path: PathBuf, + cargo_args: &[String], +) -> Result<()> { + //println!("{:?}", workspace_cfg); + println!("{:?}", program_path); + let workspace_cfg_parent = workspace_cfg.path().parent().unwrap(); + + let cargo = Manifest::from_path(program_path.join("Cargo.toml")) + .map_err(|_| anyhow!("Could not find Cargo.toml for program"))?; + + let target_dir = { + let mut target_dir = OsString::from("--target-dir="); + target_dir.push( + workspace_cfg_parent + .join(".anchor/expanded-macros") + .join(&(*cargo).package.as_ref().unwrap().name) + .join("expand-target"), + ); + target_dir + }; + + let package = format!("--package={}", cargo.package.as_ref().unwrap().name); + + let program_expansions_path = workspace_cfg_parent + .join(".anchor/expanded-macros") + .join(&cargo.package.as_ref().unwrap().name) + .join("expansions"); + fs::create_dir_all(&program_expansions_path)?; + + let exit = std::process::Command::new("cargo") + .arg("expand") + .arg(target_dir) + .arg(&package) + .args(cargo_args) + .stderr(Stdio::inherit()) + .output() + .map_err(|e| anyhow::format_err!("{}", e.to_string()))?; + if !exit.status.success() { + std::process::exit(exit.status.code().unwrap_or(1)); + } + + let version = cargo.version(); + let time = chrono::Utc::now().to_string().replace(" ", "_"); + fs::write( + program_expansions_path.join(format!( + "{}-{}-{}.rs", + (*cargo).package.as_ref().unwrap().name, + version, + time + )), + &exit.stdout, + ) + .map_err(|e| anyhow::format_err!("{}", e.to_string())) +} + #[allow(clippy::too_many_arguments)] pub fn build( cfg_override: &ConfigOverride, From c3b5fb634419bc953326fad53e8d1bd7329fa58f Mon Sep 17 00:00:00 2001 From: Paul Schaaf Date: Fri, 17 Dec 2021 19:22:42 +0100 Subject: [PATCH 02/11] cli: remove printlns --- cli/src/lib.rs | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/cli/src/lib.rs b/cli/src/lib.rs index d3bb2eaf0c..e5368ae421 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -588,14 +588,10 @@ pub fn expand( cd_member(cfg_override, program_name)?; } - println!("current dir: {:?}", std::env::current_dir().unwrap()); - let workspace_cfg = Config::discover(cfg_override)?.expect("Not in workspace."); let cfg_parent = workspace_cfg.path().parent().expect("Invalid Anchor.toml"); let cargo = Manifest::discover()?; - println!("cargo path: {:?}", cargo.as_ref().unwrap().path()); - let expansions_path = cfg_parent.join(".anchor/expanded-macros"); fs::create_dir_all(&expansions_path)?; @@ -607,14 +603,11 @@ pub fn expand( expand_all(&workspace_cfg, cargo_args) } // Reaching this arm means Cargo.toml belongs to a single package. Expand it. - Some(cargo) => { - println!("hello"); - expand_program( - &workspace_cfg, - cargo.path().parent().unwrap().to_path_buf(), - cargo_args, - ) - } + Some(cargo) => expand_program( + &workspace_cfg, + cargo.path().parent().unwrap().to_path_buf(), + cargo_args, + ), } } @@ -641,8 +634,6 @@ fn expand_program( program_path: PathBuf, cargo_args: &[String], ) -> Result<()> { - //println!("{:?}", workspace_cfg); - println!("{:?}", program_path); let workspace_cfg_parent = workspace_cfg.path().parent().unwrap(); let cargo = Manifest::from_path(program_path.join("Cargo.toml")) From e873a0fd3fea0709ef54ca79737aeafb76def626 Mon Sep 17 00:00:00 2001 From: Paul Schaaf Date: Fri, 17 Dec 2021 19:38:37 +0100 Subject: [PATCH 03/11] cli: use a singe target folder for all expanded programs --- cli/src/lib.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cli/src/lib.rs b/cli/src/lib.rs index e5368ae421..6cff31a7c7 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -644,7 +644,6 @@ fn expand_program( target_dir.push( workspace_cfg_parent .join(".anchor/expanded-macros") - .join(&(*cargo).package.as_ref().unwrap().name) .join("expand-target"), ); target_dir @@ -671,7 +670,7 @@ fn expand_program( } let version = cargo.version(); - let time = chrono::Utc::now().to_string().replace(" ", "_"); + let time = chrono::Utc::now().to_string().replace(' ', "_"); fs::write( program_expansions_path.join(format!( "{}-{}-{}.rs", From e24e3db4f05532f801b8caf3f97d458a285c0f83 Mon Sep 17 00:00:00 2001 From: Paul Schaaf Date: Fri, 17 Dec 2021 19:59:42 +0100 Subject: [PATCH 04/11] cli: refactoring --- cli/src/lib.rs | 28 ++++++++++------------------ 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/cli/src/lib.rs b/cli/src/lib.rs index 6cff31a7c7..832bc90745 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -48,6 +48,8 @@ pub mod template; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub const DOCKER_BUILDER_VERSION: &str = VERSION; +const EXPANDED_MACROS_PATH: &str = ".anchor/expanded-macros"; + #[derive(Debug, Clap)] #[clap(version = VERSION)] pub struct Opts { @@ -592,7 +594,7 @@ pub fn expand( let cfg_parent = workspace_cfg.path().parent().expect("Invalid Anchor.toml"); let cargo = Manifest::discover()?; - let expansions_path = cfg_parent.join(".anchor/expanded-macros"); + let expansions_path = cfg_parent.join(EXPANDED_MACROS_PATH); fs::create_dir_all(&expansions_path)?; match cargo { @@ -613,20 +615,11 @@ pub fn expand( fn expand_all(workspace_cfg: &WithPath, cargo_args: &[String]) -> Result<()> { let cur_dir = std::env::current_dir()?; - let r = match workspace_cfg.path().parent() { - None => Err(anyhow!( - "Invalid Anchor.toml at {}", - workspace_cfg.path().display() - )), - Some(_parent) => { - for p in workspace_cfg.get_program_list()? { - expand_program(workspace_cfg, p, cargo_args)?; - } - Ok(()) - } - }; + for p in workspace_cfg.get_program_list()? { + expand_program(workspace_cfg, p, cargo_args)?; + } std::env::set_current_dir(cur_dir)?; - r + Ok(()) } fn expand_program( @@ -643,7 +636,7 @@ fn expand_program( let mut target_dir = OsString::from("--target-dir="); target_dir.push( workspace_cfg_parent - .join(".anchor/expanded-macros") + .join(EXPANDED_MACROS_PATH) .join("expand-target"), ); target_dir @@ -652,9 +645,8 @@ fn expand_program( let package = format!("--package={}", cargo.package.as_ref().unwrap().name); let program_expansions_path = workspace_cfg_parent - .join(".anchor/expanded-macros") - .join(&cargo.package.as_ref().unwrap().name) - .join("expansions"); + .join(EXPANDED_MACROS_PATH) + .join(&cargo.package.as_ref().unwrap().name); fs::create_dir_all(&program_expansions_path)?; let exit = std::process::Command::new("cargo") From ccdf179140dbf3d1ecf7449d0bd10c3b37401296 Mon Sep 17 00:00:00 2001 From: Paul Schaaf Date: Fri, 17 Dec 2021 20:24:29 +0100 Subject: [PATCH 05/11] docs: changelog, cli: usage docs --- CHANGELOG.md | 1 + cli/src/lib.rs | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 77def4e0f4..f8a9c8e2bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ incremented for features. * lang: Add `programdata_address: Option` field to `Program` account. Will be populated if account is a program owned by the upgradable bpf loader ([#1125](https://github.com/project-serum/anchor/pull/1125)) * lang,ts,ci,cli,docs: update solana toolchain to version 1.8.5([#1133](https://github.com/project-serum/anchor/pull/1133)) +* cli: Add `anchor expand` command which wraps around `cargo expand` ([#1160](https://github.com/project-serum/anchor/pull/1160)) ### Breaking diff --git a/cli/src/lib.rs b/cli/src/lib.rs index 832bc90745..ba2c841891 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -101,8 +101,12 @@ pub enum Command { cargo_args: Vec, }, /// Expands macros (wrapper around cargo expand) + /// + /// Use it in a program folder to expand program + /// + /// Use it in a workspace root to expand entire workspace Expand { - /// Only expands this program + /// Expand only this program #[clap(short, long)] program_name: Option, /// Arguments to pass to the underlying `cargo expand` command From 1c23f5404d2208883bf57bf9b692bebe9f2d3085 Mon Sep 17 00:00:00 2001 From: Paul Schaaf Date: Fri, 17 Dec 2021 21:13:20 +0100 Subject: [PATCH 06/11] cli: refactoring --- cli/src/lib.rs | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/cli/src/lib.rs b/cli/src/lib.rs index ba2c841891..4d4fec1d26 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -611,6 +611,7 @@ pub fn expand( // Reaching this arm means Cargo.toml belongs to a single package. Expand it. Some(cargo) => expand_program( &workspace_cfg, + // If we found Cargo.toml, it must be in a directory so unwrap is safe cargo.path().parent().unwrap().to_path_buf(), cargo_args, ), @@ -636,27 +637,30 @@ fn expand_program( let cargo = Manifest::from_path(program_path.join("Cargo.toml")) .map_err(|_| anyhow!("Could not find Cargo.toml for program"))?; - let target_dir = { - let mut target_dir = OsString::from("--target-dir="); - target_dir.push( + let target_dir_arg = { + let mut target_dir_arg = OsString::from("--target-dir="); + target_dir_arg.push( workspace_cfg_parent .join(EXPANDED_MACROS_PATH) .join("expand-target"), ); - target_dir + target_dir_arg }; - let package = format!("--package={}", cargo.package.as_ref().unwrap().name); - + let package_name = &cargo + .package + .as_ref() + .ok_or_else(|| anyhow!("Cargo config is missing a package"))? + .name; let program_expansions_path = workspace_cfg_parent .join(EXPANDED_MACROS_PATH) - .join(&cargo.package.as_ref().unwrap().name); + .join(package_name); fs::create_dir_all(&program_expansions_path)?; let exit = std::process::Command::new("cargo") .arg("expand") - .arg(target_dir) - .arg(&package) + .arg(target_dir_arg) + .arg(&format!("--package={}", package_name)) .args(cargo_args) .stderr(Stdio::inherit()) .output() @@ -668,12 +672,7 @@ fn expand_program( let version = cargo.version(); let time = chrono::Utc::now().to_string().replace(' ', "_"); fs::write( - program_expansions_path.join(format!( - "{}-{}-{}.rs", - (*cargo).package.as_ref().unwrap().name, - version, - time - )), + program_expansions_path.join(format!("{}-{}-{}.rs", package_name, version, time)), &exit.stdout, ) .map_err(|e| anyhow::format_err!("{}", e.to_string())) From f56af143c78fe3f41eb17794b38784ae99df8dbd Mon Sep 17 00:00:00 2001 From: Paul Schaaf Date: Fri, 17 Dec 2021 21:20:06 +0100 Subject: [PATCH 07/11] cli: refactoring --- cli/src/lib.rs | 32 +++++++++++++------------------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/cli/src/lib.rs b/cli/src/lib.rs index 4d4fec1d26..fe94937764 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -48,8 +48,6 @@ pub mod template; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub const DOCKER_BUILDER_VERSION: &str = VERSION; -const EXPANDED_MACROS_PATH: &str = ".anchor/expanded-macros"; - #[derive(Debug, Clap)] #[clap(version = VERSION)] pub struct Opts { @@ -598,52 +596,50 @@ pub fn expand( let cfg_parent = workspace_cfg.path().parent().expect("Invalid Anchor.toml"); let cargo = Manifest::discover()?; - let expansions_path = cfg_parent.join(EXPANDED_MACROS_PATH); + let expansions_path = cfg_parent.join(".anchor/expanded-macros"); fs::create_dir_all(&expansions_path)?; match cargo { // No Cargo.toml found, expand entire workspace - None => expand_all(&workspace_cfg, cargo_args), + None => expand_all(&workspace_cfg, expansions_path, cargo_args), // Cargo.toml is at root of workspace, expand entire workspace Some(cargo) if cargo.path().parent() == workspace_cfg.path().parent() => { - expand_all(&workspace_cfg, cargo_args) + expand_all(&workspace_cfg, expansions_path, cargo_args) } // Reaching this arm means Cargo.toml belongs to a single package. Expand it. Some(cargo) => expand_program( - &workspace_cfg, // If we found Cargo.toml, it must be in a directory so unwrap is safe cargo.path().parent().unwrap().to_path_buf(), + expansions_path, cargo_args, ), } } -fn expand_all(workspace_cfg: &WithPath, cargo_args: &[String]) -> Result<()> { +fn expand_all( + workspace_cfg: &WithPath, + expansions_path: PathBuf, + cargo_args: &[String], +) -> Result<()> { let cur_dir = std::env::current_dir()?; for p in workspace_cfg.get_program_list()? { - expand_program(workspace_cfg, p, cargo_args)?; + expand_program(p, expansions_path.clone(), cargo_args)?; } std::env::set_current_dir(cur_dir)?; Ok(()) } fn expand_program( - workspace_cfg: &WithPath, program_path: PathBuf, + expansions_path: PathBuf, cargo_args: &[String], ) -> Result<()> { - let workspace_cfg_parent = workspace_cfg.path().parent().unwrap(); - let cargo = Manifest::from_path(program_path.join("Cargo.toml")) .map_err(|_| anyhow!("Could not find Cargo.toml for program"))?; let target_dir_arg = { let mut target_dir_arg = OsString::from("--target-dir="); - target_dir_arg.push( - workspace_cfg_parent - .join(EXPANDED_MACROS_PATH) - .join("expand-target"), - ); + target_dir_arg.push(expansions_path.join("expand-target")); target_dir_arg }; @@ -652,9 +648,7 @@ fn expand_program( .as_ref() .ok_or_else(|| anyhow!("Cargo config is missing a package"))? .name; - let program_expansions_path = workspace_cfg_parent - .join(EXPANDED_MACROS_PATH) - .join(package_name); + let program_expansions_path = expansions_path.join(package_name); fs::create_dir_all(&program_expansions_path)?; let exit = std::process::Command::new("cargo") From 6f16bad60a136e2b50e5473380aaa4bc34a5844e Mon Sep 17 00:00:00 2001 From: Paul Schaaf Date: Sat, 18 Dec 2021 11:52:36 +0100 Subject: [PATCH 08/11] cli: add logging --- cli/src/lib.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/cli/src/lib.rs b/cli/src/lib.rs index fe94937764..7849da4710 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -660,16 +660,22 @@ fn expand_program( .output() .map_err(|e| anyhow::format_err!("{}", e.to_string()))?; if !exit.status.success() { + eprintln!("'anchor expand' failed. Perhaps you have not installed 'cargo-expand'? https://github.com/dtolnay/cargo-expand#installation"); std::process::exit(exit.status.code().unwrap_or(1)); } let version = cargo.version(); let time = chrono::Utc::now().to_string().replace(' ', "_"); - fs::write( - program_expansions_path.join(format!("{}-{}-{}.rs", package_name, version, time)), - &exit.stdout, - ) - .map_err(|e| anyhow::format_err!("{}", e.to_string())) + let file_path = + program_expansions_path.join(format!("{}-{}-{}.rs", package_name, version, time)); + fs::write(&file_path, &exit.stdout).map_err(|e| anyhow::format_err!("{}", e.to_string()))?; + + println!( + "Expanded {} into file {}\n", + package_name, + file_path.to_string_lossy() + ); + Ok(()) } #[allow(clippy::too_many_arguments)] From 24f96f152f86f1b2c20e2ae971bfd9b205fde797 Mon Sep 17 00:00:00 2001 From: Paul Schaaf Date: Sat, 18 Dec 2021 12:07:14 +0100 Subject: [PATCH 09/11] clippy --- lang/src/context.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lang/src/context.rs b/lang/src/context.rs index 45fc28c9f4..6148a7c366 100644 --- a/lang/src/context.rs +++ b/lang/src/context.rs @@ -76,11 +76,13 @@ where } } + #[must_use] pub fn with_signer(mut self, signer_seeds: &'a [&'b [&'c [u8]]]) -> Self { self.signer_seeds = signer_seeds; self } + #[must_use] pub fn with_remaining_accounts(mut self, ra: Vec>) -> Self { self.remaining_accounts = ra; self @@ -156,6 +158,7 @@ impl<'a, 'b, 'c, 'info, T: Accounts<'info>> CpiStateContext<'a, 'b, 'c, 'info, T } } + #[must_use] pub fn with_signer(mut self, signer_seeds: &'a [&'b [&'c [u8]]]) -> Self { self.cpi_ctx = self.cpi_ctx.with_signer(signer_seeds); self From 3173c050d0092d3682d6565797553657b47faea0 Mon Sep 17 00:00:00 2001 From: Paul Schaaf Date: Sat, 18 Dec 2021 12:26:06 +0100 Subject: [PATCH 10/11] clippy --- cli/src/lib.rs | 3 +-- client/src/lib.rs | 9 +++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/cli/src/lib.rs b/cli/src/lib.rs index 7849da4710..db5d02f904 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -1384,8 +1384,7 @@ fn fetch_idl(cfg_override: &ConfigOverride, idl_addr: Pubkey) -> Result { fn extract_idl(file: &str) -> Result> { let file = shellexpand::tilde(file); - let manifest_from_path = - std::env::current_dir()?.join(PathBuf::from(&*file).parent().unwrap().to_path_buf()); + let manifest_from_path = std::env::current_dir()?.join(PathBuf::from(&*file).parent().unwrap()); let cargo = Manifest::discover_from_path(manifest_from_path)? .ok_or_else(|| anyhow!("Cargo.toml not found"))?; anchor_syn::idl::file::parse(&*file, cargo.version()) diff --git a/client/src/lib.rs b/client/src/lib.rs index ce19f06da8..d5e6520b5e 100644 --- a/client/src/lib.rs +++ b/client/src/lib.rs @@ -362,37 +362,44 @@ impl<'a> RequestBuilder<'a> { } } + #[must_use] pub fn payer(mut self, payer: Keypair) -> Self { self.payer = payer; self } + #[must_use] pub fn cluster(mut self, url: &str) -> Self { self.cluster = url.to_string(); self } + #[must_use] pub fn instruction(mut self, ix: Instruction) -> Self { self.instructions.push(ix); self } + #[must_use] pub fn program(mut self, program_id: Pubkey) -> Self { self.program_id = program_id; self } + #[must_use] pub fn accounts(mut self, accounts: impl ToAccountMetas) -> Self { let mut metas = accounts.to_account_metas(None); self.accounts.append(&mut metas); self } + #[must_use] pub fn options(mut self, options: CommitmentConfig) -> Self { self.options = options; self } + #[must_use] pub fn args(mut self, args: impl InstructionData) -> Self { self.instruction_data = Some(args.data()); self @@ -400,6 +407,7 @@ impl<'a> RequestBuilder<'a> { /// Invokes the `#[state]`'s `new` constructor. #[allow(clippy::wrong_self_convention)] + #[must_use] pub fn new(mut self, args: impl InstructionData) -> Self { assert!(self.namespace == RequestNamespace::State { new: false }); self.namespace = RequestNamespace::State { new: true }; @@ -407,6 +415,7 @@ impl<'a> RequestBuilder<'a> { self } + #[must_use] pub fn signer(mut self, signer: &'a dyn Signer) -> Self { self.signers.push(signer); self From 6cafa37cb74abefb403b673c1d10357f837f16eb Mon Sep 17 00:00:00 2001 From: Paul Schaaf Date: Sun, 19 Dec 2021 11:07:09 +0100 Subject: [PATCH 11/11] docs: more docs and display commands in commands.md in alphabetical order --- cli/src/lib.rs | 3 +- docs/src/cli/commands.md | 164 +++++++++++++++++++++------------------ 2 files changed, 91 insertions(+), 76 deletions(-) diff --git a/cli/src/lib.rs b/cli/src/lib.rs index db5d02f904..19d8a275b8 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -102,7 +102,8 @@ pub enum Command { /// /// Use it in a program folder to expand program /// - /// Use it in a workspace root to expand entire workspace + /// Use it in a workspace but outside a program + /// folder to expand the entire workspace Expand { /// Expand only this program #[clap(short, long)] diff --git a/docs/src/cli/commands.md b/docs/src/cli/commands.md index bd366d37d9..ee5a18eee1 100644 --- a/docs/src/cli/commands.md +++ b/docs/src/cli/commands.md @@ -18,6 +18,7 @@ SUBCOMMANDS: build Builds the workspace cluster Cluster commands deploy Deploys each program in the workspace + expand Expands the macros of a program or the workspace help Prints this message or the help of the given subcommand(s) idl Commands for interacting with interface definitions init Initializes a workspace @@ -30,21 +31,6 @@ SUBCOMMANDS: Cargo.toml ``` -## Init - -``` -anchor init -``` - -Initializes a project workspace with the following structure. - -* `Anchor.toml`: Anchor configuration file. -* `Cargo.toml`: Rust workspace configuration file. -* `package.json`: JavaScript dependencies file. -* `programs/`: Directory for Solana program crates. -* `app/`: Directory for your application frontend. -* `tests/`: Directory for JavaScript integration tests. -* `migrations/deploy.js`: Deploy script. ## Build @@ -60,77 +46,49 @@ anchor build --verifiable Runs the build inside a docker image so that the output binary is deterministic (assuming a Cargo.lock file is used). This command must be run from within a single crate subdirectory within the workspace. For example, `programs//`. -## Deploy +## Cluster + +### Cluster list ``` -anchor deploy +anchor cluster list ``` -Deploys all programs in the workspace to the configured cluster. - -::: tip Note -This is different from the `solana program deploy` command, because everytime it's run -it will generate a *new* program address. -::: - -## Upgrade +This lists cluster endpoints: ``` -anchor upgrade --program-id -``` +Cluster Endpoints: -Uses Solana's upgradeable BPF loader to upgrade the on chain program code. +* Mainnet - https://solana-api.projectserum.com +* Mainnet - https://api.mainnet-beta.solana.com +* Devnet - https://api.devnet.solana.com +* Testnet - https://api.testnet.solana.com +``` -## Test +## Deploy ``` -anchor test +anchor deploy ``` -Run an integration test suit against the configured cluster, deploying new versions -of all workspace programs before running them. - -If the configured network is a localnet, then automatically starts the localnetwork and runs -the test. - -::: tip Note -Be sure to shutdown any other local validators, otherwise `anchor test` will fail to run. - -If you'd prefer to run the program against your local validator use `anchor test --skip-local-validator`. -::: - -When running tests we stream program logs to `.anchor/program-logs/
..log` +Deploys all programs in the workspace to the configured cluster. ::: tip Note -The Anchor workflow [recommends](https://www.parity.io/paritys-checklist-for-secure-smart-contract-development/) -to test your program using integration tests in a language other -than Rust to make sure that bugs related to syntax misunderstandings -are coverable with tests and not just replicated in tests. +This is different from the `solana program deploy` command, because everytime it's run +it will generate a *new* program address. ::: -## Migrate +## Expand ``` -anchor migrate +anchor expand ``` -Runs the deploy script located at `migrations/deploy.js`, injecting a provider configured -from the workspace's `Anchor.toml`. For example, +If run inside a program folder, expands the macros of the program. -```javascript -// File: migrations/deploys.js +If run in the workspace but outside a program folder, expands the macros of the workspace. -const anchor = require("@project-serum/anchor"); - -module.exports = async function (provider) { - anchor.setProvider(provider); - - // Add your deploy script here. -} -``` - -Migrations are a new feature -and only support this simple deploy script at the moment. +If run with the `--program-name` option, expand only the given program. ## Idl @@ -195,6 +153,46 @@ anchor idl set-authority -n -p Sets a new authority on the IDL account. Both the `new-authority` and `program-id` must be encoded in base 58. +## Init + +``` +anchor init +``` + +Initializes a project workspace with the following structure. + +* `Anchor.toml`: Anchor configuration file. +* `Cargo.toml`: Rust workspace configuration file. +* `package.json`: JavaScript dependencies file. +* `programs/`: Directory for Solana program crates. +* `app/`: Directory for your application frontend. +* `tests/`: Directory for JavaScript integration tests. +* `migrations/deploy.js`: Deploy script. + +## Migrate + +``` +anchor migrate +``` + +Runs the deploy script located at `migrations/deploy.js`, injecting a provider configured +from the workspace's `Anchor.toml`. For example, + +```javascript +// File: migrations/deploys.js + +const anchor = require("@project-serum/anchor"); + +module.exports = async function (provider) { + anchor.setProvider(provider); + + // Add your deploy script here. +} +``` + +Migrations are a new feature +and only support this simple deploy script at the moment. + ## New ``` @@ -203,24 +201,40 @@ anchor new Creates a new program in the workspace's `programs/` directory initialized with boilerplate. -## Cluster - -### Cluster list +## Test ``` -anchor cluster list +anchor test ``` -This lists cluster endpoints: +Run an integration test suit against the configured cluster, deploying new versions +of all workspace programs before running them. -``` -Cluster Endpoints: +If the configured network is a localnet, then automatically starts the localnetwork and runs +the test. + +::: tip Note +Be sure to shutdown any other local validators, otherwise `anchor test` will fail to run. + +If you'd prefer to run the program against your local validator use `anchor test --skip-local-validator`. +::: + +When running tests we stream program logs to `.anchor/program-logs/
..log` + +::: tip Note +The Anchor workflow [recommends](https://www.parity.io/paritys-checklist-for-secure-smart-contract-development/) +to test your program using integration tests in a language other +than Rust to make sure that bugs related to syntax misunderstandings +are coverable with tests and not just replicated in tests. +::: + +## Upgrade -* Mainnet - https://solana-api.projectserum.com -* Mainnet - https://api.mainnet-beta.solana.com -* Devnet - https://api.devnet.solana.com -* Testnet - https://api.testnet.solana.com ``` +anchor upgrade --program-id +``` + +Uses Solana's upgradeable BPF loader to upgrade the on chain program code. ## Verify