main.rs 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. //! CLI for workspace management of anchor programs.
  2. use crate::config::{read_all_programs, Config, Program};
  3. use anchor_lang::idl::{IdlAccount, IdlInstruction};
  4. use anchor_lang::{AccountDeserialize, AnchorDeserialize, AnchorSerialize};
  5. use anchor_syn::idl::Idl;
  6. use anyhow::{anyhow, Context, Result};
  7. use clap::Clap;
  8. use flate2::read::ZlibDecoder;
  9. use flate2::write::ZlibEncoder;
  10. use flate2::Compression;
  11. use rand::rngs::OsRng;
  12. use serde::{Deserialize, Serialize};
  13. use solana_client::rpc_client::RpcClient;
  14. use solana_client::rpc_config::RpcSendTransactionConfig;
  15. use solana_program::instruction::{AccountMeta, Instruction};
  16. use solana_sdk::account_utils::StateMut;
  17. use solana_sdk::bpf_loader_upgradeable::UpgradeableLoaderState;
  18. use solana_sdk::commitment_config::CommitmentConfig;
  19. use solana_sdk::pubkey::Pubkey;
  20. use solana_sdk::signature::Keypair;
  21. use solana_sdk::signature::Signer;
  22. use solana_sdk::sysvar;
  23. use solana_sdk::transaction::Transaction;
  24. use std::fs::{self, File};
  25. use std::io::prelude::*;
  26. use std::path::{Path, PathBuf};
  27. use std::process::{Child, Stdio};
  28. use std::string::ToString;
  29. mod config;
  30. mod template;
  31. // Version of the docker image.
  32. const VERSION: &str = env!("CARGO_PKG_VERSION");
  33. const DOCKER_BUILDER_VERSION: &str = VERSION;
  34. #[derive(Debug, Clap)]
  35. #[clap(version = VERSION)]
  36. pub struct Opts {
  37. #[clap(subcommand)]
  38. pub command: Command,
  39. }
  40. #[derive(Debug, Clap)]
  41. pub enum Command {
  42. /// Initializes a workspace.
  43. Init {
  44. name: String,
  45. #[clap(short, long)]
  46. typescript: bool,
  47. },
  48. /// Builds the workspace.
  49. Build {
  50. /// Output directory for the IDL.
  51. #[clap(short, long)]
  52. idl: Option<String>,
  53. /// True if the build artifiact needs to be deterministic and verifiable.
  54. #[clap(short, long)]
  55. verifiable: bool,
  56. },
  57. /// Verifies the on-chain bytecode matches the locally compiled artifact.
  58. /// Run this command inside a program subdirectory, i.e., in the dir
  59. /// containing the program's Cargo.toml.
  60. Verify {
  61. /// The deployed program to compare against.
  62. program_id: Pubkey,
  63. },
  64. /// Runs integration tests against a localnetwork.
  65. Test {
  66. /// Use this flag if you want to run tests against previously deployed
  67. /// programs.
  68. #[clap(long)]
  69. skip_deploy: bool,
  70. /// Flag to skip starting a local validator, if the configured cluster
  71. /// url is a localnet.
  72. #[clap(long)]
  73. skip_local_validator: bool,
  74. file: Option<String>,
  75. },
  76. /// Creates a new program.
  77. New { name: String },
  78. /// Commands for interacting with interface definitions.
  79. Idl {
  80. #[clap(subcommand)]
  81. subcmd: IdlCommand,
  82. },
  83. /// Deploys each program in the workspace.
  84. Deploy {
  85. #[clap(short, long)]
  86. url: Option<String>,
  87. #[clap(short, long)]
  88. keypair: Option<String>,
  89. },
  90. /// Runs the deploy migration script.
  91. Migrate {
  92. #[clap(short, long)]
  93. url: Option<String>,
  94. },
  95. /// Deploys, initializes an IDL, and migrates all in one command.
  96. Launch {
  97. #[clap(short, long)]
  98. url: Option<String>,
  99. #[clap(short, long)]
  100. keypair: Option<String>,
  101. /// True if the build should be verifiable. If deploying to mainnet,
  102. /// this should almost always be set.
  103. #[clap(short, long)]
  104. verifiable: bool,
  105. },
  106. /// Upgrades a single program. The configured wallet must be the upgrade
  107. /// authority.
  108. Upgrade {
  109. /// The program to upgrade.
  110. #[clap(short, long)]
  111. program_id: Pubkey,
  112. /// Filepath to the new program binary.
  113. program_filepath: String,
  114. },
  115. #[cfg(feature = "dev")]
  116. /// Runs an airdrop loop, continuously funding the configured wallet.
  117. Airdrop {
  118. #[clap(short, long)]
  119. url: Option<String>,
  120. },
  121. }
  122. #[derive(Debug, Clap)]
  123. pub enum IdlCommand {
  124. /// Initializes a program's IDL account. Can only be run once.
  125. Init {
  126. program_id: Pubkey,
  127. #[clap(short, long)]
  128. filepath: String,
  129. },
  130. /// Writes an IDL into a buffer account. This can be used with SetBuffer
  131. /// to perform an upgrade.
  132. WriteBuffer {
  133. program_id: Pubkey,
  134. #[clap(short, long)]
  135. filepath: String,
  136. },
  137. /// Sets a new IDL buffer for the program.
  138. SetBuffer {
  139. program_id: Pubkey,
  140. /// Address of the buffer account to set as the idl on the program.
  141. #[clap(short, long)]
  142. buffer: Pubkey,
  143. },
  144. /// Upgrades the IDL to the new file. An alias for first writing and then
  145. /// then setting the idl buffer account.
  146. Upgrade {
  147. program_id: Pubkey,
  148. #[clap(short, long)]
  149. filepath: String,
  150. },
  151. /// Sets a new authority on the IDL account.
  152. SetAuthority {
  153. /// The IDL account buffer to set the authority of. If none is given,
  154. /// then the canonical IDL account is used.
  155. address: Option<Pubkey>,
  156. /// Program to change the IDL authority.
  157. #[clap(short, long)]
  158. program_id: Pubkey,
  159. /// New authority of the IDL account.
  160. #[clap(short, long)]
  161. new_authority: Pubkey,
  162. },
  163. /// Command to remove the ability to modify the IDL account. This should
  164. /// likely be used in conjection with eliminating an "upgrade authority" on
  165. /// the program.
  166. EraseAuthority {
  167. #[clap(short, long)]
  168. program_id: Pubkey,
  169. },
  170. /// Outputs the authority for the IDL account.
  171. Authority {
  172. /// The program to view.
  173. program_id: Pubkey,
  174. },
  175. /// Parses an IDL from source.
  176. Parse {
  177. /// Path to the program's interface definition.
  178. #[clap(short, long)]
  179. file: String,
  180. /// Output file for the idl (stdout if not specified).
  181. #[clap(short, long)]
  182. out: Option<String>,
  183. },
  184. /// Fetches an IDL for the given address from a cluster.
  185. /// The address can be a program, IDL account, or IDL buffer.
  186. Fetch {
  187. address: Pubkey,
  188. /// Output file for the idl (stdout if not specified).
  189. #[clap(short, long)]
  190. out: Option<String>,
  191. },
  192. }
  193. fn main() -> Result<()> {
  194. let opts = Opts::parse();
  195. match opts.command {
  196. Command::Init { name, typescript } => init(name, typescript),
  197. Command::New { name } => new(name),
  198. Command::Build { idl, verifiable } => build(idl, verifiable),
  199. Command::Verify { program_id } => verify(program_id),
  200. Command::Deploy { url, keypair } => deploy(url, keypair),
  201. Command::Upgrade {
  202. program_id,
  203. program_filepath,
  204. } => upgrade(program_id, program_filepath),
  205. Command::Idl { subcmd } => idl(subcmd),
  206. Command::Migrate { url } => migrate(url),
  207. Command::Launch {
  208. url,
  209. keypair,
  210. verifiable,
  211. } => launch(url, keypair, verifiable),
  212. Command::Test {
  213. skip_deploy,
  214. skip_local_validator,
  215. file,
  216. } => test(skip_deploy, skip_local_validator, file),
  217. #[cfg(feature = "dev")]
  218. Command::Airdrop { url } => airdrop(url),
  219. }
  220. }
  221. fn init(name: String, typescript: bool) -> Result<()> {
  222. let cfg = Config::discover()?;
  223. if cfg.is_some() {
  224. println!("Anchor workspace already initialized");
  225. }
  226. fs::create_dir(name.clone())?;
  227. std::env::set_current_dir(&name)?;
  228. fs::create_dir("app")?;
  229. let cfg = Config::default();
  230. let toml = cfg.to_string();
  231. let mut file = File::create("Anchor.toml")?;
  232. file.write_all(toml.as_bytes())?;
  233. // Build virtual manifest.
  234. let mut virt_manifest = File::create("Cargo.toml")?;
  235. virt_manifest.write_all(template::virtual_manifest().as_bytes())?;
  236. // Initialize .gitignore file
  237. let mut virt_manifest = File::create(".gitignore")?;
  238. virt_manifest.write_all(template::git_ignore().as_bytes())?;
  239. // Build the program.
  240. fs::create_dir("programs")?;
  241. new_program(&name)?;
  242. // Build the test suite.
  243. fs::create_dir("tests")?;
  244. // Build the migrations directory.
  245. fs::create_dir("migrations")?;
  246. if typescript {
  247. // Build typescript config
  248. let mut ts_config = File::create("tsconfig.json")?;
  249. ts_config.write_all(template::ts_config().as_bytes())?;
  250. let mut deploy = File::create("migrations/deploy.ts")?;
  251. deploy.write_all(&template::ts_deploy_script().as_bytes())?;
  252. let mut mocha = File::create(&format!("tests/{}.spec.ts", name))?;
  253. mocha.write_all(template::ts_mocha(&name).as_bytes())?;
  254. } else {
  255. let mut mocha = File::create(&format!("tests/{}.js", name))?;
  256. mocha.write_all(template::mocha(&name).as_bytes())?;
  257. let mut deploy = File::create("migrations/deploy.js")?;
  258. deploy.write_all(&template::deploy_script().as_bytes())?;
  259. }
  260. println!("{} initialized", name);
  261. Ok(())
  262. }
  263. // Creates a new program crate in the `programs/<name>` directory.
  264. fn new(name: String) -> Result<()> {
  265. with_workspace(|_cfg, path, _cargo| {
  266. match path.parent() {
  267. None => {
  268. println!("Unable to make new program");
  269. }
  270. Some(parent) => {
  271. std::env::set_current_dir(&parent)?;
  272. new_program(&name)?;
  273. println!("Created new program.");
  274. }
  275. };
  276. Ok(())
  277. })
  278. }
  279. // Creates a new program crate in the current directory with `name`.
  280. fn new_program(name: &str) -> Result<()> {
  281. fs::create_dir(&format!("programs/{}", name))?;
  282. fs::create_dir(&format!("programs/{}/src/", name))?;
  283. let mut cargo_toml = File::create(&format!("programs/{}/Cargo.toml", name))?;
  284. cargo_toml.write_all(template::cargo_toml(&name).as_bytes())?;
  285. let mut xargo_toml = File::create(&format!("programs/{}/Xargo.toml", name))?;
  286. xargo_toml.write_all(template::xargo_toml().as_bytes())?;
  287. let mut lib_rs = File::create(&format!("programs/{}/src/lib.rs", name))?;
  288. lib_rs.write_all(template::lib_rs(&name).as_bytes())?;
  289. Ok(())
  290. }
  291. fn build(idl: Option<String>, verifiable: bool) -> Result<()> {
  292. let (cfg, path, cargo) = Config::discover()?.expect("Not in workspace.");
  293. let idl_out = match idl {
  294. Some(idl) => Some(PathBuf::from(idl)),
  295. None => {
  296. let cfg_parent = match path.parent() {
  297. None => return Err(anyhow!("Invalid Anchor.toml")),
  298. Some(parent) => parent,
  299. };
  300. fs::create_dir_all(cfg_parent.join("target/idl"))?;
  301. Some(cfg_parent.join("target/idl"))
  302. }
  303. };
  304. match cargo {
  305. None => build_all(&cfg, path, idl_out, verifiable)?,
  306. Some(ct) => build_cwd(path.as_path(), ct, idl_out, verifiable)?,
  307. };
  308. set_workspace_dir_or_exit();
  309. Ok(())
  310. }
  311. fn build_all(
  312. _cfg: &Config,
  313. cfg_path: PathBuf,
  314. idl_out: Option<PathBuf>,
  315. verifiable: bool,
  316. ) -> Result<()> {
  317. let cur_dir = std::env::current_dir()?;
  318. let r = match cfg_path.parent() {
  319. None => Err(anyhow!("Invalid Anchor.toml at {}", cfg_path.display())),
  320. Some(parent) => {
  321. let files = fs::read_dir(parent.join("programs"))?;
  322. for f in files {
  323. let p = f?.path();
  324. build_cwd(
  325. cfg_path.as_path(),
  326. p.join("Cargo.toml"),
  327. idl_out.clone(),
  328. verifiable,
  329. )?;
  330. }
  331. Ok(())
  332. }
  333. };
  334. std::env::set_current_dir(cur_dir)?;
  335. r
  336. }
  337. // Runs the build command outside of a workspace.
  338. fn build_cwd(
  339. cfg_path: &Path,
  340. cargo_toml: PathBuf,
  341. idl_out: Option<PathBuf>,
  342. verifiable: bool,
  343. ) -> Result<()> {
  344. match cargo_toml.parent() {
  345. None => return Err(anyhow!("Unable to find parent")),
  346. Some(p) => std::env::set_current_dir(&p)?,
  347. };
  348. match verifiable {
  349. false => _build_cwd(idl_out),
  350. true => build_cwd_verifiable(cfg_path.parent().unwrap()),
  351. }
  352. }
  353. // Builds an anchor program in a docker image and copies the build artifacts
  354. // into the `target/` directory.
  355. fn build_cwd_verifiable(workspace_dir: &Path) -> Result<()> {
  356. // Docker vars.
  357. let container_name = "anchor-program";
  358. let image_name = format!("projectserum/build:v{}", DOCKER_BUILDER_VERSION);
  359. let volume_mount = format!(
  360. "{}:/workdir",
  361. workspace_dir.canonicalize()?.display().to_string()
  362. );
  363. // Create output dirs.
  364. fs::create_dir_all(workspace_dir.join("target/deploy"))?;
  365. fs::create_dir_all(workspace_dir.join("target/idl"))?;
  366. // Build the program in docker.
  367. let exit = std::process::Command::new("docker")
  368. .args(&[
  369. "run",
  370. "--name",
  371. &container_name,
  372. "-v",
  373. &volume_mount,
  374. &image_name,
  375. "anchor",
  376. "build",
  377. ])
  378. .stdout(Stdio::inherit())
  379. .stderr(Stdio::inherit())
  380. .output()
  381. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  382. if !exit.status.success() {
  383. println!("Error building program");
  384. return Ok(());
  385. }
  386. let idl = extract_idl("src/lib.rs")?;
  387. // Copy the binary out of the docker image.
  388. let out_file = format!("../../target/deploy/{}.so", idl.name);
  389. let bin_artifact = format!("{}:/workdir/target/deploy/{}.so", container_name, idl.name);
  390. let exit = std::process::Command::new("docker")
  391. .args(&["cp", &bin_artifact, &out_file])
  392. .stdout(Stdio::inherit())
  393. .stderr(Stdio::inherit())
  394. .output()
  395. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  396. if !exit.status.success() {
  397. return Ok(());
  398. }
  399. // Copy the idl out of the docker image.
  400. let out_file = format!("../../target/idl/{}.json", idl.name);
  401. let idl_artifact = format!("{}:/workdir/target/idl/{}.json", container_name, idl.name);
  402. let exit = std::process::Command::new("docker")
  403. .args(&["cp", &idl_artifact, &out_file])
  404. .stdout(Stdio::inherit())
  405. .stderr(Stdio::inherit())
  406. .output()
  407. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  408. if !exit.status.success() {
  409. return Ok(());
  410. }
  411. // Remove the docker image.
  412. let exit = std::process::Command::new("docker")
  413. .args(&["rm", &container_name])
  414. .stdout(Stdio::inherit())
  415. .stderr(Stdio::inherit())
  416. .output()
  417. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  418. if !exit.status.success() {
  419. std::process::exit(exit.status.code().unwrap_or(1));
  420. }
  421. Ok(())
  422. }
  423. fn _build_cwd(idl_out: Option<PathBuf>) -> Result<()> {
  424. let exit = std::process::Command::new("cargo")
  425. .arg("build-bpf")
  426. .stdout(Stdio::inherit())
  427. .stderr(Stdio::inherit())
  428. .output()
  429. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  430. if !exit.status.success() {
  431. std::process::exit(exit.status.code().unwrap_or(1));
  432. }
  433. // Always assume idl is located ar src/lib.rs.
  434. let idl = extract_idl("src/lib.rs")?;
  435. let out = match idl_out {
  436. None => PathBuf::from(".").join(&idl.name).with_extension("json"),
  437. Some(o) => PathBuf::from(&o.join(&idl.name).with_extension("json")),
  438. };
  439. write_idl(&idl, OutFile::File(out))
  440. }
  441. fn verify(program_id: Pubkey) -> Result<()> {
  442. let (cfg, _path, cargo) = Config::discover()?.expect("Not in workspace.");
  443. let cargo = cargo.ok_or(anyhow!("Must be inside program subdirectory."))?;
  444. let program_dir = cargo.parent().unwrap();
  445. // Build the program we want to verify.
  446. let cur_dir = std::env::current_dir()?;
  447. build(None, true)?;
  448. std::env::set_current_dir(&cur_dir)?;
  449. let local_idl = extract_idl("src/lib.rs")?;
  450. // Verify binary.
  451. let bin_path = program_dir
  452. .join("../../target/deploy/")
  453. .join(format!("{}.so", local_idl.name));
  454. let is_buffer = verify_bin(program_id, &bin_path, cfg.cluster.url())?;
  455. // Verify IDL (only if it's not a buffer account).
  456. if !is_buffer {
  457. std::env::set_current_dir(program_dir)?;
  458. let deployed_idl = fetch_idl(program_id)?;
  459. if local_idl != deployed_idl {
  460. println!("Error: IDLs don't match");
  461. std::process::exit(1);
  462. }
  463. }
  464. println!("{} is verified.", program_id);
  465. Ok(())
  466. }
  467. fn verify_bin(program_id: Pubkey, bin_path: &Path, cluster: &str) -> Result<bool> {
  468. let client = RpcClient::new(cluster.to_string());
  469. // Get the deployed build artifacts.
  470. let (deployed_bin, is_buffer) = {
  471. let account = client
  472. .get_account_with_commitment(&program_id, CommitmentConfig::default())?
  473. .value
  474. .map_or(Err(anyhow!("Account not found")), Ok)?;
  475. match account.state()? {
  476. UpgradeableLoaderState::Program {
  477. programdata_address,
  478. } => (
  479. client
  480. .get_account_with_commitment(&programdata_address, CommitmentConfig::default())?
  481. .value
  482. .map_or(Err(anyhow!("Account not found")), Ok)?
  483. .data[UpgradeableLoaderState::programdata_data_offset().unwrap_or(0)..]
  484. .to_vec(),
  485. false,
  486. ),
  487. UpgradeableLoaderState::Buffer { .. } => {
  488. let offset = UpgradeableLoaderState::buffer_data_offset().unwrap_or(0);
  489. (account.data[offset..].to_vec(), true)
  490. }
  491. _ => return Err(anyhow!("Invalid program id")),
  492. }
  493. };
  494. let mut local_bin = {
  495. let mut f = File::open(bin_path)?;
  496. let mut contents = vec![];
  497. f.read_to_end(&mut contents)?;
  498. contents
  499. };
  500. // The deployed program probably has zero bytes appended. The default is
  501. // 2x the binary size in case of an upgrade.
  502. if local_bin.len() < deployed_bin.len() {
  503. local_bin.append(&mut vec![0; deployed_bin.len() - local_bin.len()]);
  504. }
  505. // Finally, check the bytes.
  506. if local_bin != deployed_bin {
  507. println!("Error: Binaries don't match");
  508. std::process::exit(1);
  509. }
  510. Ok(is_buffer)
  511. }
  512. // Fetches an IDL for the given program_id.
  513. fn fetch_idl(idl_addr: Pubkey) -> Result<Idl> {
  514. let cfg = Config::discover()?.expect("Inside a workspace").0;
  515. let client = RpcClient::new(cfg.cluster.url().to_string());
  516. let mut account = client
  517. .get_account_with_commitment(&idl_addr, CommitmentConfig::processed())?
  518. .value
  519. .map_or(Err(anyhow!("Account not found")), Ok)?;
  520. if account.executable {
  521. let idl_addr = IdlAccount::address(&idl_addr);
  522. account = client
  523. .get_account_with_commitment(&idl_addr, CommitmentConfig::processed())?
  524. .value
  525. .map_or(Err(anyhow!("Account not found")), Ok)?;
  526. }
  527. // Cut off account discriminator.
  528. let mut d: &[u8] = &account.data[8..];
  529. let idl_account: IdlAccount = AnchorDeserialize::deserialize(&mut d)?;
  530. let mut z = ZlibDecoder::new(&idl_account.data[..]);
  531. let mut s = Vec::new();
  532. z.read_to_end(&mut s)?;
  533. serde_json::from_slice(&s[..]).map_err(Into::into)
  534. }
  535. fn extract_idl(file: &str) -> Result<Idl> {
  536. let file = shellexpand::tilde(file);
  537. anchor_syn::parser::file::parse(&*file)
  538. }
  539. fn idl(subcmd: IdlCommand) -> Result<()> {
  540. match subcmd {
  541. IdlCommand::Init {
  542. program_id,
  543. filepath,
  544. } => idl_init(program_id, filepath),
  545. IdlCommand::WriteBuffer {
  546. program_id,
  547. filepath,
  548. } => idl_write_buffer(program_id, filepath).map(|_| ()),
  549. IdlCommand::SetBuffer { program_id, buffer } => idl_set_buffer(program_id, buffer),
  550. IdlCommand::Upgrade {
  551. program_id,
  552. filepath,
  553. } => idl_upgrade(program_id, filepath),
  554. IdlCommand::SetAuthority {
  555. program_id,
  556. address,
  557. new_authority,
  558. } => idl_set_authority(program_id, address, new_authority),
  559. IdlCommand::EraseAuthority { program_id } => idl_erase_authority(program_id),
  560. IdlCommand::Authority { program_id } => idl_authority(program_id),
  561. IdlCommand::Parse { file, out } => idl_parse(file, out),
  562. IdlCommand::Fetch { address, out } => idl_fetch(address, out),
  563. }
  564. }
  565. fn idl_init(program_id: Pubkey, idl_filepath: String) -> Result<()> {
  566. with_workspace(|cfg, _path, _cargo| {
  567. let keypair = cfg.wallet.to_string();
  568. let bytes = std::fs::read(idl_filepath)?;
  569. let idl: Idl = serde_json::from_reader(&*bytes)?;
  570. let idl_address = create_idl_account(&cfg, &keypair, &program_id, &idl)?;
  571. println!("Idl account created: {:?}", idl_address);
  572. Ok(())
  573. })
  574. }
  575. fn idl_write_buffer(program_id: Pubkey, idl_filepath: String) -> Result<Pubkey> {
  576. with_workspace(|cfg, _path, _cargo| {
  577. let keypair = cfg.wallet.to_string();
  578. let bytes = std::fs::read(idl_filepath)?;
  579. let idl: Idl = serde_json::from_reader(&*bytes)?;
  580. let idl_buffer = create_idl_buffer(&cfg, &keypair, &program_id, &idl)?;
  581. idl_write(&cfg, &program_id, &idl, idl_buffer)?;
  582. println!("Idl buffer created: {:?}", idl_buffer);
  583. Ok(idl_buffer)
  584. })
  585. }
  586. fn idl_set_buffer(program_id: Pubkey, buffer: Pubkey) -> Result<()> {
  587. with_workspace(|cfg, _path, _cargo| {
  588. let keypair = solana_sdk::signature::read_keypair_file(&cfg.wallet.to_string())
  589. .map_err(|_| anyhow!("Unable to read keypair file"))?;
  590. let client = RpcClient::new(cfg.cluster.url().to_string());
  591. // Instruction to set the buffer onto the IdlAccount.
  592. let set_buffer_ix = {
  593. let accounts = vec![
  594. AccountMeta::new(buffer, false),
  595. AccountMeta::new(IdlAccount::address(&program_id), false),
  596. AccountMeta::new(keypair.pubkey(), true),
  597. ];
  598. let mut data = anchor_lang::idl::IDL_IX_TAG.to_le_bytes().to_vec();
  599. data.append(&mut IdlInstruction::SetBuffer.try_to_vec()?);
  600. Instruction {
  601. program_id,
  602. accounts,
  603. data,
  604. }
  605. };
  606. // Build the transaction.
  607. let (recent_hash, _fee_calc) = client.get_recent_blockhash()?;
  608. let tx = Transaction::new_signed_with_payer(
  609. &[set_buffer_ix],
  610. Some(&keypair.pubkey()),
  611. &[&keypair],
  612. recent_hash,
  613. );
  614. // Send the transaction.
  615. client.send_and_confirm_transaction_with_spinner_and_config(
  616. &tx,
  617. CommitmentConfig::confirmed(),
  618. RpcSendTransactionConfig {
  619. skip_preflight: true,
  620. ..RpcSendTransactionConfig::default()
  621. },
  622. )?;
  623. Ok(())
  624. })
  625. }
  626. fn idl_upgrade(program_id: Pubkey, idl_filepath: String) -> Result<()> {
  627. let buffer = idl_write_buffer(program_id, idl_filepath)?;
  628. idl_set_buffer(program_id, buffer)
  629. }
  630. fn idl_authority(program_id: Pubkey) -> Result<()> {
  631. with_workspace(|cfg, _path, _cargo| {
  632. let client = RpcClient::new(cfg.cluster.url().to_string());
  633. let idl_address = {
  634. let account = client
  635. .get_account_with_commitment(&program_id, CommitmentConfig::processed())?
  636. .value
  637. .map_or(Err(anyhow!("Account not found")), Ok)?;
  638. if account.executable {
  639. IdlAccount::address(&program_id)
  640. } else {
  641. program_id
  642. }
  643. };
  644. let account = client.get_account(&idl_address)?;
  645. let mut data: &[u8] = &account.data;
  646. let idl_account: IdlAccount = AccountDeserialize::try_deserialize(&mut data)?;
  647. println!("{:?}", idl_account.authority);
  648. Ok(())
  649. })
  650. }
  651. fn idl_set_authority(
  652. program_id: Pubkey,
  653. address: Option<Pubkey>,
  654. new_authority: Pubkey,
  655. ) -> Result<()> {
  656. with_workspace(|cfg, _path, _cargo| {
  657. // Misc.
  658. let idl_address = match address {
  659. None => IdlAccount::address(&program_id),
  660. Some(addr) => addr,
  661. };
  662. let keypair = solana_sdk::signature::read_keypair_file(&cfg.wallet.to_string())
  663. .map_err(|_| anyhow!("Unable to read keypair file"))?;
  664. let client = RpcClient::new(cfg.cluster.url().to_string());
  665. // Instruction data.
  666. let data =
  667. serialize_idl_ix(anchor_lang::idl::IdlInstruction::SetAuthority { new_authority })?;
  668. // Instruction accounts.
  669. let accounts = vec![
  670. AccountMeta::new(idl_address, false),
  671. AccountMeta::new_readonly(keypair.pubkey(), true),
  672. ];
  673. // Instruction.
  674. let ix = Instruction {
  675. program_id,
  676. accounts,
  677. data,
  678. };
  679. // Send transaction.
  680. let (recent_hash, _fee_calc) = client.get_recent_blockhash()?;
  681. let tx = Transaction::new_signed_with_payer(
  682. &[ix],
  683. Some(&keypair.pubkey()),
  684. &[&keypair],
  685. recent_hash,
  686. );
  687. client.send_and_confirm_transaction_with_spinner_and_config(
  688. &tx,
  689. CommitmentConfig::confirmed(),
  690. RpcSendTransactionConfig {
  691. skip_preflight: true,
  692. ..RpcSendTransactionConfig::default()
  693. },
  694. )?;
  695. println!("Authority update complete.");
  696. Ok(())
  697. })
  698. }
  699. fn idl_erase_authority(program_id: Pubkey) -> Result<()> {
  700. println!("Are you sure you want to erase the IDL authority: [y/n]");
  701. let stdin = std::io::stdin();
  702. let mut stdin_lines = stdin.lock().lines();
  703. let input = stdin_lines.next().unwrap().unwrap();
  704. if input != "y" {
  705. println!("Not erasing.");
  706. return Ok(());
  707. }
  708. // Program will treat the zero authority as erased.
  709. let new_authority = Pubkey::new_from_array([0u8; 32]);
  710. idl_set_authority(program_id, None, new_authority)?;
  711. Ok(())
  712. }
  713. // Write the idl to the account buffer, chopping up the IDL into pieces
  714. // and sending multiple transactions in the event the IDL doesn't fit into
  715. // a single transaction.
  716. fn idl_write(cfg: &Config, program_id: &Pubkey, idl: &Idl, idl_address: Pubkey) -> Result<()> {
  717. // Remove the metadata before deploy.
  718. let mut idl = idl.clone();
  719. idl.metadata = None;
  720. // Misc.
  721. let keypair = solana_sdk::signature::read_keypair_file(&cfg.wallet.to_string())
  722. .map_err(|_| anyhow!("Unable to read keypair file"))?;
  723. let client = RpcClient::new(cfg.cluster.url().to_string());
  724. // Serialize and compress the idl.
  725. let idl_data = {
  726. let json_bytes = serde_json::to_vec(&idl)?;
  727. let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
  728. e.write_all(&json_bytes)?;
  729. e.finish()?
  730. };
  731. const MAX_WRITE_SIZE: usize = 1000;
  732. let mut offset = 0;
  733. while offset < idl_data.len() {
  734. // Instruction data.
  735. let data = {
  736. let start = offset;
  737. let end = std::cmp::min(offset + MAX_WRITE_SIZE, idl_data.len());
  738. serialize_idl_ix(anchor_lang::idl::IdlInstruction::Write {
  739. data: idl_data[start..end].to_vec(),
  740. })?
  741. };
  742. // Instruction accounts.
  743. let accounts = vec![
  744. AccountMeta::new(idl_address, false),
  745. AccountMeta::new_readonly(keypair.pubkey(), true),
  746. ];
  747. // Instruction.
  748. let ix = Instruction {
  749. program_id: *program_id,
  750. accounts,
  751. data,
  752. };
  753. // Send transaction.
  754. let (recent_hash, _fee_calc) = client.get_recent_blockhash()?;
  755. let tx = Transaction::new_signed_with_payer(
  756. &[ix],
  757. Some(&keypair.pubkey()),
  758. &[&keypair],
  759. recent_hash,
  760. );
  761. client.send_and_confirm_transaction_with_spinner_and_config(
  762. &tx,
  763. CommitmentConfig::confirmed(),
  764. RpcSendTransactionConfig {
  765. skip_preflight: true,
  766. ..RpcSendTransactionConfig::default()
  767. },
  768. )?;
  769. offset += MAX_WRITE_SIZE;
  770. }
  771. Ok(())
  772. }
  773. fn idl_parse(file: String, out: Option<String>) -> Result<()> {
  774. let idl = extract_idl(&file)?;
  775. let out = match out {
  776. None => OutFile::Stdout,
  777. Some(out) => OutFile::File(PathBuf::from(out)),
  778. };
  779. write_idl(&idl, out)
  780. }
  781. fn idl_fetch(address: Pubkey, out: Option<String>) -> Result<()> {
  782. let idl = fetch_idl(address)?;
  783. let out = match out {
  784. None => OutFile::Stdout,
  785. Some(out) => OutFile::File(PathBuf::from(out)),
  786. };
  787. write_idl(&idl, out)
  788. }
  789. fn write_idl(idl: &Idl, out: OutFile) -> Result<()> {
  790. let idl_json = serde_json::to_string_pretty(idl)?;
  791. match out {
  792. OutFile::Stdout => println!("{}", idl_json),
  793. OutFile::File(out) => std::fs::write(out, idl_json)?,
  794. };
  795. Ok(())
  796. }
  797. enum OutFile {
  798. Stdout,
  799. File(PathBuf),
  800. }
  801. // Builds, deploys, and tests all workspace programs in a single command.
  802. fn test(skip_deploy: bool, skip_local_validator: bool, file: Option<String>) -> Result<()> {
  803. with_workspace(|cfg, _path, _cargo| {
  804. // Bootup validator, if needed.
  805. let validator_handle = match cfg.cluster.url() {
  806. "http://127.0.0.1:8899" => {
  807. build(None, false)?;
  808. let flags = match skip_deploy {
  809. true => None,
  810. false => Some(genesis_flags(cfg)?),
  811. };
  812. match skip_local_validator {
  813. true => None,
  814. false => Some(start_test_validator(cfg, flags)?),
  815. }
  816. }
  817. _ => {
  818. if !skip_deploy {
  819. build(None, false)?;
  820. deploy(None, None)?;
  821. }
  822. None
  823. }
  824. };
  825. // Setup log reader.
  826. let log_streams = stream_logs(&cfg.cluster.url());
  827. // Run the tests.
  828. let test_result: Result<_> = {
  829. let ts_config_exist = Path::new("tsconfig.json").exists();
  830. let mut args = vec!["-t", "1000000"];
  831. if let Some(ref file) = file {
  832. args.push(file);
  833. } else if ts_config_exist {
  834. args.push("tests/**/*.spec.ts");
  835. } else {
  836. args.push("tests/");
  837. }
  838. let exit = match ts_config_exist {
  839. true => std::process::Command::new("ts-mocha")
  840. .arg("-p")
  841. .arg("./tsconfig.json")
  842. .args(args)
  843. .env("ANCHOR_PROVIDER_URL", cfg.cluster.url())
  844. .stdout(Stdio::inherit())
  845. .stderr(Stdio::inherit())
  846. .output()
  847. .map_err(anyhow::Error::from)
  848. .with_context(|| "ts-mocha"),
  849. false => std::process::Command::new("mocha")
  850. .args(args)
  851. .env("ANCHOR_PROVIDER_URL", cfg.cluster.url())
  852. .stdout(Stdio::inherit())
  853. .stderr(Stdio::inherit())
  854. .output()
  855. .map_err(anyhow::Error::from)
  856. .with_context(|| "mocha"),
  857. };
  858. exit
  859. };
  860. // Check all errors and shut down.
  861. if let Some(mut child) = validator_handle {
  862. if let Err(err) = child.kill() {
  863. println!("Failed to kill subprocess {}: {}", child.id(), err);
  864. }
  865. }
  866. for mut child in log_streams? {
  867. if let Err(err) = child.kill() {
  868. println!("Failed to kill subprocess {}: {}", child.id(), err);
  869. }
  870. }
  871. match test_result {
  872. Ok(exit) => {
  873. if !exit.status.success() {
  874. std::process::exit(exit.status.code().unwrap());
  875. }
  876. }
  877. Err(err) => {
  878. println!("Failed to run test: {:#}", err)
  879. }
  880. }
  881. Ok(())
  882. })
  883. }
  884. // Returns the solana-test-validator flags to embed the workspace programs
  885. // in the genesis block. This allows us to run tests without every deploying.
  886. fn genesis_flags(cfg: &Config) -> Result<Vec<String>> {
  887. let mut flags = Vec::new();
  888. for mut program in read_all_programs()? {
  889. let binary_path = program.binary_path().display().to_string();
  890. let kp = Keypair::generate(&mut OsRng);
  891. let address = kp.pubkey().to_string();
  892. flags.push("--bpf-program".to_string());
  893. flags.push(address.clone());
  894. flags.push(binary_path);
  895. // Add program address to the IDL.
  896. program.idl.metadata = Some(serde_json::to_value(IdlTestMetadata { address })?);
  897. // Persist it.
  898. let idl_out = PathBuf::from("target/idl")
  899. .join(&program.idl.name)
  900. .with_extension("json");
  901. write_idl(&program.idl, OutFile::File(idl_out))?;
  902. }
  903. if let Some(test) = cfg.test.as_ref() {
  904. for entry in &test.genesis {
  905. flags.push("--bpf-program".to_string());
  906. flags.push(entry.address.clone());
  907. flags.push(entry.program.clone());
  908. }
  909. }
  910. Ok(flags)
  911. }
  912. fn stream_logs(url: &str) -> Result<Vec<std::process::Child>> {
  913. let program_logs_dir = ".anchor/program-logs";
  914. if Path::new(program_logs_dir).exists() {
  915. std::fs::remove_dir_all(program_logs_dir)?;
  916. }
  917. fs::create_dir_all(program_logs_dir)?;
  918. let mut handles = vec![];
  919. for program in read_all_programs()? {
  920. let mut file = File::open(&format!("target/idl/{}.json", program.lib_name))?;
  921. let mut contents = vec![];
  922. file.read_to_end(&mut contents)?;
  923. let idl: Idl = serde_json::from_slice(&contents)?;
  924. let metadata = idl
  925. .metadata
  926. .ok_or_else(|| anyhow!("Program address not found."))?;
  927. let metadata: IdlTestMetadata = serde_json::from_value(metadata)?;
  928. let log_file = File::create(format!(
  929. "{}/{}.{}.log",
  930. program_logs_dir, metadata.address, program.idl.name
  931. ))?;
  932. let stdio = std::process::Stdio::from(log_file);
  933. let child = std::process::Command::new("solana")
  934. .arg("logs")
  935. .arg(metadata.address)
  936. .arg("--url")
  937. .arg(url)
  938. .stdout(stdio)
  939. .spawn()?;
  940. handles.push(child);
  941. }
  942. Ok(handles)
  943. }
  944. #[derive(Debug, Serialize, Deserialize)]
  945. pub struct IdlTestMetadata {
  946. address: String,
  947. }
  948. fn start_test_validator(cfg: &Config, flags: Option<Vec<String>>) -> Result<Child> {
  949. fs::create_dir_all(".anchor")?;
  950. let test_ledger_filename = ".anchor/test-ledger";
  951. let test_ledger_log_filename = ".anchor/test-ledger-log.txt";
  952. if Path::new(test_ledger_filename).exists() {
  953. std::fs::remove_dir_all(test_ledger_filename)?;
  954. }
  955. if Path::new(test_ledger_log_filename).exists() {
  956. std::fs::remove_file(test_ledger_log_filename)?;
  957. }
  958. // Start a validator for testing.
  959. let test_validator_stdout = File::create(test_ledger_log_filename)?;
  960. let test_validator_stderr = test_validator_stdout.try_clone()?;
  961. let validator_handle = std::process::Command::new("solana-test-validator")
  962. .arg("--ledger")
  963. .arg(test_ledger_filename)
  964. .arg("--mint")
  965. .arg(cfg.wallet_kp()?.pubkey().to_string())
  966. .args(flags.unwrap_or_default())
  967. .stdout(Stdio::from(test_validator_stdout))
  968. .stderr(Stdio::from(test_validator_stderr))
  969. .spawn()
  970. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  971. // Wait for the validator to be ready.
  972. let client = RpcClient::new("http://localhost:8899".to_string());
  973. let mut count = 0;
  974. let ms_wait = 5000;
  975. while count < ms_wait {
  976. let r = client.get_recent_blockhash();
  977. if r.is_ok() {
  978. break;
  979. }
  980. std::thread::sleep(std::time::Duration::from_millis(1));
  981. count += 1;
  982. }
  983. if count == 5000 {
  984. println!("Unable to start test validator.");
  985. std::process::exit(1);
  986. }
  987. Ok(validator_handle)
  988. }
  989. // TODO: Testing and deploys should use separate sections of metadata.
  990. // Similarly, each network should have separate metadata.
  991. fn deploy(url: Option<String>, keypair: Option<String>) -> Result<()> {
  992. _deploy(url, keypair).map(|_| ())
  993. }
  994. fn _deploy(url: Option<String>, keypair: Option<String>) -> Result<Vec<(Pubkey, Program)>> {
  995. with_workspace(|cfg, _path, _cargo| {
  996. // Fallback to config vars if not provided via CLI.
  997. let url = url.unwrap_or_else(|| cfg.cluster.url().to_string());
  998. let keypair = keypair.unwrap_or_else(|| cfg.wallet.to_string());
  999. // Deploy the programs.
  1000. println!("Deploying workspace: {}", url);
  1001. println!("Upgrade authority: {}", keypair);
  1002. let mut programs = Vec::new();
  1003. for mut program in read_all_programs()? {
  1004. let binary_path = program.binary_path().display().to_string();
  1005. println!("Deploying {}...", binary_path);
  1006. // Write the program's keypair filepath. This forces a new deploy
  1007. // address.
  1008. let program_kp = Keypair::generate(&mut OsRng);
  1009. let mut file = File::create(program.anchor_keypair_path())?;
  1010. file.write_all(format!("{:?}", &program_kp.to_bytes()).as_bytes())?;
  1011. // Send deploy transactions.
  1012. let exit = std::process::Command::new("solana")
  1013. .arg("program")
  1014. .arg("deploy")
  1015. .arg("--url")
  1016. .arg(&url)
  1017. .arg("--keypair")
  1018. .arg(&keypair)
  1019. .arg("--program-id")
  1020. .arg(program.anchor_keypair_path().display().to_string())
  1021. .arg(&binary_path)
  1022. .stdout(Stdio::inherit())
  1023. .stderr(Stdio::inherit())
  1024. .output()
  1025. .expect("Must deploy");
  1026. if !exit.status.success() {
  1027. println!("There was a problem deploying: {:?}.", exit);
  1028. std::process::exit(exit.status.code().unwrap_or(1));
  1029. }
  1030. // Add program address to the IDL.
  1031. program.idl.metadata = Some(serde_json::to_value(IdlTestMetadata {
  1032. address: program_kp.pubkey().to_string(),
  1033. })?);
  1034. // Persist it.
  1035. let idl_out = PathBuf::from("target/idl")
  1036. .join(&program.idl.name)
  1037. .with_extension("json");
  1038. write_idl(&program.idl, OutFile::File(idl_out))?;
  1039. programs.push((program_kp.pubkey(), program))
  1040. }
  1041. println!("Deploy success");
  1042. Ok(programs)
  1043. })
  1044. }
  1045. fn upgrade(program_id: Pubkey, program_filepath: String) -> Result<()> {
  1046. let path: PathBuf = program_filepath.parse().unwrap();
  1047. let program_filepath = path.canonicalize()?.display().to_string();
  1048. with_workspace(|cfg, _path, _cargo| {
  1049. let exit = std::process::Command::new("solana")
  1050. .arg("program")
  1051. .arg("deploy")
  1052. .arg("--url")
  1053. .arg(cfg.cluster.url())
  1054. .arg("--keypair")
  1055. .arg(&cfg.wallet.to_string())
  1056. .arg("--program-id")
  1057. .arg(program_id.to_string())
  1058. .arg(&program_filepath)
  1059. .stdout(Stdio::inherit())
  1060. .stderr(Stdio::inherit())
  1061. .output()
  1062. .expect("Must deploy");
  1063. if !exit.status.success() {
  1064. println!("There was a problem deploying: {:?}.", exit);
  1065. std::process::exit(exit.status.code().unwrap_or(1));
  1066. }
  1067. Ok(())
  1068. })
  1069. }
  1070. fn launch(url: Option<String>, keypair: Option<String>, verifiable: bool) -> Result<()> {
  1071. // Build and deploy.
  1072. build(None, verifiable)?;
  1073. let programs = _deploy(url.clone(), keypair.clone())?;
  1074. with_workspace(|cfg, _path, _cargo| {
  1075. let url = url.unwrap_or_else(|| cfg.cluster.url().to_string());
  1076. let keypair = keypair.unwrap_or_else(|| cfg.wallet.to_string());
  1077. // Add metadata to all IDLs.
  1078. for (address, program) in programs {
  1079. // Store the IDL on chain.
  1080. let idl_address = create_idl_account(&cfg, &keypair, &address, &program.idl)?;
  1081. println!("IDL account created: {}", idl_address.to_string());
  1082. }
  1083. // Run migration script.
  1084. if Path::new("migrations/deploy.js").exists() || Path::new("migrations/deploy.ts").exists()
  1085. {
  1086. migrate(Some(url))?;
  1087. }
  1088. Ok(())
  1089. })
  1090. }
  1091. // with_workspace ensures the current working directory is always the top level
  1092. // workspace directory, i.e., where the `Anchor.toml` file is located, before
  1093. // and after the closure invocation.
  1094. //
  1095. // The closure passed into this function must never change the working directory
  1096. // to be outside the workspace. Doing so will have undefined behavior.
  1097. fn with_workspace<R>(f: impl FnOnce(&Config, PathBuf, Option<PathBuf>) -> R) -> R {
  1098. set_workspace_dir_or_exit();
  1099. clear_program_keys().unwrap();
  1100. let (cfg, cfg_path, cargo_toml) = Config::discover()
  1101. .expect("Previously set the workspace dir")
  1102. .expect("Anchor.toml must always exist");
  1103. let r = f(&cfg, cfg_path, cargo_toml);
  1104. set_workspace_dir_or_exit();
  1105. clear_program_keys().unwrap();
  1106. r
  1107. }
  1108. // The Solana CLI doesn't redeploy a program if this file exists.
  1109. // So remove it to make all commands explicit.
  1110. fn clear_program_keys() -> Result<()> {
  1111. for program in read_all_programs()? {
  1112. let anchor_keypair_path = program.anchor_keypair_path();
  1113. if Path::exists(&anchor_keypair_path) {
  1114. std::fs::remove_file(anchor_keypair_path).expect("Always remove");
  1115. }
  1116. }
  1117. Ok(())
  1118. }
  1119. fn create_idl_account(
  1120. cfg: &Config,
  1121. keypair_path: &str,
  1122. program_id: &Pubkey,
  1123. idl: &Idl,
  1124. ) -> Result<Pubkey> {
  1125. // Misc.
  1126. let idl_address = IdlAccount::address(program_id);
  1127. let keypair = solana_sdk::signature::read_keypair_file(keypair_path)
  1128. .map_err(|_| anyhow!("Unable to read keypair file"))?;
  1129. let client = RpcClient::new(cfg.cluster.url().to_string());
  1130. let idl_data = serialize_idl(idl)?;
  1131. // Run `Create instruction.
  1132. {
  1133. let data = serialize_idl_ix(anchor_lang::idl::IdlInstruction::Create {
  1134. data_len: (idl_data.len() as u64) * 2, // Double for future growth.
  1135. })?;
  1136. let program_signer = Pubkey::find_program_address(&[], program_id).0;
  1137. let accounts = vec![
  1138. AccountMeta::new_readonly(keypair.pubkey(), true),
  1139. AccountMeta::new(idl_address, false),
  1140. AccountMeta::new_readonly(program_signer, false),
  1141. AccountMeta::new_readonly(solana_program::system_program::ID, false),
  1142. AccountMeta::new_readonly(*program_id, false),
  1143. AccountMeta::new_readonly(solana_program::sysvar::rent::ID, false),
  1144. ];
  1145. let ix = Instruction {
  1146. program_id: *program_id,
  1147. accounts,
  1148. data,
  1149. };
  1150. let (recent_hash, _fee_calc) = client.get_recent_blockhash()?;
  1151. let tx = Transaction::new_signed_with_payer(
  1152. &[ix],
  1153. Some(&keypair.pubkey()),
  1154. &[&keypair],
  1155. recent_hash,
  1156. );
  1157. client.send_and_confirm_transaction_with_spinner_and_config(
  1158. &tx,
  1159. CommitmentConfig::confirmed(),
  1160. RpcSendTransactionConfig {
  1161. skip_preflight: true,
  1162. ..RpcSendTransactionConfig::default()
  1163. },
  1164. )?;
  1165. }
  1166. // Write directly to the IDL account buffer.
  1167. idl_write(cfg, program_id, idl, IdlAccount::address(program_id))?;
  1168. Ok(idl_address)
  1169. }
  1170. fn create_idl_buffer(
  1171. cfg: &Config,
  1172. keypair_path: &str,
  1173. program_id: &Pubkey,
  1174. idl: &Idl,
  1175. ) -> Result<Pubkey> {
  1176. let keypair = solana_sdk::signature::read_keypair_file(keypair_path)
  1177. .map_err(|_| anyhow!("Unable to read keypair file"))?;
  1178. let client = RpcClient::new(cfg.cluster.url().to_string());
  1179. let buffer = Keypair::generate(&mut OsRng);
  1180. // Creates the new buffer account with the system program.
  1181. let create_account_ix = {
  1182. let space = 8 + 32 + 4 + serialize_idl(idl)?.len() as usize;
  1183. let lamports = client.get_minimum_balance_for_rent_exemption(space)?;
  1184. solana_sdk::system_instruction::create_account(
  1185. &keypair.pubkey(),
  1186. &buffer.pubkey(),
  1187. lamports,
  1188. space as u64,
  1189. program_id,
  1190. )
  1191. };
  1192. // Program instruction to create the buffer.
  1193. let create_buffer_ix = {
  1194. let accounts = vec![
  1195. AccountMeta::new(buffer.pubkey(), false),
  1196. AccountMeta::new_readonly(keypair.pubkey(), true),
  1197. AccountMeta::new_readonly(sysvar::rent::ID, false),
  1198. ];
  1199. let mut data = anchor_lang::idl::IDL_IX_TAG.to_le_bytes().to_vec();
  1200. data.append(&mut IdlInstruction::CreateBuffer.try_to_vec()?);
  1201. Instruction {
  1202. program_id: *program_id,
  1203. accounts,
  1204. data,
  1205. }
  1206. };
  1207. // Build the transaction.
  1208. let (recent_hash, _fee_calc) = client.get_recent_blockhash()?;
  1209. let tx = Transaction::new_signed_with_payer(
  1210. &[create_account_ix, create_buffer_ix],
  1211. Some(&keypair.pubkey()),
  1212. &[&keypair, &buffer],
  1213. recent_hash,
  1214. );
  1215. // Send the transaction.
  1216. client.send_and_confirm_transaction_with_spinner_and_config(
  1217. &tx,
  1218. CommitmentConfig::confirmed(),
  1219. RpcSendTransactionConfig {
  1220. skip_preflight: true,
  1221. ..RpcSendTransactionConfig::default()
  1222. },
  1223. )?;
  1224. Ok(buffer.pubkey())
  1225. }
  1226. // Serialize and compress the idl.
  1227. fn serialize_idl(idl: &Idl) -> Result<Vec<u8>> {
  1228. let json_bytes = serde_json::to_vec(idl)?;
  1229. let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
  1230. e.write_all(&json_bytes)?;
  1231. e.finish().map_err(Into::into)
  1232. }
  1233. fn serialize_idl_ix(ix_inner: anchor_lang::idl::IdlInstruction) -> Result<Vec<u8>> {
  1234. let mut data = anchor_lang::idl::IDL_IX_TAG.to_le_bytes().to_vec();
  1235. data.append(&mut ix_inner.try_to_vec()?);
  1236. Ok(data)
  1237. }
  1238. fn migrate(url: Option<String>) -> Result<()> {
  1239. with_workspace(|cfg, _path, _cargo| {
  1240. println!("Running migration deploy script");
  1241. let url = url.unwrap_or_else(|| cfg.cluster.url().to_string());
  1242. let cur_dir = std::env::current_dir()?;
  1243. let module_path = cur_dir.join("migrations/deploy.js");
  1244. let ts_config_exist = Path::new("tsconfig.json").exists();
  1245. let ts_deploy_file_exists = Path::new("migrations/deploy.ts").exists();
  1246. if ts_config_exist && ts_deploy_file_exists {
  1247. let ts_module_path = cur_dir.join("migrations/deploy.ts");
  1248. let exit = std::process::Command::new("tsc")
  1249. .arg(&ts_module_path)
  1250. .stdout(Stdio::inherit())
  1251. .stderr(Stdio::inherit())
  1252. .output()?;
  1253. if !exit.status.success() {
  1254. std::process::exit(exit.status.code().unwrap());
  1255. }
  1256. };
  1257. let deploy_script_host_str =
  1258. template::deploy_script_host(&url, &module_path.display().to_string());
  1259. if !Path::new(".anchor").exists() {
  1260. fs::create_dir(".anchor")?;
  1261. }
  1262. std::env::set_current_dir(".anchor")?;
  1263. std::fs::write("deploy.js", deploy_script_host_str)?;
  1264. let exit = std::process::Command::new("node")
  1265. .arg("deploy.js")
  1266. .stdout(Stdio::inherit())
  1267. .stderr(Stdio::inherit())
  1268. .output()?;
  1269. if ts_config_exist && ts_deploy_file_exists {
  1270. std::fs::remove_file(&module_path)
  1271. .map_err(|_| anyhow!("Unable to remove file {}", module_path.display()))?;
  1272. }
  1273. if !exit.status.success() {
  1274. println!("Deploy failed.");
  1275. std::process::exit(exit.status.code().unwrap());
  1276. }
  1277. println!("Deploy complete.");
  1278. Ok(())
  1279. })
  1280. }
  1281. fn set_workspace_dir_or_exit() {
  1282. let d = match Config::discover() {
  1283. Err(_) => {
  1284. println!("Not in anchor workspace.");
  1285. std::process::exit(1);
  1286. }
  1287. Ok(d) => d,
  1288. };
  1289. match d {
  1290. None => {
  1291. println!("Not in anchor workspace.");
  1292. std::process::exit(1);
  1293. }
  1294. Some((_cfg, cfg_path, _inside_cargo)) => {
  1295. match cfg_path.parent() {
  1296. None => {
  1297. println!("Unable to make new program");
  1298. }
  1299. Some(parent) => {
  1300. if std::env::set_current_dir(&parent).is_err() {
  1301. println!("Not in anchor workspace.");
  1302. std::process::exit(1);
  1303. }
  1304. }
  1305. };
  1306. }
  1307. }
  1308. }
  1309. #[cfg(feature = "dev")]
  1310. fn airdrop(url: Option<String>) -> Result<()> {
  1311. let url = url.unwrap_or_else(|| "https://devnet.solana.com".to_string());
  1312. loop {
  1313. let exit = std::process::Command::new("solana")
  1314. .arg("airdrop")
  1315. .arg("10")
  1316. .arg("--url")
  1317. .arg(&url)
  1318. .stdout(Stdio::inherit())
  1319. .stderr(Stdio::inherit())
  1320. .output()
  1321. .expect("Must airdrop");
  1322. if !exit.status.success() {
  1323. println!("There was a problem airdropping: {:?}.", exit);
  1324. std::process::exit(exit.status.code().unwrap_or(1));
  1325. }
  1326. std::thread::sleep(std::time::Duration::from_millis(10000));
  1327. }
  1328. }