main.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. use crate::config::{find_cargo_toml, read_all_programs, Config, Program};
  2. use anchor_syn::idl::Idl;
  3. use anyhow::{anyhow, Result};
  4. use clap::Clap;
  5. use serde::{Deserialize, Serialize};
  6. use solana_client::rpc_client::RpcClient;
  7. use solana_sdk::pubkey::Pubkey;
  8. use std::fs::{self, File};
  9. use std::io::prelude::*;
  10. use std::path::{Path, PathBuf};
  11. use std::process::{Child, Stdio};
  12. use std::string::ToString;
  13. mod config;
  14. mod template;
  15. #[derive(Debug, Clap)]
  16. pub struct Opts {
  17. #[clap(subcommand)]
  18. pub command: Command,
  19. }
  20. #[derive(Debug, Clap)]
  21. pub enum Command {
  22. /// Initializes a workspace.
  23. Init { name: String },
  24. /// Builds a Solana program.
  25. Build {
  26. /// Output directory for the IDL.
  27. #[clap(short, long)]
  28. idl: Option<String>,
  29. },
  30. /// Runs integration tests against a localnetwork.
  31. Test,
  32. /// Creates a new program.
  33. New { name: String },
  34. /// Outputs an interface definition file.
  35. Idl {
  36. /// Path to the program's interface definition.
  37. #[clap(short, long)]
  38. file: String,
  39. /// Output file for the idl (stdout if not specified).
  40. #[clap(short, long)]
  41. out: Option<String>,
  42. },
  43. /// Deploys the workspace to the configured cluster.
  44. Deploy {
  45. #[clap(short, long)]
  46. url: Option<String>,
  47. #[clap(short, long)]
  48. keypair: Option<String>,
  49. },
  50. }
  51. fn main() -> Result<()> {
  52. let opts = Opts::parse();
  53. match opts.command {
  54. Command::Init { name } => init(name),
  55. Command::Build { idl } => build(idl),
  56. Command::Test => test(),
  57. Command::New { name } => new(name),
  58. Command::Idl { file, out } => {
  59. if out.is_none() {
  60. return idl(file, None);
  61. }
  62. idl(file, Some(&PathBuf::from(out.unwrap())))
  63. }
  64. Command::Deploy { url, keypair } => deploy(url, keypair),
  65. }
  66. }
  67. fn init(name: String) -> Result<()> {
  68. let cfg = Config::discover()?;
  69. if cfg.is_some() {
  70. println!("Anchor workspace already initialized");
  71. }
  72. fs::create_dir(name.clone())?;
  73. std::env::set_current_dir(&name)?;
  74. fs::create_dir("app")?;
  75. let cfg = Config::default();
  76. let toml = cfg.to_string();
  77. let mut file = File::create("Anchor.toml")?;
  78. file.write_all(toml.as_bytes())?;
  79. // Build virtual manifest.
  80. let mut virt_manifest = File::create("Cargo.toml")?;
  81. virt_manifest.write_all(template::virtual_manifest().as_bytes())?;
  82. // Build the program.
  83. fs::create_dir("programs")?;
  84. new_program(&name)?;
  85. // Build the test suite.
  86. fs::create_dir("tests")?;
  87. let mut mocha = File::create(&format!("tests/{}.js", name))?;
  88. mocha.write_all(template::mocha(&name).as_bytes())?;
  89. println!("{} initialized", name);
  90. Ok(())
  91. }
  92. // Creates a new program crate in the `programs/<name>` directory.
  93. fn new(name: String) -> Result<()> {
  94. match Config::discover()? {
  95. None => {
  96. println!("Not in anchor workspace.");
  97. std::process::exit(1);
  98. }
  99. Some((_cfg, cfg_path, _inside_cargo)) => {
  100. match cfg_path.parent() {
  101. None => {
  102. println!("Unable to make new program");
  103. }
  104. Some(parent) => {
  105. std::env::set_current_dir(&parent)?;
  106. new_program(&name)?;
  107. println!("Created new program.");
  108. }
  109. };
  110. }
  111. }
  112. Ok(())
  113. }
  114. // Creates a new program crate in the current directory with `name`.
  115. fn new_program(name: &str) -> Result<()> {
  116. fs::create_dir(&format!("programs/{}", name))?;
  117. fs::create_dir(&format!("programs/{}/src/", name))?;
  118. let mut cargo_toml = File::create(&format!("programs/{}/Cargo.toml", name))?;
  119. cargo_toml.write_all(template::cargo_toml(&name).as_bytes())?;
  120. let mut xargo_toml = File::create(&format!("programs/{}/Xargo.toml", name))?;
  121. xargo_toml.write_all(template::xargo_toml().as_bytes())?;
  122. let mut lib_rs = File::create(&format!("programs/{}/src/lib.rs", name))?;
  123. lib_rs.write_all(template::lib_rs(&name).as_bytes())?;
  124. Ok(())
  125. }
  126. fn build(idl: Option<String>) -> Result<()> {
  127. match Config::discover()? {
  128. None => build_cwd(idl),
  129. Some((cfg, cfg_path, inside_cargo)) => build_ws(cfg, cfg_path, inside_cargo, idl),
  130. }
  131. }
  132. // Runs the build inside a workspace.
  133. //
  134. // * Builds a single program if the current dir is within a Cargo subdirectory,
  135. // e.g., `programs/my-program/src`.
  136. // * Builds *all* programs if thje current dir is anywhere else in the workspace.
  137. //
  138. fn build_ws(
  139. cfg: Config,
  140. cfg_path: PathBuf,
  141. cargo_toml: Option<PathBuf>,
  142. idl: Option<String>,
  143. ) -> Result<()> {
  144. let idl_out = match idl {
  145. Some(idl) => Some(PathBuf::from(idl)),
  146. None => {
  147. let cfg_parent = match cfg_path.parent() {
  148. None => return Err(anyhow::anyhow!("Invalid Anchor.toml")),
  149. Some(parent) => parent,
  150. };
  151. fs::create_dir_all(cfg_parent.join("target/idl"))?;
  152. Some(cfg_parent.join("target/idl"))
  153. }
  154. };
  155. match cargo_toml {
  156. None => build_all(cfg, cfg_path, idl_out),
  157. Some(ct) => _build_cwd(ct, idl_out),
  158. }
  159. }
  160. fn build_all(_cfg: Config, cfg_path: PathBuf, idl_out: Option<PathBuf>) -> Result<()> {
  161. match cfg_path.parent() {
  162. None => Err(anyhow::anyhow!(
  163. "Invalid Anchor.toml at {}",
  164. cfg_path.display()
  165. )),
  166. Some(parent) => {
  167. let files = fs::read_dir(parent.join("programs"))?;
  168. for f in files {
  169. let p = f?.path();
  170. _build_cwd(p.join("Cargo.toml"), idl_out.clone())?;
  171. }
  172. Ok(())
  173. }
  174. }
  175. }
  176. fn build_cwd(idl_out: Option<String>) -> Result<()> {
  177. match find_cargo_toml()? {
  178. None => {
  179. println!("Cargo.toml not found");
  180. std::process::exit(1);
  181. }
  182. Some(cargo_toml) => _build_cwd(cargo_toml, idl_out.map(PathBuf::from)),
  183. }
  184. }
  185. // Runs the build command outside of a workspace.
  186. fn _build_cwd(cargo_toml: PathBuf, idl_out: Option<PathBuf>) -> Result<()> {
  187. match cargo_toml.parent() {
  188. None => return Err(anyhow::anyhow!("Unable to find parent")),
  189. Some(p) => std::env::set_current_dir(&p)?,
  190. };
  191. let exit = std::process::Command::new("cargo")
  192. .arg("build-bpf")
  193. .stdout(Stdio::inherit())
  194. .stderr(Stdio::inherit())
  195. .output()
  196. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  197. if !exit.status.success() {
  198. std::process::exit(exit.status.code().unwrap_or(1));
  199. }
  200. // Always assume idl is located ar src/lib.rs.
  201. let idl = extract_idl("src/lib.rs")?;
  202. let out = match idl_out {
  203. None => PathBuf::from(".").join(&idl.name).with_extension("json"),
  204. Some(o) => PathBuf::from(&o.join(&idl.name).with_extension("json")),
  205. };
  206. write_idl(&idl, Some(&out))
  207. }
  208. fn idl(file: String, out: Option<&Path>) -> Result<()> {
  209. let idl = extract_idl(&file)?;
  210. write_idl(&idl, out)
  211. }
  212. fn extract_idl(file: &str) -> Result<Idl> {
  213. let file = shellexpand::tilde(file);
  214. anchor_syn::parser::file::parse(&*file)
  215. }
  216. fn write_idl(idl: &Idl, out: Option<&Path>) -> Result<()> {
  217. let idl_json = serde_json::to_string_pretty(idl)?;
  218. match out.as_ref() {
  219. None => println!("{}", idl_json),
  220. Some(out) => std::fs::write(out, idl_json)?,
  221. };
  222. Ok(())
  223. }
  224. // Builds, deploys, and tests all workspace programs in a single command.
  225. fn test() -> Result<()> {
  226. // Switch directories to top level workspace.
  227. set_workspace_dir_or_exit();
  228. // Build everything.
  229. build(None)?;
  230. // Switch again (todo: restore cwd in `build` command).
  231. set_workspace_dir_or_exit();
  232. // Bootup validator.
  233. let mut validator_handle = start_test_validator()?;
  234. // Deploy all programs.
  235. let cfg = Config::discover()?.expect("Inside a workspace").0;
  236. let programs = deploy_ws("http://localhost:8899", &cfg.wallet.to_string())?;
  237. // Store deployed program addresses in IDL metadata (for consumption by
  238. // client + tests).
  239. for (program, address) in programs {
  240. // Add metadata to the IDL.
  241. let mut idl = program.idl;
  242. idl.metadata = Some(serde_json::to_value(IdlTestMetadata {
  243. address: address.to_string(),
  244. })?);
  245. // Persist it.
  246. let idl_out = PathBuf::from("target/idl")
  247. .join(&idl.name)
  248. .with_extension("json");
  249. write_idl(&idl, Some(&idl_out))?;
  250. }
  251. // Run the tests.
  252. if let Err(e) = std::process::Command::new("mocha")
  253. .arg("-t")
  254. .arg("10000")
  255. .arg("tests/")
  256. .stdout(Stdio::inherit())
  257. .stderr(Stdio::inherit())
  258. .output()
  259. {
  260. validator_handle.kill()?;
  261. return Err(anyhow::format_err!("{}", e.to_string()));
  262. }
  263. validator_handle.kill()?;
  264. Ok(())
  265. }
  266. #[derive(Debug, Serialize, Deserialize)]
  267. pub struct IdlTestMetadata {
  268. address: String,
  269. }
  270. fn start_test_validator() -> Result<Child> {
  271. fs::create_dir_all(".anchor")?;
  272. let test_ledger_filename = ".anchor/test-ledger";
  273. let test_ledger_log_filename = ".anchor/test-ledger-log.txt";
  274. if Path::new(test_ledger_filename).exists() {
  275. std::fs::remove_dir_all(test_ledger_filename)?;
  276. }
  277. if Path::new(test_ledger_log_filename).exists() {
  278. std::fs::remove_file(test_ledger_log_filename)?;
  279. }
  280. // Start a validator for testing.
  281. let test_validator_stdout = File::create(test_ledger_log_filename)?;
  282. let test_validator_stderr = test_validator_stdout.try_clone()?;
  283. let validator_handle = std::process::Command::new("solana-test-validator")
  284. .arg("--ledger")
  285. .arg(test_ledger_filename)
  286. .stdout(Stdio::from(test_validator_stdout))
  287. .stderr(Stdio::from(test_validator_stderr))
  288. .spawn()
  289. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  290. // Wait for the validator to be ready.
  291. let client = RpcClient::new("http://localhost:8899".to_string());
  292. let mut count = 0;
  293. let ms_wait = 5000;
  294. while count < ms_wait {
  295. let r = client.get_recent_blockhash();
  296. if r.is_ok() {
  297. break;
  298. }
  299. std::thread::sleep(std::time::Duration::from_millis(1));
  300. count += 1;
  301. }
  302. if count == 5000 {
  303. println!("Unable to start test validator.");
  304. std::process::exit(1);
  305. }
  306. Ok(validator_handle)
  307. }
  308. fn deploy(url: Option<String>, keypair: Option<String>) -> Result<()> {
  309. let (cfg, ws_path, _) = Config::discover()?.ok_or(anyhow!("Not in Anchor workspace."))?;
  310. std::env::set_current_dir(ws_path.parent().unwrap())?;
  311. let url = url.unwrap_or(cfg.cluster.url().to_string());
  312. let keypair = keypair.unwrap_or(cfg.wallet.to_string());
  313. let deployment = deploy_ws(&url, &keypair)?;
  314. for (program, address) in deployment {
  315. println!("Deployed {} at {}", program.idl.name, address.to_string());
  316. }
  317. Ok(())
  318. }
  319. fn deploy_ws(url: &str, keypair: &str) -> Result<Vec<(Program, Pubkey)>> {
  320. let mut programs = vec![];
  321. println!("Deploying workspace to {}...", url);
  322. for program in read_all_programs()? {
  323. let binary_path = format!("target/deploy/{}.so", program.lib_name);
  324. println!("Deploying {}...", binary_path);
  325. let exit = std::process::Command::new("solana")
  326. .arg("deploy")
  327. .arg(&binary_path)
  328. .arg("--url")
  329. .arg(url)
  330. .arg("--keypair")
  331. .arg(keypair)
  332. .output()
  333. .expect("Must deploy");
  334. if !exit.status.success() {
  335. println!("There was a problem deploying: {:?}.", exit);
  336. std::process::exit(exit.status.code().unwrap_or(1));
  337. }
  338. let stdout: DeployStdout = serde_json::from_str(std::str::from_utf8(&exit.stdout)?)?;
  339. programs.push((program, stdout.program_id.parse()?));
  340. }
  341. println!("Deploy success!");
  342. Ok(programs)
  343. }
  344. #[derive(Debug, Deserialize)]
  345. #[serde(rename_all = "camelCase")]
  346. pub struct DeployStdout {
  347. program_id: String,
  348. }
  349. fn set_workspace_dir_or_exit() {
  350. let d = match Config::discover() {
  351. Err(_) => {
  352. println!("Not in anchor workspace.");
  353. std::process::exit(1);
  354. }
  355. Ok(d) => d,
  356. };
  357. match d {
  358. None => {
  359. println!("Not in anchor workspace.");
  360. std::process::exit(1);
  361. }
  362. Some((_cfg, cfg_path, _inside_cargo)) => {
  363. match cfg_path.parent() {
  364. None => {
  365. println!("Unable to make new program");
  366. }
  367. Some(parent) => match std::env::set_current_dir(&parent) {
  368. Err(_) => {
  369. println!("Not in anchor workspace.");
  370. std::process::exit(1);
  371. }
  372. Ok(_) => {}
  373. },
  374. };
  375. }
  376. }
  377. }