lib.rs 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158
  1. use crate::config::{
  2. AnchorPackage, BootstrapMode, BuildConfig, Config, ConfigOverride, Manifest, ProgramDeployment,
  3. ProgramWorkspace, ScriptsConfig, TestValidator, WithPath, SHUTDOWN_WAIT, STARTUP_WAIT,
  4. };
  5. use anchor_client::Cluster;
  6. use anchor_lang::idl::{IdlAccount, IdlInstruction, ERASED_AUTHORITY};
  7. use anchor_lang::{AccountDeserialize, AnchorDeserialize, AnchorSerialize};
  8. use anchor_syn::idl::Idl;
  9. use anyhow::{anyhow, Context, Result};
  10. use clap::Parser;
  11. use flate2::read::GzDecoder;
  12. use flate2::read::ZlibDecoder;
  13. use flate2::write::{GzEncoder, ZlibEncoder};
  14. use flate2::Compression;
  15. use heck::SnakeCase;
  16. use rand::rngs::OsRng;
  17. use reqwest::blocking::multipart::{Form, Part};
  18. use reqwest::blocking::Client;
  19. use semver::{Version, VersionReq};
  20. use serde::{Deserialize, Serialize};
  21. use solana_client::rpc_client::RpcClient;
  22. use solana_client::rpc_config::RpcSendTransactionConfig;
  23. use solana_program::instruction::{AccountMeta, Instruction};
  24. use solana_sdk::account_utils::StateMut;
  25. use solana_sdk::bpf_loader;
  26. use solana_sdk::bpf_loader_deprecated;
  27. use solana_sdk::bpf_loader_upgradeable::{self, UpgradeableLoaderState};
  28. use solana_sdk::commitment_config::CommitmentConfig;
  29. use solana_sdk::pubkey::Pubkey;
  30. use solana_sdk::signature::Keypair;
  31. use solana_sdk::signature::Signer;
  32. use solana_sdk::sysvar;
  33. use solana_sdk::transaction::Transaction;
  34. use std::collections::BTreeMap;
  35. use std::collections::HashMap;
  36. use std::collections::HashSet;
  37. use std::ffi::OsString;
  38. use std::fs::{self, File};
  39. use std::io::prelude::*;
  40. use std::path::{Path, PathBuf};
  41. use std::process::{Child, Stdio};
  42. use std::str::FromStr;
  43. use std::string::ToString;
  44. use tar::Archive;
  45. pub mod config;
  46. mod path;
  47. pub mod template;
  48. // Version of the docker image.
  49. pub const VERSION: &str = env!("CARGO_PKG_VERSION");
  50. pub const DOCKER_BUILDER_VERSION: &str = VERSION;
  51. #[derive(Debug, Parser)]
  52. #[clap(version = VERSION)]
  53. pub struct Opts {
  54. #[clap(flatten)]
  55. pub cfg_override: ConfigOverride,
  56. #[clap(subcommand)]
  57. pub command: Command,
  58. }
  59. #[derive(Debug, Parser)]
  60. pub enum Command {
  61. /// Initializes a workspace.
  62. Init {
  63. name: String,
  64. #[clap(short, long)]
  65. javascript: bool,
  66. #[clap(long)]
  67. no_git: bool,
  68. },
  69. /// Builds the workspace.
  70. Build {
  71. /// Output directory for the IDL.
  72. #[clap(short, long)]
  73. idl: Option<String>,
  74. /// True if the build should not fail even if there are
  75. /// no "CHECK" comments where normally required
  76. #[clap(long)]
  77. skip_lint: bool,
  78. /// Output directory for the TypeScript IDL.
  79. #[clap(short = 't', long)]
  80. idl_ts: Option<String>,
  81. /// True if the build artifact needs to be deterministic and verifiable.
  82. #[clap(short, long)]
  83. verifiable: bool,
  84. #[clap(short, long)]
  85. program_name: Option<String>,
  86. /// Version of the Solana toolchain to use. For --verifiable builds
  87. /// only.
  88. #[clap(short, long)]
  89. solana_version: Option<String>,
  90. /// Docker image to use. For --verifiable builds only.
  91. #[clap(short, long)]
  92. docker_image: Option<String>,
  93. /// Bootstrap docker image from scratch, installing all requirements for
  94. /// verifiable builds. Only works for debian-based images.
  95. #[clap(arg_enum, short, long, default_value = "none")]
  96. bootstrap: BootstrapMode,
  97. /// Arguments to pass to the underlying `cargo build-bpf` command
  98. #[clap(
  99. required = false,
  100. takes_value = true,
  101. multiple_values = true,
  102. last = true
  103. )]
  104. cargo_args: Vec<String>,
  105. /// Suppress doc strings in IDL output
  106. #[clap(long)]
  107. no_docs: bool,
  108. },
  109. /// Expands macros (wrapper around cargo expand)
  110. ///
  111. /// Use it in a program folder to expand program
  112. ///
  113. /// Use it in a workspace but outside a program
  114. /// folder to expand the entire workspace
  115. Expand {
  116. /// Expand only this program
  117. #[clap(short, long)]
  118. program_name: Option<String>,
  119. /// Arguments to pass to the underlying `cargo expand` command
  120. #[clap(
  121. required = false,
  122. takes_value = true,
  123. multiple_values = true,
  124. last = true
  125. )]
  126. cargo_args: Vec<String>,
  127. },
  128. /// Verifies the on-chain bytecode matches the locally compiled artifact.
  129. /// Run this command inside a program subdirectory, i.e., in the dir
  130. /// containing the program's Cargo.toml.
  131. Verify {
  132. /// The deployed program to compare against.
  133. program_id: Pubkey,
  134. #[clap(short, long)]
  135. program_name: Option<String>,
  136. /// Version of the Solana toolchain to use. For --verifiable builds
  137. /// only.
  138. #[clap(short, long)]
  139. solana_version: Option<String>,
  140. /// Docker image to use. For --verifiable builds only.
  141. #[clap(short, long)]
  142. docker_image: Option<String>,
  143. /// Bootstrap docker image from scratch, installing all requirements for
  144. /// verifiable builds. Only works for debian-based images.
  145. #[clap(arg_enum, short, long, default_value = "none")]
  146. bootstrap: BootstrapMode,
  147. /// Arguments to pass to the underlying `cargo build-bpf` command.
  148. #[clap(
  149. required = false,
  150. takes_value = true,
  151. multiple_values = true,
  152. last = true
  153. )]
  154. cargo_args: Vec<String>,
  155. },
  156. /// Runs integration tests against a localnetwork.
  157. Test {
  158. /// Use this flag if you want to run tests against previously deployed
  159. /// programs.
  160. #[clap(long)]
  161. skip_deploy: bool,
  162. /// True if the build should not fail even if there are
  163. /// no "CHECK" comments where normally required
  164. #[clap(long)]
  165. skip_lint: bool,
  166. /// Flag to skip starting a local validator, if the configured cluster
  167. /// url is a localnet.
  168. #[clap(long)]
  169. skip_local_validator: bool,
  170. /// Flag to skip building the program in the workspace,
  171. /// use this to save time when running test and the program code is not altered.
  172. #[clap(long)]
  173. skip_build: bool,
  174. /// Flag to keep the local validator running after tests
  175. /// to be able to check the transactions.
  176. #[clap(long)]
  177. detach: bool,
  178. #[clap(multiple_values = true)]
  179. args: Vec<String>,
  180. /// Arguments to pass to the underlying `cargo build-bpf` command.
  181. #[clap(
  182. required = false,
  183. takes_value = true,
  184. multiple_values = true,
  185. last = true
  186. )]
  187. cargo_args: Vec<String>,
  188. },
  189. /// Creates a new program.
  190. New { name: String },
  191. /// Commands for interacting with interface definitions.
  192. Idl {
  193. #[clap(subcommand)]
  194. subcmd: IdlCommand,
  195. },
  196. /// Remove all artifacts from the target directory except program keypairs.
  197. Clean,
  198. /// Deploys each program in the workspace.
  199. Deploy {
  200. /// Only deploy this program
  201. #[clap(short, long)]
  202. program_name: Option<String>,
  203. /// Keypair of the program (filepath) (requires program-name)
  204. #[clap(long, requires = "program-name")]
  205. program_keypair: Option<String>,
  206. },
  207. /// Runs the deploy migration script.
  208. Migrate,
  209. /// Deploys, initializes an IDL, and migrates all in one command.
  210. /// Upgrades a single program. The configured wallet must be the upgrade
  211. /// authority.
  212. Upgrade {
  213. /// The program to upgrade.
  214. #[clap(short, long)]
  215. program_id: Pubkey,
  216. /// Filepath to the new program binary.
  217. program_filepath: String,
  218. },
  219. #[cfg(feature = "dev")]
  220. /// Runs an airdrop loop, continuously funding the configured wallet.
  221. Airdrop {
  222. #[clap(short, long)]
  223. url: Option<String>,
  224. },
  225. /// Cluster commands.
  226. Cluster {
  227. #[clap(subcommand)]
  228. subcmd: ClusterCommand,
  229. },
  230. /// Starts a node shell with an Anchor client setup according to the local
  231. /// config.
  232. Shell,
  233. /// Runs the script defined by the current workspace's Anchor.toml.
  234. Run {
  235. /// The name of the script to run.
  236. script: String,
  237. },
  238. /// Saves an api token from the registry locally.
  239. Login {
  240. /// API access token.
  241. token: String,
  242. },
  243. /// Publishes a verified build to the Anchor registry.
  244. Publish {
  245. /// The name of the program to publish.
  246. program: String,
  247. /// Arguments to pass to the underlying `cargo build-bpf` command.
  248. #[clap(
  249. required = false,
  250. takes_value = true,
  251. multiple_values = true,
  252. last = true
  253. )]
  254. cargo_args: Vec<String>,
  255. },
  256. /// Keypair commands.
  257. Keys {
  258. #[clap(subcommand)]
  259. subcmd: KeysCommand,
  260. },
  261. /// Localnet commands.
  262. Localnet {
  263. /// Flag to skip building the program in the workspace,
  264. /// use this to save time when running test and the program code is not altered.
  265. #[clap(long)]
  266. skip_build: bool,
  267. /// Use this flag if you want to run tests against previously deployed
  268. /// programs.
  269. #[clap(long)]
  270. skip_deploy: bool,
  271. /// True if the build should not fail even if there are
  272. /// no "CHECK" comments where normally required
  273. #[clap(long)]
  274. skip_lint: bool,
  275. /// Arguments to pass to the underlying `cargo build-bpf` command.
  276. #[clap(
  277. required = false,
  278. takes_value = true,
  279. multiple_values = true,
  280. last = true
  281. )]
  282. cargo_args: Vec<String>,
  283. },
  284. }
  285. #[derive(Debug, Parser)]
  286. pub enum KeysCommand {
  287. List,
  288. }
  289. #[derive(Debug, Parser)]
  290. pub enum IdlCommand {
  291. /// Initializes a program's IDL account. Can only be run once.
  292. Init {
  293. program_id: Pubkey,
  294. #[clap(short, long)]
  295. filepath: String,
  296. },
  297. /// Writes an IDL into a buffer account. This can be used with SetBuffer
  298. /// to perform an upgrade.
  299. WriteBuffer {
  300. program_id: Pubkey,
  301. #[clap(short, long)]
  302. filepath: String,
  303. },
  304. /// Sets a new IDL buffer for the program.
  305. SetBuffer {
  306. program_id: Pubkey,
  307. /// Address of the buffer account to set as the idl on the program.
  308. #[clap(short, long)]
  309. buffer: Pubkey,
  310. },
  311. /// Upgrades the IDL to the new file. An alias for first writing and then
  312. /// then setting the idl buffer account.
  313. Upgrade {
  314. program_id: Pubkey,
  315. #[clap(short, long)]
  316. filepath: String,
  317. },
  318. /// Sets a new authority on the IDL account.
  319. SetAuthority {
  320. /// The IDL account buffer to set the authority of. If none is given,
  321. /// then the canonical IDL account is used.
  322. address: Option<Pubkey>,
  323. /// Program to change the IDL authority.
  324. #[clap(short, long)]
  325. program_id: Pubkey,
  326. /// New authority of the IDL account.
  327. #[clap(short, long)]
  328. new_authority: Pubkey,
  329. },
  330. /// Command to remove the ability to modify the IDL account. This should
  331. /// likely be used in conjection with eliminating an "upgrade authority" on
  332. /// the program.
  333. EraseAuthority {
  334. #[clap(short, long)]
  335. program_id: Pubkey,
  336. },
  337. /// Outputs the authority for the IDL account.
  338. Authority {
  339. /// The program to view.
  340. program_id: Pubkey,
  341. },
  342. /// Parses an IDL from source.
  343. Parse {
  344. /// Path to the program's interface definition.
  345. #[clap(short, long)]
  346. file: String,
  347. /// Output file for the IDL (stdout if not specified).
  348. #[clap(short, long)]
  349. out: Option<String>,
  350. /// Output file for the TypeScript IDL.
  351. #[clap(short = 't', long)]
  352. out_ts: Option<String>,
  353. /// Suppress doc strings in output
  354. #[clap(long)]
  355. no_docs: bool,
  356. },
  357. /// Fetches an IDL for the given address from a cluster.
  358. /// The address can be a program, IDL account, or IDL buffer.
  359. Fetch {
  360. address: Pubkey,
  361. /// Output file for the idl (stdout if not specified).
  362. #[clap(short, long)]
  363. out: Option<String>,
  364. },
  365. }
  366. #[derive(Debug, Parser)]
  367. pub enum ClusterCommand {
  368. /// Prints common cluster urls.
  369. List,
  370. }
  371. pub fn entry(opts: Opts) -> Result<()> {
  372. match opts.command {
  373. Command::Init {
  374. name,
  375. javascript,
  376. no_git,
  377. } => init(&opts.cfg_override, name, javascript, no_git),
  378. Command::New { name } => new(&opts.cfg_override, name),
  379. Command::Build {
  380. idl,
  381. idl_ts,
  382. verifiable,
  383. program_name,
  384. solana_version,
  385. docker_image,
  386. bootstrap,
  387. cargo_args,
  388. skip_lint,
  389. no_docs,
  390. } => build(
  391. &opts.cfg_override,
  392. idl,
  393. idl_ts,
  394. verifiable,
  395. skip_lint,
  396. program_name,
  397. solana_version,
  398. docker_image,
  399. bootstrap,
  400. None,
  401. None,
  402. cargo_args,
  403. no_docs,
  404. ),
  405. Command::Verify {
  406. program_id,
  407. program_name,
  408. solana_version,
  409. docker_image,
  410. bootstrap,
  411. cargo_args,
  412. } => verify(
  413. &opts.cfg_override,
  414. program_id,
  415. program_name,
  416. solana_version,
  417. docker_image,
  418. bootstrap,
  419. cargo_args,
  420. ),
  421. Command::Clean => clean(&opts.cfg_override),
  422. Command::Deploy {
  423. program_name,
  424. program_keypair,
  425. } => deploy(&opts.cfg_override, program_name, program_keypair),
  426. Command::Expand {
  427. program_name,
  428. cargo_args,
  429. } => expand(&opts.cfg_override, program_name, &cargo_args),
  430. Command::Upgrade {
  431. program_id,
  432. program_filepath,
  433. } => upgrade(&opts.cfg_override, program_id, program_filepath),
  434. Command::Idl { subcmd } => idl(&opts.cfg_override, subcmd),
  435. Command::Migrate => migrate(&opts.cfg_override),
  436. Command::Test {
  437. skip_deploy,
  438. skip_local_validator,
  439. skip_build,
  440. detach,
  441. args,
  442. cargo_args,
  443. skip_lint,
  444. } => test(
  445. &opts.cfg_override,
  446. skip_deploy,
  447. skip_local_validator,
  448. skip_build,
  449. skip_lint,
  450. detach,
  451. args,
  452. cargo_args,
  453. ),
  454. #[cfg(feature = "dev")]
  455. Command::Airdrop { .. } => airdrop(&opts.cfg_override),
  456. Command::Cluster { subcmd } => cluster(subcmd),
  457. Command::Shell => shell(&opts.cfg_override),
  458. Command::Run { script } => run(&opts.cfg_override, script),
  459. Command::Login { token } => login(&opts.cfg_override, token),
  460. Command::Publish {
  461. program,
  462. cargo_args,
  463. } => publish(&opts.cfg_override, program, cargo_args),
  464. Command::Keys { subcmd } => keys(&opts.cfg_override, subcmd),
  465. Command::Localnet {
  466. skip_build,
  467. skip_deploy,
  468. skip_lint,
  469. cargo_args,
  470. } => localnet(
  471. &opts.cfg_override,
  472. skip_build,
  473. skip_deploy,
  474. skip_lint,
  475. cargo_args,
  476. ),
  477. }
  478. }
  479. fn init(cfg_override: &ConfigOverride, name: String, javascript: bool, no_git: bool) -> Result<()> {
  480. if Config::discover(cfg_override)?.is_some() {
  481. return Err(anyhow!("Workspace already initialized"));
  482. }
  483. // The list is taken from https://doc.rust-lang.org/reference/keywords.html.
  484. let key_words = [
  485. "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn",
  486. "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
  487. "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe",
  488. "use", "where", "while", "async", "await", "dyn", "abstract", "become", "box", "do",
  489. "final", "macro", "override", "priv", "typeof", "unsized", "virtual", "yield", "try",
  490. "unique",
  491. ];
  492. if key_words.contains(&name[..].into()) {
  493. return Err(anyhow!(
  494. "{} is a reserved word in rust, name your project something else!",
  495. name
  496. ));
  497. } else if name.chars().next().unwrap().is_numeric() {
  498. return Err(anyhow!(
  499. "Cannot start project name with numbers, name your project something else!"
  500. ));
  501. }
  502. fs::create_dir(name.clone())?;
  503. std::env::set_current_dir(&name)?;
  504. fs::create_dir("app")?;
  505. let mut cfg = Config::default();
  506. cfg.scripts.insert(
  507. "test".to_owned(),
  508. if javascript {
  509. "yarn run mocha -t 1000000 tests/"
  510. } else {
  511. "yarn run ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts"
  512. }
  513. .to_owned(),
  514. );
  515. let mut localnet = BTreeMap::new();
  516. localnet.insert(
  517. name.to_snake_case(),
  518. ProgramDeployment {
  519. address: template::default_program_id(),
  520. path: None,
  521. idl: None,
  522. },
  523. );
  524. cfg.programs.insert(Cluster::Localnet, localnet);
  525. let toml = cfg.to_string();
  526. fs::write("Anchor.toml", toml)?;
  527. // Build virtual manifest.
  528. fs::write("Cargo.toml", template::virtual_manifest())?;
  529. // Initialize .gitignore file
  530. fs::write(".gitignore", template::git_ignore())?;
  531. // Initialize .prettierignore file
  532. fs::write(".prettierignore", template::prettier_ignore())?;
  533. // Build the program.
  534. fs::create_dir("programs")?;
  535. new_program(&name)?;
  536. // Build the test suite.
  537. fs::create_dir("tests")?;
  538. // Build the migrations directory.
  539. fs::create_dir("migrations")?;
  540. if javascript {
  541. // Build javascript config
  542. let mut package_json = File::create("package.json")?;
  543. package_json.write_all(template::package_json().as_bytes())?;
  544. let mut mocha = File::create(&format!("tests/{}.js", name))?;
  545. mocha.write_all(template::mocha(&name).as_bytes())?;
  546. let mut deploy = File::create("migrations/deploy.js")?;
  547. deploy.write_all(template::deploy_script().as_bytes())?;
  548. } else {
  549. // Build typescript config
  550. let mut ts_config = File::create("tsconfig.json")?;
  551. ts_config.write_all(template::ts_config().as_bytes())?;
  552. let mut ts_package_json = File::create("package.json")?;
  553. ts_package_json.write_all(template::ts_package_json().as_bytes())?;
  554. let mut deploy = File::create("migrations/deploy.ts")?;
  555. deploy.write_all(template::ts_deploy_script().as_bytes())?;
  556. let mut mocha = File::create(&format!("tests/{}.ts", name))?;
  557. mocha.write_all(template::ts_mocha(&name).as_bytes())?;
  558. }
  559. // Install node modules.
  560. let yarn_result = std::process::Command::new("yarn")
  561. .stdout(Stdio::inherit())
  562. .stderr(Stdio::inherit())
  563. .output()
  564. .map_err(|e| anyhow::format_err!("yarn install failed: {}", e.to_string()))?;
  565. if !yarn_result.status.success() {
  566. println!("Failed yarn install will attempt to npm install");
  567. std::process::Command::new("npm")
  568. .arg("install")
  569. .stdout(Stdio::inherit())
  570. .stderr(Stdio::inherit())
  571. .output()
  572. .map_err(|e| anyhow::format_err!("npm install failed: {}", e.to_string()))?;
  573. println!("Failed to install node dependencies")
  574. }
  575. if !no_git {
  576. let git_result = std::process::Command::new("git")
  577. .arg("init")
  578. .stdout(Stdio::inherit())
  579. .stderr(Stdio::inherit())
  580. .output()
  581. .map_err(|e| anyhow::format_err!("git init failed: {}", e.to_string()))?;
  582. if !git_result.status.success() {
  583. eprintln!("Failed to automatically initialize a new git repository");
  584. }
  585. }
  586. println!("{} initialized", name);
  587. Ok(())
  588. }
  589. // Creates a new program crate in the `programs/<name>` directory.
  590. fn new(cfg_override: &ConfigOverride, name: String) -> Result<()> {
  591. with_workspace(cfg_override, |cfg| {
  592. match cfg.path().parent() {
  593. None => {
  594. println!("Unable to make new program");
  595. }
  596. Some(parent) => {
  597. std::env::set_current_dir(&parent)?;
  598. new_program(&name)?;
  599. println!("Created new program.");
  600. }
  601. };
  602. Ok(())
  603. })
  604. }
  605. // Creates a new program crate in the current directory with `name`.
  606. fn new_program(name: &str) -> Result<()> {
  607. fs::create_dir(&format!("programs/{}", name))?;
  608. fs::create_dir(&format!("programs/{}/src/", name))?;
  609. let mut cargo_toml = File::create(&format!("programs/{}/Cargo.toml", name))?;
  610. cargo_toml.write_all(template::cargo_toml(name).as_bytes())?;
  611. let mut xargo_toml = File::create(&format!("programs/{}/Xargo.toml", name))?;
  612. xargo_toml.write_all(template::xargo_toml().as_bytes())?;
  613. let mut lib_rs = File::create(&format!("programs/{}/src/lib.rs", name))?;
  614. lib_rs.write_all(template::lib_rs(name).as_bytes())?;
  615. Ok(())
  616. }
  617. pub fn expand(
  618. cfg_override: &ConfigOverride,
  619. program_name: Option<String>,
  620. cargo_args: &[String],
  621. ) -> Result<()> {
  622. // Change to the workspace member directory, if needed.
  623. if let Some(program_name) = program_name.as_ref() {
  624. cd_member(cfg_override, program_name)?;
  625. }
  626. let workspace_cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  627. let cfg_parent = workspace_cfg.path().parent().expect("Invalid Anchor.toml");
  628. let cargo = Manifest::discover()?;
  629. let expansions_path = cfg_parent.join(".anchor/expanded-macros");
  630. fs::create_dir_all(&expansions_path)?;
  631. match cargo {
  632. // No Cargo.toml found, expand entire workspace
  633. None => expand_all(&workspace_cfg, expansions_path, cargo_args),
  634. // Cargo.toml is at root of workspace, expand entire workspace
  635. Some(cargo) if cargo.path().parent() == workspace_cfg.path().parent() => {
  636. expand_all(&workspace_cfg, expansions_path, cargo_args)
  637. }
  638. // Reaching this arm means Cargo.toml belongs to a single package. Expand it.
  639. Some(cargo) => expand_program(
  640. // If we found Cargo.toml, it must be in a directory so unwrap is safe
  641. cargo.path().parent().unwrap().to_path_buf(),
  642. expansions_path,
  643. cargo_args,
  644. ),
  645. }
  646. }
  647. fn expand_all(
  648. workspace_cfg: &WithPath<Config>,
  649. expansions_path: PathBuf,
  650. cargo_args: &[String],
  651. ) -> Result<()> {
  652. let cur_dir = std::env::current_dir()?;
  653. for p in workspace_cfg.get_program_list()? {
  654. expand_program(p, expansions_path.clone(), cargo_args)?;
  655. }
  656. std::env::set_current_dir(cur_dir)?;
  657. Ok(())
  658. }
  659. fn expand_program(
  660. program_path: PathBuf,
  661. expansions_path: PathBuf,
  662. cargo_args: &[String],
  663. ) -> Result<()> {
  664. let cargo = Manifest::from_path(program_path.join("Cargo.toml"))
  665. .map_err(|_| anyhow!("Could not find Cargo.toml for program"))?;
  666. let target_dir_arg = {
  667. let mut target_dir_arg = OsString::from("--target-dir=");
  668. target_dir_arg.push(expansions_path.join("expand-target"));
  669. target_dir_arg
  670. };
  671. let package_name = &cargo
  672. .package
  673. .as_ref()
  674. .ok_or_else(|| anyhow!("Cargo config is missing a package"))?
  675. .name;
  676. let program_expansions_path = expansions_path.join(package_name);
  677. fs::create_dir_all(&program_expansions_path)?;
  678. let exit = std::process::Command::new("cargo")
  679. .arg("expand")
  680. .arg(target_dir_arg)
  681. .arg(&format!("--package={}", package_name))
  682. .args(cargo_args)
  683. .stderr(Stdio::inherit())
  684. .output()
  685. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  686. if !exit.status.success() {
  687. eprintln!("'anchor expand' failed. Perhaps you have not installed 'cargo-expand'? https://github.com/dtolnay/cargo-expand#installation");
  688. std::process::exit(exit.status.code().unwrap_or(1));
  689. }
  690. let version = cargo.version();
  691. let time = chrono::Utc::now().to_string().replace(' ', "_");
  692. let file_path =
  693. program_expansions_path.join(format!("{}-{}-{}.rs", package_name, version, time));
  694. fs::write(&file_path, &exit.stdout).map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  695. println!(
  696. "Expanded {} into file {}\n",
  697. package_name,
  698. file_path.to_string_lossy()
  699. );
  700. Ok(())
  701. }
  702. #[allow(clippy::too_many_arguments)]
  703. pub fn build(
  704. cfg_override: &ConfigOverride,
  705. idl: Option<String>,
  706. idl_ts: Option<String>,
  707. verifiable: bool,
  708. skip_lint: bool,
  709. program_name: Option<String>,
  710. solana_version: Option<String>,
  711. docker_image: Option<String>,
  712. bootstrap: BootstrapMode,
  713. stdout: Option<File>, // Used for the package registry server.
  714. stderr: Option<File>, // Used for the package registry server.
  715. cargo_args: Vec<String>,
  716. no_docs: bool,
  717. ) -> Result<()> {
  718. // Change to the workspace member directory, if needed.
  719. if let Some(program_name) = program_name.as_ref() {
  720. cd_member(cfg_override, program_name)?;
  721. }
  722. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  723. let build_config = BuildConfig {
  724. verifiable,
  725. solana_version: solana_version.or_else(|| cfg.solana_version.clone()),
  726. docker_image: docker_image.unwrap_or_else(|| cfg.docker()),
  727. bootstrap,
  728. };
  729. let cfg_parent = cfg.path().parent().expect("Invalid Anchor.toml");
  730. let cargo = Manifest::discover()?;
  731. let idl_out = match idl {
  732. Some(idl) => Some(PathBuf::from(idl)),
  733. None => Some(cfg_parent.join("target/idl")),
  734. };
  735. fs::create_dir_all(idl_out.as_ref().unwrap())?;
  736. let idl_ts_out = match idl_ts {
  737. Some(idl_ts) => Some(PathBuf::from(idl_ts)),
  738. None => Some(cfg_parent.join("target/types")),
  739. };
  740. fs::create_dir_all(idl_ts_out.as_ref().unwrap())?;
  741. if !&cfg.workspace.types.is_empty() {
  742. fs::create_dir_all(cfg_parent.join(&cfg.workspace.types))?;
  743. };
  744. match cargo {
  745. // No Cargo.toml so build the entire workspace.
  746. None => build_all(
  747. &cfg,
  748. cfg.path(),
  749. idl_out,
  750. idl_ts_out,
  751. &build_config,
  752. stdout,
  753. stderr,
  754. cargo_args,
  755. skip_lint,
  756. no_docs,
  757. )?,
  758. // If the Cargo.toml is at the root, build the entire workspace.
  759. Some(cargo) if cargo.path().parent() == cfg.path().parent() => build_all(
  760. &cfg,
  761. cfg.path(),
  762. idl_out,
  763. idl_ts_out,
  764. &build_config,
  765. stdout,
  766. stderr,
  767. cargo_args,
  768. skip_lint,
  769. no_docs,
  770. )?,
  771. // Cargo.toml represents a single package. Build it.
  772. Some(cargo) => build_cwd(
  773. &cfg,
  774. cargo.path().to_path_buf(),
  775. idl_out,
  776. idl_ts_out,
  777. &build_config,
  778. stdout,
  779. stderr,
  780. cargo_args,
  781. skip_lint,
  782. no_docs,
  783. )?,
  784. }
  785. set_workspace_dir_or_exit();
  786. Ok(())
  787. }
  788. #[allow(clippy::too_many_arguments)]
  789. fn build_all(
  790. cfg: &WithPath<Config>,
  791. cfg_path: &Path,
  792. idl_out: Option<PathBuf>,
  793. idl_ts_out: Option<PathBuf>,
  794. build_config: &BuildConfig,
  795. stdout: Option<File>, // Used for the package registry server.
  796. stderr: Option<File>, // Used for the package registry server.
  797. cargo_args: Vec<String>,
  798. skip_lint: bool,
  799. no_docs: bool,
  800. ) -> Result<()> {
  801. let cur_dir = std::env::current_dir()?;
  802. let r = match cfg_path.parent() {
  803. None => Err(anyhow!("Invalid Anchor.toml at {}", cfg_path.display())),
  804. Some(_parent) => {
  805. for p in cfg.get_program_list()? {
  806. build_cwd(
  807. cfg,
  808. p.join("Cargo.toml"),
  809. idl_out.clone(),
  810. idl_ts_out.clone(),
  811. build_config,
  812. stdout.as_ref().map(|f| f.try_clone()).transpose()?,
  813. stderr.as_ref().map(|f| f.try_clone()).transpose()?,
  814. cargo_args.clone(),
  815. skip_lint,
  816. no_docs,
  817. )?;
  818. }
  819. Ok(())
  820. }
  821. };
  822. std::env::set_current_dir(cur_dir)?;
  823. r
  824. }
  825. // Runs the build command outside of a workspace.
  826. #[allow(clippy::too_many_arguments)]
  827. fn build_cwd(
  828. cfg: &WithPath<Config>,
  829. cargo_toml: PathBuf,
  830. idl_out: Option<PathBuf>,
  831. idl_ts_out: Option<PathBuf>,
  832. build_config: &BuildConfig,
  833. stdout: Option<File>,
  834. stderr: Option<File>,
  835. cargo_args: Vec<String>,
  836. skip_lint: bool,
  837. no_docs: bool,
  838. ) -> Result<()> {
  839. match cargo_toml.parent() {
  840. None => return Err(anyhow!("Unable to find parent")),
  841. Some(p) => std::env::set_current_dir(&p)?,
  842. };
  843. match build_config.verifiable {
  844. false => _build_cwd(cfg, idl_out, idl_ts_out, skip_lint, cargo_args),
  845. true => build_cwd_verifiable(
  846. cfg,
  847. cargo_toml,
  848. build_config,
  849. stdout,
  850. stderr,
  851. skip_lint,
  852. cargo_args,
  853. no_docs,
  854. ),
  855. }
  856. }
  857. // Builds an anchor program in a docker image and copies the build artifacts
  858. // into the `target/` directory.
  859. #[allow(clippy::too_many_arguments)]
  860. fn build_cwd_verifiable(
  861. cfg: &WithPath<Config>,
  862. cargo_toml: PathBuf,
  863. build_config: &BuildConfig,
  864. stdout: Option<File>,
  865. stderr: Option<File>,
  866. skip_lint: bool,
  867. cargo_args: Vec<String>,
  868. no_docs: bool,
  869. ) -> Result<()> {
  870. // Create output dirs.
  871. let workspace_dir = cfg.path().parent().unwrap().canonicalize()?;
  872. fs::create_dir_all(workspace_dir.join("target/verifiable"))?;
  873. fs::create_dir_all(workspace_dir.join("target/idl"))?;
  874. fs::create_dir_all(workspace_dir.join("target/types"))?;
  875. if !&cfg.workspace.types.is_empty() {
  876. fs::create_dir_all(workspace_dir.join(&cfg.workspace.types))?;
  877. }
  878. let container_name = "anchor-program";
  879. // Build the binary in docker.
  880. let result = docker_build(
  881. cfg,
  882. container_name,
  883. cargo_toml,
  884. build_config,
  885. stdout,
  886. stderr,
  887. cargo_args,
  888. );
  889. match &result {
  890. Err(e) => {
  891. eprintln!("Error during Docker build: {:?}", e);
  892. }
  893. Ok(_) => {
  894. // Build the idl.
  895. println!("Extracting the IDL");
  896. if let Ok(Some(idl)) = extract_idl(cfg, "src/lib.rs", skip_lint, no_docs) {
  897. // Write out the JSON file.
  898. println!("Writing the IDL file");
  899. let out_file = workspace_dir.join(format!("target/idl/{}.json", idl.name));
  900. write_idl(&idl, OutFile::File(out_file))?;
  901. // Write out the TypeScript type.
  902. println!("Writing the .ts file");
  903. let ts_file = workspace_dir.join(format!("target/types/{}.ts", idl.name));
  904. fs::write(&ts_file, template::idl_ts(&idl)?)?;
  905. // Copy out the TypeScript type.
  906. if !&cfg.workspace.types.is_empty() {
  907. fs::copy(
  908. ts_file,
  909. workspace_dir
  910. .join(&cfg.workspace.types)
  911. .join(idl.name)
  912. .with_extension("ts"),
  913. )?;
  914. }
  915. }
  916. println!("Build success");
  917. }
  918. }
  919. result
  920. }
  921. fn docker_build(
  922. cfg: &WithPath<Config>,
  923. container_name: &str,
  924. cargo_toml: PathBuf,
  925. build_config: &BuildConfig,
  926. stdout: Option<File>,
  927. stderr: Option<File>,
  928. cargo_args: Vec<String>,
  929. ) -> Result<()> {
  930. let binary_name = Manifest::from_path(&cargo_toml)?.lib_name()?;
  931. // Docker vars.
  932. let workdir = Path::new("/workdir");
  933. let volume_mount = format!(
  934. "{}:{}",
  935. cfg.path().parent().unwrap().canonicalize()?.display(),
  936. workdir.to_str().unwrap(),
  937. );
  938. println!("Using image {:?}", build_config.docker_image);
  939. // Start the docker image running detached in the background.
  940. let target_dir = workdir.join("docker-target");
  941. println!("Run docker image");
  942. let exit = std::process::Command::new("docker")
  943. .args(&[
  944. "run",
  945. "-it",
  946. "-d",
  947. "--name",
  948. container_name,
  949. "--env",
  950. &format!(
  951. "CARGO_TARGET_DIR={}",
  952. target_dir.as_path().to_str().unwrap()
  953. ),
  954. "-v",
  955. &volume_mount,
  956. "-w",
  957. workdir.to_str().unwrap(),
  958. &build_config.docker_image,
  959. "bash",
  960. ])
  961. .stdout(Stdio::inherit())
  962. .stderr(Stdio::inherit())
  963. .output()
  964. .map_err(|e| anyhow::format_err!("Docker build failed: {}", e.to_string()))?;
  965. if !exit.status.success() {
  966. return Err(anyhow!("Failed to build program"));
  967. }
  968. let result = docker_prep(container_name, build_config).and_then(|_| {
  969. let cfg_parent = cfg.path().parent().unwrap();
  970. docker_build_bpf(
  971. container_name,
  972. cargo_toml.as_path(),
  973. cfg_parent,
  974. target_dir.as_path(),
  975. binary_name,
  976. stdout,
  977. stderr,
  978. cargo_args,
  979. )
  980. });
  981. // Cleanup regardless of errors
  982. docker_cleanup(container_name, target_dir.as_path())?;
  983. // Done.
  984. result
  985. }
  986. fn docker_prep(container_name: &str, build_config: &BuildConfig) -> Result<()> {
  987. // Set the solana version in the container, if given. Otherwise use the
  988. // default.
  989. match build_config.bootstrap {
  990. BootstrapMode::Debian => {
  991. // Install build requirements
  992. docker_exec(container_name, &["apt", "update"])?;
  993. docker_exec(
  994. container_name,
  995. &["apt", "install", "-y", "curl", "build-essential"],
  996. )?;
  997. // Install Rust
  998. docker_exec(
  999. container_name,
  1000. &["curl", "https://sh.rustup.rs", "-sfo", "rustup.sh"],
  1001. )?;
  1002. docker_exec(container_name, &["sh", "rustup.sh", "-y"])?;
  1003. docker_exec(container_name, &["rm", "-f", "rustup.sh"])?;
  1004. }
  1005. BootstrapMode::None => {}
  1006. }
  1007. if let Some(solana_version) = &build_config.solana_version {
  1008. println!("Using solana version: {}", solana_version);
  1009. // Install Solana CLI
  1010. docker_exec(
  1011. container_name,
  1012. &[
  1013. "curl",
  1014. "-sSfL",
  1015. &format!("https://release.solana.com/v{0}/install", solana_version,),
  1016. "-o",
  1017. "solana_installer.sh",
  1018. ],
  1019. )?;
  1020. docker_exec(container_name, &["sh", "solana_installer.sh"])?;
  1021. docker_exec(container_name, &["rm", "-f", "solana_installer.sh"])?;
  1022. }
  1023. Ok(())
  1024. }
  1025. #[allow(clippy::too_many_arguments)]
  1026. fn docker_build_bpf(
  1027. container_name: &str,
  1028. cargo_toml: &Path,
  1029. cfg_parent: &Path,
  1030. target_dir: &Path,
  1031. binary_name: String,
  1032. stdout: Option<File>,
  1033. stderr: Option<File>,
  1034. cargo_args: Vec<String>,
  1035. ) -> Result<()> {
  1036. let manifest_path =
  1037. pathdiff::diff_paths(cargo_toml.canonicalize()?, cfg_parent.canonicalize()?)
  1038. .ok_or_else(|| anyhow!("Unable to diff paths"))?;
  1039. println!(
  1040. "Building {} manifest: {:?}",
  1041. binary_name,
  1042. manifest_path.display()
  1043. );
  1044. // Execute the build.
  1045. let exit = std::process::Command::new("docker")
  1046. .args(&[
  1047. "exec",
  1048. "--env",
  1049. "PATH=/root/.local/share/solana/install/active_release/bin:/root/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  1050. container_name,
  1051. "cargo",
  1052. "build-bpf",
  1053. "--manifest-path",
  1054. &manifest_path.display().to_string(),
  1055. ])
  1056. .args(cargo_args)
  1057. .stdout(match stdout {
  1058. None => Stdio::inherit(),
  1059. Some(f) => f.into(),
  1060. })
  1061. .stderr(match stderr {
  1062. None => Stdio::inherit(),
  1063. Some(f) => f.into(),
  1064. })
  1065. .output()
  1066. .map_err(|e| anyhow::format_err!("Docker build failed: {}", e.to_string()))?;
  1067. if !exit.status.success() {
  1068. return Err(anyhow!("Failed to build program"));
  1069. }
  1070. // Copy the binary out of the docker image.
  1071. println!("Copying out the build artifacts");
  1072. let out_file = cfg_parent
  1073. .canonicalize()?
  1074. .join(format!("target/verifiable/{}.so", binary_name))
  1075. .display()
  1076. .to_string();
  1077. // This requires the target directory of any built program to be located at
  1078. // the root of the workspace.
  1079. let mut bin_path = target_dir.join("deploy");
  1080. bin_path.push(format!("{}.so", binary_name));
  1081. let bin_artifact = format!(
  1082. "{}:{}",
  1083. container_name,
  1084. bin_path.as_path().to_str().unwrap()
  1085. );
  1086. let exit = std::process::Command::new("docker")
  1087. .args(&["cp", &bin_artifact, &out_file])
  1088. .stdout(Stdio::inherit())
  1089. .stderr(Stdio::inherit())
  1090. .output()
  1091. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  1092. if !exit.status.success() {
  1093. Err(anyhow!(
  1094. "Failed to copy binary out of docker. Is the target directory set correctly?"
  1095. ))
  1096. } else {
  1097. Ok(())
  1098. }
  1099. }
  1100. fn docker_cleanup(container_name: &str, target_dir: &Path) -> Result<()> {
  1101. // Wipe the generated docker-target dir.
  1102. println!("Cleaning up the docker target directory");
  1103. docker_exec(container_name, &["rm", "-rf", target_dir.to_str().unwrap()])?;
  1104. // Remove the docker image.
  1105. println!("Removing the docker container");
  1106. let exit = std::process::Command::new("docker")
  1107. .args(&["rm", "-f", container_name])
  1108. .stdout(Stdio::inherit())
  1109. .stderr(Stdio::inherit())
  1110. .output()
  1111. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  1112. if !exit.status.success() {
  1113. println!("Unable to remove the docker container");
  1114. std::process::exit(exit.status.code().unwrap_or(1));
  1115. }
  1116. Ok(())
  1117. }
  1118. fn docker_exec(container_name: &str, args: &[&str]) -> Result<()> {
  1119. let exit = std::process::Command::new("docker")
  1120. .args([&["exec", container_name], args].concat())
  1121. .stdout(Stdio::inherit())
  1122. .stderr(Stdio::inherit())
  1123. .output()
  1124. .map_err(|e| anyhow!("Failed to run command \"{:?}\": {:?}", args, e))?;
  1125. if !exit.status.success() {
  1126. Err(anyhow!("Failed to run command: {:?}", args))
  1127. } else {
  1128. Ok(())
  1129. }
  1130. }
  1131. fn _build_cwd(
  1132. cfg: &WithPath<Config>,
  1133. idl_out: Option<PathBuf>,
  1134. idl_ts_out: Option<PathBuf>,
  1135. skip_lint: bool,
  1136. cargo_args: Vec<String>,
  1137. ) -> Result<()> {
  1138. let exit = std::process::Command::new("cargo")
  1139. .arg("build-bpf")
  1140. .args(cargo_args)
  1141. .stdout(Stdio::inherit())
  1142. .stderr(Stdio::inherit())
  1143. .output()
  1144. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  1145. if !exit.status.success() {
  1146. std::process::exit(exit.status.code().unwrap_or(1));
  1147. }
  1148. // Always assume idl is located at src/lib.rs.
  1149. if let Some(idl) = extract_idl(cfg, "src/lib.rs", skip_lint, false)? {
  1150. // JSON out path.
  1151. let out = match idl_out {
  1152. None => PathBuf::from(".").join(&idl.name).with_extension("json"),
  1153. Some(o) => PathBuf::from(&o.join(&idl.name).with_extension("json")),
  1154. };
  1155. // TS out path.
  1156. let ts_out = match idl_ts_out {
  1157. None => PathBuf::from(".").join(&idl.name).with_extension("ts"),
  1158. Some(o) => PathBuf::from(&o.join(&idl.name).with_extension("ts")),
  1159. };
  1160. // Write out the JSON file.
  1161. write_idl(&idl, OutFile::File(out))?;
  1162. // Write out the TypeScript type.
  1163. fs::write(&ts_out, template::idl_ts(&idl)?)?;
  1164. // Copy out the TypeScript type.
  1165. let cfg_parent = cfg.path().parent().expect("Invalid Anchor.toml");
  1166. if !&cfg.workspace.types.is_empty() {
  1167. fs::copy(
  1168. &ts_out,
  1169. cfg_parent
  1170. .join(&cfg.workspace.types)
  1171. .join(&idl.name)
  1172. .with_extension("ts"),
  1173. )?;
  1174. }
  1175. }
  1176. Ok(())
  1177. }
  1178. fn verify(
  1179. cfg_override: &ConfigOverride,
  1180. program_id: Pubkey,
  1181. program_name: Option<String>,
  1182. solana_version: Option<String>,
  1183. docker_image: Option<String>,
  1184. bootstrap: BootstrapMode,
  1185. cargo_args: Vec<String>,
  1186. ) -> Result<()> {
  1187. // Change to the workspace member directory, if needed.
  1188. if let Some(program_name) = program_name.as_ref() {
  1189. cd_member(cfg_override, program_name)?;
  1190. }
  1191. // Proceed with the command.
  1192. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  1193. let cargo = Manifest::discover()?.ok_or_else(|| anyhow!("Cargo.toml not found"))?;
  1194. // Build the program we want to verify.
  1195. let cur_dir = std::env::current_dir()?;
  1196. build(
  1197. cfg_override,
  1198. None, // idl
  1199. None, // idl ts
  1200. true, // verifiable
  1201. true, // skip lint
  1202. None, // program name
  1203. solana_version.or_else(|| cfg.solana_version.clone()), // solana version
  1204. docker_image, // docker image
  1205. bootstrap, // bootstrap docker image
  1206. None, // stdout
  1207. None, // stderr
  1208. cargo_args,
  1209. false,
  1210. )?;
  1211. std::env::set_current_dir(&cur_dir)?;
  1212. // Verify binary.
  1213. let binary_name = cargo.lib_name()?;
  1214. let bin_path = cfg
  1215. .path()
  1216. .parent()
  1217. .ok_or_else(|| anyhow!("Unable to find workspace root"))?
  1218. .join("target/verifiable/")
  1219. .join(format!("{}.so", binary_name));
  1220. let url = cluster_url(&cfg, &cfg.test_validator);
  1221. let bin_ver = verify_bin(program_id, &bin_path, &url)?;
  1222. if !bin_ver.is_verified {
  1223. println!("Error: Binaries don't match");
  1224. std::process::exit(1);
  1225. }
  1226. // Verify IDL (only if it's not a buffer account).
  1227. if let Some(local_idl) = extract_idl(&cfg, "src/lib.rs", true, false)? {
  1228. if bin_ver.state != BinVerificationState::Buffer {
  1229. let deployed_idl = fetch_idl(cfg_override, program_id)?;
  1230. if local_idl != deployed_idl {
  1231. println!("Error: IDLs don't match");
  1232. std::process::exit(1);
  1233. }
  1234. }
  1235. }
  1236. println!("{} is verified.", program_id);
  1237. Ok(())
  1238. }
  1239. fn cd_member(cfg_override: &ConfigOverride, program_name: &str) -> Result<()> {
  1240. // Change directories to the given `program_name`, if given.
  1241. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  1242. for program in cfg.read_all_programs()? {
  1243. let cargo_toml = program.path.join("Cargo.toml");
  1244. if !cargo_toml.exists() {
  1245. return Err(anyhow!(
  1246. "Did not find Cargo.toml at the path: {}",
  1247. program.path.display()
  1248. ));
  1249. }
  1250. let p_lib_name = Manifest::from_path(&cargo_toml)?.lib_name()?;
  1251. if program_name == p_lib_name {
  1252. std::env::set_current_dir(&program.path)?;
  1253. return Ok(());
  1254. }
  1255. }
  1256. return Err(anyhow!("{} is not part of the workspace", program_name,));
  1257. }
  1258. pub fn verify_bin(program_id: Pubkey, bin_path: &Path, cluster: &str) -> Result<BinVerification> {
  1259. let client = RpcClient::new(cluster.to_string());
  1260. // Get the deployed build artifacts.
  1261. let (deployed_bin, state) = {
  1262. let account = client
  1263. .get_account_with_commitment(&program_id, CommitmentConfig::default())?
  1264. .value
  1265. .map_or(Err(anyhow!("Account not found")), Ok)?;
  1266. if account.owner == bpf_loader::id() || account.owner == bpf_loader_deprecated::id() {
  1267. let bin = account.data.to_vec();
  1268. let state = BinVerificationState::ProgramData {
  1269. slot: 0, // Need to look through the transaction history.
  1270. upgrade_authority_address: None,
  1271. };
  1272. (bin, state)
  1273. } else if account.owner == bpf_loader_upgradeable::id() {
  1274. match account.state()? {
  1275. UpgradeableLoaderState::Program {
  1276. programdata_address,
  1277. } => {
  1278. let account = client
  1279. .get_account_with_commitment(
  1280. &programdata_address,
  1281. CommitmentConfig::default(),
  1282. )?
  1283. .value
  1284. .map_or(Err(anyhow!("Account not found")), Ok)?;
  1285. let bin = account.data
  1286. [UpgradeableLoaderState::programdata_data_offset().unwrap_or(0)..]
  1287. .to_vec();
  1288. if let UpgradeableLoaderState::ProgramData {
  1289. slot,
  1290. upgrade_authority_address,
  1291. } = account.state()?
  1292. {
  1293. let state = BinVerificationState::ProgramData {
  1294. slot,
  1295. upgrade_authority_address,
  1296. };
  1297. (bin, state)
  1298. } else {
  1299. return Err(anyhow!("Expected program data"));
  1300. }
  1301. }
  1302. UpgradeableLoaderState::Buffer { .. } => {
  1303. let offset = UpgradeableLoaderState::buffer_data_offset().unwrap_or(0);
  1304. (
  1305. account.data[offset..].to_vec(),
  1306. BinVerificationState::Buffer,
  1307. )
  1308. }
  1309. _ => {
  1310. return Err(anyhow!(
  1311. "Invalid program id, not a buffer or program account"
  1312. ))
  1313. }
  1314. }
  1315. } else {
  1316. return Err(anyhow!(
  1317. "Invalid program id, not owned by any loader program"
  1318. ));
  1319. }
  1320. };
  1321. let mut local_bin = {
  1322. let mut f = File::open(bin_path)?;
  1323. let mut contents = vec![];
  1324. f.read_to_end(&mut contents)?;
  1325. contents
  1326. };
  1327. // The deployed program probably has zero bytes appended. The default is
  1328. // 2x the binary size in case of an upgrade.
  1329. if local_bin.len() < deployed_bin.len() {
  1330. local_bin.append(&mut vec![0; deployed_bin.len() - local_bin.len()]);
  1331. }
  1332. // Finally, check the bytes.
  1333. let is_verified = local_bin == deployed_bin;
  1334. Ok(BinVerification { state, is_verified })
  1335. }
  1336. #[derive(PartialEq)]
  1337. pub struct BinVerification {
  1338. pub state: BinVerificationState,
  1339. pub is_verified: bool,
  1340. }
  1341. #[derive(PartialEq)]
  1342. pub enum BinVerificationState {
  1343. Buffer,
  1344. ProgramData {
  1345. slot: u64,
  1346. upgrade_authority_address: Option<Pubkey>,
  1347. },
  1348. }
  1349. // Fetches an IDL for the given program_id.
  1350. fn fetch_idl(cfg_override: &ConfigOverride, idl_addr: Pubkey) -> Result<Idl> {
  1351. let url = match Config::discover(cfg_override)? {
  1352. Some(cfg) => cluster_url(&cfg, &cfg.test_validator),
  1353. None => {
  1354. // If the command is not run inside a workspace,
  1355. // cluster_url will be used from default solana config
  1356. // provider.cluster option can be used to override this
  1357. if let Some(cluster) = cfg_override.cluster.clone() {
  1358. cluster.url().to_string()
  1359. } else {
  1360. config::get_solana_cfg_url()?
  1361. }
  1362. }
  1363. };
  1364. let client = RpcClient::new(url);
  1365. let mut account = client
  1366. .get_account_with_commitment(&idl_addr, CommitmentConfig::processed())?
  1367. .value
  1368. .map_or(Err(anyhow!("Account not found")), Ok)?;
  1369. if account.executable {
  1370. let idl_addr = IdlAccount::address(&idl_addr);
  1371. account = client
  1372. .get_account_with_commitment(&idl_addr, CommitmentConfig::processed())?
  1373. .value
  1374. .map_or(Err(anyhow!("Account not found")), Ok)?;
  1375. }
  1376. // Cut off account discriminator.
  1377. let mut d: &[u8] = &account.data[8..];
  1378. let idl_account: IdlAccount = AnchorDeserialize::deserialize(&mut d)?;
  1379. let mut z = ZlibDecoder::new(&idl_account.data[..]);
  1380. let mut s = Vec::new();
  1381. z.read_to_end(&mut s)?;
  1382. serde_json::from_slice(&s[..]).map_err(Into::into)
  1383. }
  1384. fn extract_idl(
  1385. cfg: &WithPath<Config>,
  1386. file: &str,
  1387. skip_lint: bool,
  1388. no_docs: bool,
  1389. ) -> Result<Option<Idl>> {
  1390. let file = shellexpand::tilde(file);
  1391. let manifest_from_path = std::env::current_dir()?.join(PathBuf::from(&*file).parent().unwrap());
  1392. let cargo = Manifest::discover_from_path(manifest_from_path)?
  1393. .ok_or_else(|| anyhow!("Cargo.toml not found"))?;
  1394. anchor_syn::idl::file::parse(
  1395. &*file,
  1396. cargo.version(),
  1397. cfg.features.seeds,
  1398. no_docs,
  1399. !skip_lint,
  1400. )
  1401. }
  1402. fn idl(cfg_override: &ConfigOverride, subcmd: IdlCommand) -> Result<()> {
  1403. match subcmd {
  1404. IdlCommand::Init {
  1405. program_id,
  1406. filepath,
  1407. } => idl_init(cfg_override, program_id, filepath),
  1408. IdlCommand::WriteBuffer {
  1409. program_id,
  1410. filepath,
  1411. } => idl_write_buffer(cfg_override, program_id, filepath).map(|_| ()),
  1412. IdlCommand::SetBuffer { program_id, buffer } => {
  1413. idl_set_buffer(cfg_override, program_id, buffer)
  1414. }
  1415. IdlCommand::Upgrade {
  1416. program_id,
  1417. filepath,
  1418. } => idl_upgrade(cfg_override, program_id, filepath),
  1419. IdlCommand::SetAuthority {
  1420. program_id,
  1421. address,
  1422. new_authority,
  1423. } => idl_set_authority(cfg_override, program_id, address, new_authority),
  1424. IdlCommand::EraseAuthority { program_id } => idl_erase_authority(cfg_override, program_id),
  1425. IdlCommand::Authority { program_id } => idl_authority(cfg_override, program_id),
  1426. IdlCommand::Parse {
  1427. file,
  1428. out,
  1429. out_ts,
  1430. no_docs,
  1431. } => idl_parse(cfg_override, file, out, out_ts, no_docs),
  1432. IdlCommand::Fetch { address, out } => idl_fetch(cfg_override, address, out),
  1433. }
  1434. }
  1435. fn idl_init(cfg_override: &ConfigOverride, program_id: Pubkey, idl_filepath: String) -> Result<()> {
  1436. with_workspace(cfg_override, |cfg| {
  1437. let keypair = cfg.provider.wallet.to_string();
  1438. let bytes = fs::read(idl_filepath)?;
  1439. let idl: Idl = serde_json::from_reader(&*bytes)?;
  1440. let idl_address = create_idl_account(cfg, &keypair, &program_id, &idl)?;
  1441. println!("Idl account created: {:?}", idl_address);
  1442. Ok(())
  1443. })
  1444. }
  1445. fn idl_write_buffer(
  1446. cfg_override: &ConfigOverride,
  1447. program_id: Pubkey,
  1448. idl_filepath: String,
  1449. ) -> Result<Pubkey> {
  1450. with_workspace(cfg_override, |cfg| {
  1451. let keypair = cfg.provider.wallet.to_string();
  1452. let bytes = fs::read(idl_filepath)?;
  1453. let idl: Idl = serde_json::from_reader(&*bytes)?;
  1454. let idl_buffer = create_idl_buffer(cfg, &keypair, &program_id, &idl)?;
  1455. idl_write(cfg, &program_id, &idl, idl_buffer)?;
  1456. println!("Idl buffer created: {:?}", idl_buffer);
  1457. Ok(idl_buffer)
  1458. })
  1459. }
  1460. fn idl_set_buffer(cfg_override: &ConfigOverride, program_id: Pubkey, buffer: Pubkey) -> Result<()> {
  1461. with_workspace(cfg_override, |cfg| {
  1462. let keypair = solana_sdk::signature::read_keypair_file(&cfg.provider.wallet.to_string())
  1463. .map_err(|_| anyhow!("Unable to read keypair file"))?;
  1464. let url = cluster_url(cfg, &cfg.test_validator);
  1465. let client = RpcClient::new(url);
  1466. // Instruction to set the buffer onto the IdlAccount.
  1467. let set_buffer_ix = {
  1468. let accounts = vec![
  1469. AccountMeta::new(buffer, false),
  1470. AccountMeta::new(IdlAccount::address(&program_id), false),
  1471. AccountMeta::new(keypair.pubkey(), true),
  1472. ];
  1473. let mut data = anchor_lang::idl::IDL_IX_TAG.to_le_bytes().to_vec();
  1474. data.append(&mut IdlInstruction::SetBuffer.try_to_vec()?);
  1475. Instruction {
  1476. program_id,
  1477. accounts,
  1478. data,
  1479. }
  1480. };
  1481. // Build the transaction.
  1482. let latest_hash = client.get_latest_blockhash()?;
  1483. let tx = Transaction::new_signed_with_payer(
  1484. &[set_buffer_ix],
  1485. Some(&keypair.pubkey()),
  1486. &[&keypair],
  1487. latest_hash,
  1488. );
  1489. // Send the transaction.
  1490. client.send_and_confirm_transaction_with_spinner_and_config(
  1491. &tx,
  1492. CommitmentConfig::confirmed(),
  1493. RpcSendTransactionConfig {
  1494. skip_preflight: true,
  1495. ..RpcSendTransactionConfig::default()
  1496. },
  1497. )?;
  1498. Ok(())
  1499. })
  1500. }
  1501. fn idl_upgrade(
  1502. cfg_override: &ConfigOverride,
  1503. program_id: Pubkey,
  1504. idl_filepath: String,
  1505. ) -> Result<()> {
  1506. let buffer = idl_write_buffer(cfg_override, program_id, idl_filepath)?;
  1507. idl_set_buffer(cfg_override, program_id, buffer)
  1508. }
  1509. fn idl_authority(cfg_override: &ConfigOverride, program_id: Pubkey) -> Result<()> {
  1510. with_workspace(cfg_override, |cfg| {
  1511. let url = cluster_url(cfg, &cfg.test_validator);
  1512. let client = RpcClient::new(url);
  1513. let idl_address = {
  1514. let account = client
  1515. .get_account_with_commitment(&program_id, CommitmentConfig::processed())?
  1516. .value
  1517. .map_or(Err(anyhow!("Account not found")), Ok)?;
  1518. if account.executable {
  1519. IdlAccount::address(&program_id)
  1520. } else {
  1521. program_id
  1522. }
  1523. };
  1524. let account = client.get_account(&idl_address)?;
  1525. let mut data: &[u8] = &account.data;
  1526. let idl_account: IdlAccount = AccountDeserialize::try_deserialize(&mut data)?;
  1527. println!("{:?}", idl_account.authority);
  1528. Ok(())
  1529. })
  1530. }
  1531. fn idl_set_authority(
  1532. cfg_override: &ConfigOverride,
  1533. program_id: Pubkey,
  1534. address: Option<Pubkey>,
  1535. new_authority: Pubkey,
  1536. ) -> Result<()> {
  1537. with_workspace(cfg_override, |cfg| {
  1538. // Misc.
  1539. let idl_address = match address {
  1540. None => IdlAccount::address(&program_id),
  1541. Some(addr) => addr,
  1542. };
  1543. let keypair = solana_sdk::signature::read_keypair_file(&cfg.provider.wallet.to_string())
  1544. .map_err(|_| anyhow!("Unable to read keypair file"))?;
  1545. let url = cluster_url(cfg, &cfg.test_validator);
  1546. let client = RpcClient::new(url);
  1547. // Instruction data.
  1548. let data =
  1549. serialize_idl_ix(anchor_lang::idl::IdlInstruction::SetAuthority { new_authority })?;
  1550. // Instruction accounts.
  1551. let accounts = vec![
  1552. AccountMeta::new(idl_address, false),
  1553. AccountMeta::new_readonly(keypair.pubkey(), true),
  1554. ];
  1555. // Instruction.
  1556. let ix = Instruction {
  1557. program_id,
  1558. accounts,
  1559. data,
  1560. };
  1561. // Send transaction.
  1562. let latest_hash = client.get_latest_blockhash()?;
  1563. let tx = Transaction::new_signed_with_payer(
  1564. &[ix],
  1565. Some(&keypair.pubkey()),
  1566. &[&keypair],
  1567. latest_hash,
  1568. );
  1569. client.send_and_confirm_transaction_with_spinner_and_config(
  1570. &tx,
  1571. CommitmentConfig::confirmed(),
  1572. RpcSendTransactionConfig {
  1573. skip_preflight: true,
  1574. ..RpcSendTransactionConfig::default()
  1575. },
  1576. )?;
  1577. println!("Authority update complete.");
  1578. Ok(())
  1579. })
  1580. }
  1581. fn idl_erase_authority(cfg_override: &ConfigOverride, program_id: Pubkey) -> Result<()> {
  1582. println!("Are you sure you want to erase the IDL authority: [y/n]");
  1583. let stdin = std::io::stdin();
  1584. let mut stdin_lines = stdin.lock().lines();
  1585. let input = stdin_lines.next().unwrap().unwrap();
  1586. if input != "y" {
  1587. println!("Not erasing.");
  1588. return Ok(());
  1589. }
  1590. idl_set_authority(cfg_override, program_id, None, ERASED_AUTHORITY)?;
  1591. Ok(())
  1592. }
  1593. // Write the idl to the account buffer, chopping up the IDL into pieces
  1594. // and sending multiple transactions in the event the IDL doesn't fit into
  1595. // a single transaction.
  1596. fn idl_write(cfg: &Config, program_id: &Pubkey, idl: &Idl, idl_address: Pubkey) -> Result<()> {
  1597. // Remove the metadata before deploy.
  1598. let mut idl = idl.clone();
  1599. idl.metadata = None;
  1600. // Misc.
  1601. let keypair = solana_sdk::signature::read_keypair_file(&cfg.provider.wallet.to_string())
  1602. .map_err(|_| anyhow!("Unable to read keypair file"))?;
  1603. let url = cluster_url(cfg, &cfg.test_validator);
  1604. let client = RpcClient::new(url);
  1605. // Serialize and compress the idl.
  1606. let idl_data = {
  1607. let json_bytes = serde_json::to_vec(&idl)?;
  1608. let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
  1609. e.write_all(&json_bytes)?;
  1610. e.finish()?
  1611. };
  1612. const MAX_WRITE_SIZE: usize = 1000;
  1613. let mut offset = 0;
  1614. while offset < idl_data.len() {
  1615. // Instruction data.
  1616. let data = {
  1617. let start = offset;
  1618. let end = std::cmp::min(offset + MAX_WRITE_SIZE, idl_data.len());
  1619. serialize_idl_ix(anchor_lang::idl::IdlInstruction::Write {
  1620. data: idl_data[start..end].to_vec(),
  1621. })?
  1622. };
  1623. // Instruction accounts.
  1624. let accounts = vec![
  1625. AccountMeta::new(idl_address, false),
  1626. AccountMeta::new_readonly(keypair.pubkey(), true),
  1627. ];
  1628. // Instruction.
  1629. let ix = Instruction {
  1630. program_id: *program_id,
  1631. accounts,
  1632. data,
  1633. };
  1634. // Send transaction.
  1635. let latest_hash = client.get_latest_blockhash()?;
  1636. let tx = Transaction::new_signed_with_payer(
  1637. &[ix],
  1638. Some(&keypair.pubkey()),
  1639. &[&keypair],
  1640. latest_hash,
  1641. );
  1642. client.send_and_confirm_transaction_with_spinner_and_config(
  1643. &tx,
  1644. CommitmentConfig::confirmed(),
  1645. RpcSendTransactionConfig {
  1646. skip_preflight: true,
  1647. ..RpcSendTransactionConfig::default()
  1648. },
  1649. )?;
  1650. offset += MAX_WRITE_SIZE;
  1651. }
  1652. Ok(())
  1653. }
  1654. fn idl_parse(
  1655. cfg_override: &ConfigOverride,
  1656. file: String,
  1657. out: Option<String>,
  1658. out_ts: Option<String>,
  1659. no_docs: bool,
  1660. ) -> Result<()> {
  1661. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  1662. let idl = extract_idl(&cfg, &file, true, no_docs)?.ok_or_else(|| anyhow!("IDL not parsed"))?;
  1663. let out = match out {
  1664. None => OutFile::Stdout,
  1665. Some(out) => OutFile::File(PathBuf::from(out)),
  1666. };
  1667. write_idl(&idl, out)?;
  1668. // Write out the TypeScript IDL.
  1669. if let Some(out) = out_ts {
  1670. fs::write(out, template::idl_ts(&idl)?)?;
  1671. }
  1672. Ok(())
  1673. }
  1674. fn idl_fetch(cfg_override: &ConfigOverride, address: Pubkey, out: Option<String>) -> Result<()> {
  1675. let idl = fetch_idl(cfg_override, address)?;
  1676. let out = match out {
  1677. None => OutFile::Stdout,
  1678. Some(out) => OutFile::File(PathBuf::from(out)),
  1679. };
  1680. write_idl(&idl, out)
  1681. }
  1682. fn write_idl(idl: &Idl, out: OutFile) -> Result<()> {
  1683. let idl_json = serde_json::to_string_pretty(idl)?;
  1684. match out {
  1685. OutFile::Stdout => println!("{}", idl_json),
  1686. OutFile::File(out) => fs::write(out, idl_json)?,
  1687. };
  1688. Ok(())
  1689. }
  1690. enum OutFile {
  1691. Stdout,
  1692. File(PathBuf),
  1693. }
  1694. // Builds, deploys, and tests all workspace programs in a single command.
  1695. #[allow(clippy::too_many_arguments)]
  1696. fn test(
  1697. cfg_override: &ConfigOverride,
  1698. skip_deploy: bool,
  1699. skip_local_validator: bool,
  1700. skip_build: bool,
  1701. skip_lint: bool,
  1702. detach: bool,
  1703. extra_args: Vec<String>,
  1704. cargo_args: Vec<String>,
  1705. ) -> Result<()> {
  1706. with_workspace(cfg_override, |cfg| {
  1707. // Build if needed.
  1708. if !skip_build {
  1709. build(
  1710. cfg_override,
  1711. None,
  1712. None,
  1713. false,
  1714. skip_lint,
  1715. None,
  1716. None,
  1717. None,
  1718. BootstrapMode::None,
  1719. None,
  1720. None,
  1721. cargo_args,
  1722. false,
  1723. )?;
  1724. }
  1725. let root = cfg.path().parent().unwrap().to_owned();
  1726. cfg.add_test_config(root)?;
  1727. // Run the deploy against the cluster in two cases:
  1728. //
  1729. // 1. The cluster is not localnet.
  1730. // 2. The cluster is localnet, but we're not booting a local validator.
  1731. //
  1732. // In either case, skip the deploy if the user specifies.
  1733. let is_localnet = cfg.provider.cluster == Cluster::Localnet;
  1734. if (!is_localnet || skip_local_validator) && !skip_deploy {
  1735. deploy(cfg_override, None, None)?;
  1736. }
  1737. let mut is_first_suite = true;
  1738. if cfg.scripts.get("test").is_some() {
  1739. is_first_suite = false;
  1740. println!("\nFound a 'test' script in the Anchor.toml. Running it as a test suite!");
  1741. run_test_suite(
  1742. cfg.path(),
  1743. cfg,
  1744. is_localnet,
  1745. skip_local_validator,
  1746. skip_deploy,
  1747. detach,
  1748. &cfg.test_validator,
  1749. &cfg.scripts,
  1750. &extra_args,
  1751. )?;
  1752. }
  1753. if let Some(test_config) = &cfg.test_config {
  1754. for test_suite in test_config.iter() {
  1755. if !is_first_suite {
  1756. std::thread::sleep(std::time::Duration::from_millis(
  1757. test_suite
  1758. .1
  1759. .test
  1760. .as_ref()
  1761. .map(|val| val.shutdown_wait)
  1762. .unwrap_or(SHUTDOWN_WAIT) as u64,
  1763. ));
  1764. } else {
  1765. is_first_suite = false;
  1766. }
  1767. run_test_suite(
  1768. test_suite.0,
  1769. cfg,
  1770. is_localnet,
  1771. skip_local_validator,
  1772. skip_deploy,
  1773. detach,
  1774. &test_suite.1.test,
  1775. &test_suite.1.scripts,
  1776. &extra_args,
  1777. )?;
  1778. }
  1779. }
  1780. Ok(())
  1781. })
  1782. }
  1783. #[allow(clippy::too_many_arguments)]
  1784. fn run_test_suite(
  1785. test_suite_path: impl AsRef<Path>,
  1786. cfg: &WithPath<Config>,
  1787. is_localnet: bool,
  1788. skip_local_validator: bool,
  1789. skip_deploy: bool,
  1790. detach: bool,
  1791. test_validator: &Option<TestValidator>,
  1792. scripts: &ScriptsConfig,
  1793. extra_args: &[String],
  1794. ) -> Result<()> {
  1795. println!("\nRunning test suite: {:#?}\n", test_suite_path.as_ref());
  1796. // Start local test validator, if needed.
  1797. let mut validator_handle = None;
  1798. if is_localnet && (!skip_local_validator) {
  1799. let flags = match skip_deploy {
  1800. true => None,
  1801. false => Some(validator_flags(cfg, test_validator)?),
  1802. };
  1803. validator_handle = Some(start_test_validator(cfg, test_validator, flags, true)?);
  1804. }
  1805. let url = cluster_url(cfg, test_validator);
  1806. let node_options = format!(
  1807. "{} {}",
  1808. match std::env::var_os("NODE_OPTIONS") {
  1809. Some(value) => value
  1810. .into_string()
  1811. .map_err(std::env::VarError::NotUnicode)?,
  1812. None => "".to_owned(),
  1813. },
  1814. get_node_dns_option()?,
  1815. );
  1816. // Setup log reader.
  1817. let log_streams = stream_logs(cfg, &url);
  1818. // Run the tests.
  1819. let test_result: Result<_> = {
  1820. let cmd = scripts
  1821. .get("test")
  1822. .expect("Not able to find script for `test`")
  1823. .clone();
  1824. let mut args: Vec<&str> = cmd
  1825. .split(' ')
  1826. .chain(extra_args.iter().map(|arg| arg.as_str()))
  1827. .collect();
  1828. let program = args.remove(0);
  1829. std::process::Command::new(program)
  1830. .args(args)
  1831. .env("ANCHOR_PROVIDER_URL", url)
  1832. .env("ANCHOR_WALLET", cfg.provider.wallet.to_string())
  1833. .env("NODE_OPTIONS", node_options)
  1834. .stdout(Stdio::inherit())
  1835. .stderr(Stdio::inherit())
  1836. .output()
  1837. .map_err(anyhow::Error::from)
  1838. .context(cmd)
  1839. };
  1840. // Keep validator running if needed.
  1841. if test_result.is_ok() && detach {
  1842. println!("Local validator still running. Press Ctrl + C quit.");
  1843. std::io::stdin().lock().lines().next().unwrap().unwrap();
  1844. }
  1845. // Check all errors and shut down.
  1846. if let Some(mut child) = validator_handle {
  1847. if let Err(err) = child.kill() {
  1848. println!("Failed to kill subprocess {}: {}", child.id(), err);
  1849. }
  1850. }
  1851. for mut child in log_streams? {
  1852. if let Err(err) = child.kill() {
  1853. println!("Failed to kill subprocess {}: {}", child.id(), err);
  1854. }
  1855. }
  1856. // Must exist *after* shutting down the validator and log streams.
  1857. match test_result {
  1858. Ok(exit) => {
  1859. if !exit.status.success() {
  1860. std::process::exit(exit.status.code().unwrap());
  1861. }
  1862. }
  1863. Err(err) => {
  1864. println!("Failed to run test: {:#}", err)
  1865. }
  1866. }
  1867. Ok(())
  1868. }
  1869. // Returns the solana-test-validator flags. This will embed the workspace
  1870. // programs in the genesis block so we don't have to deploy every time. It also
  1871. // allows control of other solana-test-validator features.
  1872. fn validator_flags(
  1873. cfg: &WithPath<Config>,
  1874. test_validator: &Option<TestValidator>,
  1875. ) -> Result<Vec<String>> {
  1876. let programs = cfg.programs.get(&Cluster::Localnet);
  1877. let mut flags = Vec::new();
  1878. for mut program in cfg.read_all_programs()? {
  1879. let binary_path = program.binary_path().display().to_string();
  1880. // Use the [programs.cluster] override and fallback to the keypair
  1881. // files if no override is given.
  1882. let address = programs
  1883. .and_then(|m| m.get(&program.lib_name))
  1884. .map(|deployment| Ok(deployment.address.to_string()))
  1885. .unwrap_or_else(|| program.pubkey().map(|p| p.to_string()))?;
  1886. flags.push("--bpf-program".to_string());
  1887. flags.push(address.clone());
  1888. flags.push(binary_path);
  1889. if let Some(mut idl) = program.idl.as_mut() {
  1890. // Add program address to the IDL.
  1891. idl.metadata = Some(serde_json::to_value(IdlTestMetadata { address })?);
  1892. // Persist it.
  1893. let idl_out = PathBuf::from("target/idl")
  1894. .join(&idl.name)
  1895. .with_extension("json");
  1896. write_idl(idl, OutFile::File(idl_out))?;
  1897. }
  1898. }
  1899. if let Some(test) = test_validator.as_ref() {
  1900. if let Some(genesis) = &test.genesis {
  1901. for entry in genesis {
  1902. let program_path = Path::new(&entry.program);
  1903. if !program_path.exists() {
  1904. return Err(anyhow!(
  1905. "Program in genesis configuration does not exist at path: {}",
  1906. program_path.display()
  1907. ));
  1908. }
  1909. flags.push("--bpf-program".to_string());
  1910. flags.push(entry.address.clone());
  1911. flags.push(entry.program.clone());
  1912. }
  1913. }
  1914. if let Some(validator) = &test.validator {
  1915. let entries = serde_json::to_value(validator)?;
  1916. for (key, value) in entries.as_object().unwrap() {
  1917. if key == "ledger" {
  1918. // Ledger flag is a special case as it is passed separately to the rest of
  1919. // these validator flags.
  1920. continue;
  1921. };
  1922. if key == "account" {
  1923. for entry in value.as_array().unwrap() {
  1924. // Push the account flag for each array entry
  1925. flags.push("--account".to_string());
  1926. flags.push(entry["address"].as_str().unwrap().to_string());
  1927. flags.push(entry["filename"].as_str().unwrap().to_string());
  1928. }
  1929. } else if key == "clone" {
  1930. // Client for fetching accounts data
  1931. let client = if let Some(url) = entries["url"].as_str() {
  1932. RpcClient::new(url.to_string())
  1933. } else {
  1934. return Err(anyhow!(
  1935. "Validator url for Solana's JSON RPC should be provided in order to clone accounts from it"
  1936. ));
  1937. };
  1938. let mut pubkeys = value
  1939. .as_array()
  1940. .unwrap()
  1941. .iter()
  1942. .map(|entry| {
  1943. let address = entry["address"].as_str().unwrap();
  1944. Pubkey::from_str(address)
  1945. .map_err(|_| anyhow!("Invalid pubkey {}", address))
  1946. })
  1947. .collect::<Result<HashSet<Pubkey>>>()?;
  1948. let accounts_keys = pubkeys.iter().cloned().collect::<Vec<_>>();
  1949. let accounts = client
  1950. .get_multiple_accounts_with_commitment(
  1951. &accounts_keys,
  1952. CommitmentConfig::default(),
  1953. )?
  1954. .value;
  1955. // Check if there are program accounts
  1956. for (account, acc_key) in accounts.iter().zip(accounts_keys) {
  1957. if let Some(account) = account {
  1958. if account.owner == bpf_loader_upgradeable::id() {
  1959. let upgradable: UpgradeableLoaderState = account
  1960. .deserialize_data()
  1961. .map_err(|_| anyhow!("Invalid program account {}", acc_key))?;
  1962. if let UpgradeableLoaderState::Program {
  1963. programdata_address,
  1964. } = upgradable
  1965. {
  1966. pubkeys.insert(programdata_address);
  1967. }
  1968. }
  1969. } else {
  1970. return Err(anyhow!("Account {} not found", acc_key));
  1971. }
  1972. }
  1973. for pubkey in &pubkeys {
  1974. // Push the clone flag for each array entry
  1975. flags.push("--clone".to_string());
  1976. flags.push(pubkey.to_string());
  1977. }
  1978. } else {
  1979. // Remaining validator flags are non-array types
  1980. flags.push(format!("--{}", key.replace('_', "-")));
  1981. if let serde_json::Value::String(v) = value {
  1982. flags.push(v.to_string());
  1983. } else {
  1984. flags.push(value.to_string());
  1985. }
  1986. }
  1987. }
  1988. }
  1989. }
  1990. Ok(flags)
  1991. }
  1992. fn stream_logs(config: &WithPath<Config>, rpc_url: &str) -> Result<Vec<std::process::Child>> {
  1993. let program_logs_dir = ".anchor/program-logs";
  1994. if Path::new(program_logs_dir).exists() {
  1995. fs::remove_dir_all(program_logs_dir)?;
  1996. }
  1997. fs::create_dir_all(program_logs_dir)?;
  1998. let mut handles = vec![];
  1999. for program in config.read_all_programs()? {
  2000. let mut file = File::open(&format!("target/idl/{}.json", program.lib_name))?;
  2001. let mut contents = vec![];
  2002. file.read_to_end(&mut contents)?;
  2003. let idl: Idl = serde_json::from_slice(&contents)?;
  2004. let metadata = idl.metadata.ok_or_else(|| {
  2005. anyhow!(
  2006. "Metadata property not found in IDL of program: {}",
  2007. program.lib_name
  2008. )
  2009. })?;
  2010. let metadata: IdlTestMetadata = serde_json::from_value(metadata)?;
  2011. let log_file = File::create(format!(
  2012. "{}/{}.{}.log",
  2013. program_logs_dir, metadata.address, program.lib_name,
  2014. ))?;
  2015. let stdio = std::process::Stdio::from(log_file);
  2016. let child = std::process::Command::new("solana")
  2017. .arg("logs")
  2018. .arg(metadata.address)
  2019. .arg("--url")
  2020. .arg(rpc_url)
  2021. .stdout(stdio)
  2022. .spawn()?;
  2023. handles.push(child);
  2024. }
  2025. if let Some(test) = config.test_validator.as_ref() {
  2026. if let Some(genesis) = &test.genesis {
  2027. for entry in genesis {
  2028. let log_file = File::create(format!("{}/{}.log", program_logs_dir, entry.address))?;
  2029. let stdio = std::process::Stdio::from(log_file);
  2030. let child = std::process::Command::new("solana")
  2031. .arg("logs")
  2032. .arg(entry.address.clone())
  2033. .arg("--url")
  2034. .arg(rpc_url)
  2035. .stdout(stdio)
  2036. .spawn()?;
  2037. handles.push(child);
  2038. }
  2039. }
  2040. }
  2041. Ok(handles)
  2042. }
  2043. #[derive(Debug, Serialize, Deserialize)]
  2044. pub struct IdlTestMetadata {
  2045. address: String,
  2046. }
  2047. fn start_test_validator(
  2048. cfg: &Config,
  2049. test_validator: &Option<TestValidator>,
  2050. flags: Option<Vec<String>>,
  2051. test_log_stdout: bool,
  2052. ) -> Result<Child> {
  2053. //
  2054. let (test_ledger_directory, test_ledger_log_filename) =
  2055. test_validator_file_paths(test_validator);
  2056. // Start a validator for testing.
  2057. let (test_validator_stdout, test_validator_stderr) = match test_log_stdout {
  2058. true => {
  2059. let test_validator_stdout_file = File::create(&test_ledger_log_filename)?;
  2060. let test_validator_sterr_file = test_validator_stdout_file.try_clone()?;
  2061. (
  2062. Stdio::from(test_validator_stdout_file),
  2063. Stdio::from(test_validator_sterr_file),
  2064. )
  2065. }
  2066. false => (Stdio::inherit(), Stdio::inherit()),
  2067. };
  2068. let rpc_url = test_validator_rpc_url(test_validator);
  2069. let rpc_port = cfg
  2070. .test_validator
  2071. .as_ref()
  2072. .and_then(|test| test.validator.as_ref().map(|v| v.rpc_port))
  2073. .unwrap_or(solana_sdk::rpc_port::DEFAULT_RPC_PORT);
  2074. if !portpicker::is_free(rpc_port) {
  2075. return Err(anyhow!(
  2076. "Your configured rpc port: {rpc_port} is already in use"
  2077. ));
  2078. }
  2079. let faucet_port = cfg
  2080. .test_validator
  2081. .as_ref()
  2082. .and_then(|test| test.validator.as_ref().and_then(|v| v.faucet_port))
  2083. .unwrap_or(solana_faucet::faucet::FAUCET_PORT);
  2084. if !portpicker::is_free(faucet_port) {
  2085. return Err(anyhow!(
  2086. "Your configured faucet port: {faucet_port} is already in use"
  2087. ));
  2088. }
  2089. let mut validator_handle = std::process::Command::new("solana-test-validator")
  2090. .arg("--ledger")
  2091. .arg(test_ledger_directory)
  2092. .arg("--mint")
  2093. .arg(cfg.wallet_kp()?.pubkey().to_string())
  2094. .args(flags.unwrap_or_default())
  2095. .stdout(test_validator_stdout)
  2096. .stderr(test_validator_stderr)
  2097. .spawn()
  2098. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  2099. // Wait for the validator to be ready.
  2100. let client = RpcClient::new(rpc_url);
  2101. let mut count = 0;
  2102. let ms_wait = test_validator
  2103. .as_ref()
  2104. .map(|test| test.startup_wait)
  2105. .unwrap_or(STARTUP_WAIT);
  2106. while count < ms_wait {
  2107. let r = client.get_latest_blockhash();
  2108. if r.is_ok() {
  2109. break;
  2110. }
  2111. std::thread::sleep(std::time::Duration::from_millis(1));
  2112. count += 1;
  2113. }
  2114. if count == ms_wait {
  2115. eprintln!(
  2116. "Unable to get latest blockhash. Test validator does not look started. Check {} for errors. Consider increasing [test.startup_wait] in Anchor.toml.",
  2117. test_ledger_log_filename
  2118. );
  2119. validator_handle.kill()?;
  2120. std::process::exit(1);
  2121. }
  2122. Ok(validator_handle)
  2123. }
  2124. // Return the URL that solana-test-validator should be running on given the
  2125. // configuration
  2126. fn test_validator_rpc_url(test_validator: &Option<TestValidator>) -> String {
  2127. match test_validator {
  2128. Some(TestValidator {
  2129. validator: Some(validator),
  2130. ..
  2131. }) => format!("http://{}:{}", validator.bind_address, validator.rpc_port),
  2132. _ => "http://localhost:8899".to_string(),
  2133. }
  2134. }
  2135. // Setup and return paths to the solana-test-validator ledger directory and log
  2136. // files given the configuration
  2137. fn test_validator_file_paths(test_validator: &Option<TestValidator>) -> (String, String) {
  2138. let ledger_directory = match test_validator {
  2139. Some(TestValidator {
  2140. validator: Some(validator),
  2141. ..
  2142. }) => &validator.ledger,
  2143. _ => ".anchor/test-ledger",
  2144. };
  2145. if !Path::new(&ledger_directory).is_relative() {
  2146. // Prevent absolute paths to avoid someone using / or similar, as the
  2147. // directory gets removed
  2148. eprintln!("Ledger directory {} must be relative", ledger_directory);
  2149. std::process::exit(1);
  2150. }
  2151. if Path::new(&ledger_directory).exists() {
  2152. fs::remove_dir_all(&ledger_directory).unwrap();
  2153. }
  2154. fs::create_dir_all(&ledger_directory).unwrap();
  2155. (
  2156. ledger_directory.to_string(),
  2157. format!("{}/test-ledger-log.txt", ledger_directory),
  2158. )
  2159. }
  2160. fn cluster_url(cfg: &Config, test_validator: &Option<TestValidator>) -> String {
  2161. let is_localnet = cfg.provider.cluster == Cluster::Localnet;
  2162. match is_localnet {
  2163. // Cluster is Localnet, assume the intent is to use the configuration
  2164. // for solana-test-validator
  2165. true => test_validator_rpc_url(test_validator),
  2166. false => cfg.provider.cluster.url().to_string(),
  2167. }
  2168. }
  2169. fn clean(cfg_override: &ConfigOverride) -> Result<()> {
  2170. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  2171. let cfg_parent = cfg.path().parent().expect("Invalid Anchor.toml");
  2172. let target_dir = cfg_parent.join("target");
  2173. let deploy_dir = target_dir.join("deploy");
  2174. for entry in fs::read_dir(target_dir)? {
  2175. let path = entry?.path();
  2176. if path.is_dir() && path != deploy_dir {
  2177. fs::remove_dir_all(&path)
  2178. .map_err(|e| anyhow!("Could not remove directory {}: {}", path.display(), e))?;
  2179. } else if path.is_file() {
  2180. fs::remove_file(&path)
  2181. .map_err(|e| anyhow!("Could not remove file {}: {}", path.display(), e))?;
  2182. }
  2183. }
  2184. for file in fs::read_dir(deploy_dir)? {
  2185. let path = file?.path();
  2186. if path.extension() != Some(&OsString::from("json")) {
  2187. fs::remove_file(&path)
  2188. .map_err(|e| anyhow!("Could not remove file {}: {}", path.display(), e))?;
  2189. }
  2190. }
  2191. Ok(())
  2192. }
  2193. fn deploy(
  2194. cfg_override: &ConfigOverride,
  2195. program_str: Option<String>,
  2196. program_keypair: Option<String>,
  2197. ) -> Result<()> {
  2198. with_workspace(cfg_override, |cfg| {
  2199. let url = cluster_url(cfg, &cfg.test_validator);
  2200. let keypair = cfg.provider.wallet.to_string();
  2201. // Deploy the programs.
  2202. println!("Deploying workspace: {}", url);
  2203. println!("Upgrade authority: {}", keypair);
  2204. for mut program in cfg.read_all_programs()? {
  2205. if let Some(single_prog_str) = &program_str {
  2206. let program_name = program.path.file_name().unwrap().to_str().unwrap();
  2207. if single_prog_str.as_str() != program_name {
  2208. continue;
  2209. }
  2210. }
  2211. let binary_path = program.binary_path().display().to_string();
  2212. println!(
  2213. "Deploying program {:?}...",
  2214. program.path.file_name().unwrap().to_str().unwrap()
  2215. );
  2216. println!("Program path: {}...", binary_path);
  2217. let program_keypair_filepath = match &program_keypair {
  2218. Some(program_keypair) => program_keypair.clone(),
  2219. None => program.keypair_file()?.path().display().to_string(),
  2220. };
  2221. // Send deploy transactions.
  2222. let exit = std::process::Command::new("solana")
  2223. .arg("program")
  2224. .arg("deploy")
  2225. .arg("--url")
  2226. .arg(&url)
  2227. .arg("--keypair")
  2228. .arg(&keypair)
  2229. .arg("--program-id")
  2230. .arg(program_keypair_filepath)
  2231. .arg(&binary_path)
  2232. .stdout(Stdio::inherit())
  2233. .stderr(Stdio::inherit())
  2234. .output()
  2235. .expect("Must deploy");
  2236. if !exit.status.success() {
  2237. println!("There was a problem deploying: {:?}.", exit);
  2238. std::process::exit(exit.status.code().unwrap_or(1));
  2239. }
  2240. let program_pubkey = program.pubkey()?;
  2241. if let Some(mut idl) = program.idl.as_mut() {
  2242. // Add program address to the IDL.
  2243. idl.metadata = Some(serde_json::to_value(IdlTestMetadata {
  2244. address: program_pubkey.to_string(),
  2245. })?);
  2246. // Persist it.
  2247. let idl_out = PathBuf::from("target/idl")
  2248. .join(&idl.name)
  2249. .with_extension("json");
  2250. write_idl(idl, OutFile::File(idl_out))?;
  2251. }
  2252. }
  2253. println!("Deploy success");
  2254. Ok(())
  2255. })
  2256. }
  2257. fn upgrade(
  2258. cfg_override: &ConfigOverride,
  2259. program_id: Pubkey,
  2260. program_filepath: String,
  2261. ) -> Result<()> {
  2262. let path: PathBuf = program_filepath.parse().unwrap();
  2263. let program_filepath = path.canonicalize()?.display().to_string();
  2264. with_workspace(cfg_override, |cfg| {
  2265. let url = cluster_url(cfg, &cfg.test_validator);
  2266. let exit = std::process::Command::new("solana")
  2267. .arg("program")
  2268. .arg("deploy")
  2269. .arg("--url")
  2270. .arg(url)
  2271. .arg("--keypair")
  2272. .arg(&cfg.provider.wallet.to_string())
  2273. .arg("--program-id")
  2274. .arg(program_id.to_string())
  2275. .arg(&program_filepath)
  2276. .stdout(Stdio::inherit())
  2277. .stderr(Stdio::inherit())
  2278. .output()
  2279. .expect("Must deploy");
  2280. if !exit.status.success() {
  2281. println!("There was a problem deploying: {:?}.", exit);
  2282. std::process::exit(exit.status.code().unwrap_or(1));
  2283. }
  2284. Ok(())
  2285. })
  2286. }
  2287. fn create_idl_account(
  2288. cfg: &Config,
  2289. keypair_path: &str,
  2290. program_id: &Pubkey,
  2291. idl: &Idl,
  2292. ) -> Result<Pubkey> {
  2293. // Misc.
  2294. let idl_address = IdlAccount::address(program_id);
  2295. let keypair = solana_sdk::signature::read_keypair_file(keypair_path)
  2296. .map_err(|_| anyhow!("Unable to read keypair file"))?;
  2297. let url = cluster_url(cfg, &cfg.test_validator);
  2298. let client = RpcClient::new(url);
  2299. let idl_data = serialize_idl(idl)?;
  2300. // Run `Create instruction.
  2301. {
  2302. let data = serialize_idl_ix(anchor_lang::idl::IdlInstruction::Create {
  2303. data_len: (idl_data.len() as u64) * 2, // Double for future growth.
  2304. })?;
  2305. let program_signer = Pubkey::find_program_address(&[], program_id).0;
  2306. let accounts = vec![
  2307. AccountMeta::new_readonly(keypair.pubkey(), true),
  2308. AccountMeta::new(idl_address, false),
  2309. AccountMeta::new_readonly(program_signer, false),
  2310. AccountMeta::new_readonly(solana_program::system_program::ID, false),
  2311. AccountMeta::new_readonly(*program_id, false),
  2312. AccountMeta::new_readonly(solana_program::sysvar::rent::ID, false),
  2313. ];
  2314. let ix = Instruction {
  2315. program_id: *program_id,
  2316. accounts,
  2317. data,
  2318. };
  2319. let latest_hash = client.get_latest_blockhash()?;
  2320. let tx = Transaction::new_signed_with_payer(
  2321. &[ix],
  2322. Some(&keypair.pubkey()),
  2323. &[&keypair],
  2324. latest_hash,
  2325. );
  2326. client.send_and_confirm_transaction_with_spinner_and_config(
  2327. &tx,
  2328. CommitmentConfig::finalized(),
  2329. RpcSendTransactionConfig {
  2330. skip_preflight: true,
  2331. ..RpcSendTransactionConfig::default()
  2332. },
  2333. )?;
  2334. }
  2335. // Write directly to the IDL account buffer.
  2336. idl_write(cfg, program_id, idl, IdlAccount::address(program_id))?;
  2337. Ok(idl_address)
  2338. }
  2339. fn create_idl_buffer(
  2340. cfg: &Config,
  2341. keypair_path: &str,
  2342. program_id: &Pubkey,
  2343. idl: &Idl,
  2344. ) -> Result<Pubkey> {
  2345. let keypair = solana_sdk::signature::read_keypair_file(keypair_path)
  2346. .map_err(|_| anyhow!("Unable to read keypair file"))?;
  2347. let url = cluster_url(cfg, &cfg.test_validator);
  2348. let client = RpcClient::new(url);
  2349. let buffer = Keypair::generate(&mut OsRng);
  2350. // Creates the new buffer account with the system program.
  2351. let create_account_ix = {
  2352. let space = 8 + 32 + 4 + serialize_idl(idl)?.len() as usize;
  2353. let lamports = client.get_minimum_balance_for_rent_exemption(space)?;
  2354. solana_sdk::system_instruction::create_account(
  2355. &keypair.pubkey(),
  2356. &buffer.pubkey(),
  2357. lamports,
  2358. space as u64,
  2359. program_id,
  2360. )
  2361. };
  2362. // Program instruction to create the buffer.
  2363. let create_buffer_ix = {
  2364. let accounts = vec![
  2365. AccountMeta::new(buffer.pubkey(), false),
  2366. AccountMeta::new_readonly(keypair.pubkey(), true),
  2367. AccountMeta::new_readonly(sysvar::rent::ID, false),
  2368. ];
  2369. let mut data = anchor_lang::idl::IDL_IX_TAG.to_le_bytes().to_vec();
  2370. data.append(&mut IdlInstruction::CreateBuffer.try_to_vec()?);
  2371. Instruction {
  2372. program_id: *program_id,
  2373. accounts,
  2374. data,
  2375. }
  2376. };
  2377. // Build the transaction.
  2378. let latest_hash = client.get_latest_blockhash()?;
  2379. let tx = Transaction::new_signed_with_payer(
  2380. &[create_account_ix, create_buffer_ix],
  2381. Some(&keypair.pubkey()),
  2382. &[&keypair, &buffer],
  2383. latest_hash,
  2384. );
  2385. // Send the transaction.
  2386. client.send_and_confirm_transaction_with_spinner_and_config(
  2387. &tx,
  2388. CommitmentConfig::confirmed(),
  2389. RpcSendTransactionConfig {
  2390. skip_preflight: true,
  2391. ..RpcSendTransactionConfig::default()
  2392. },
  2393. )?;
  2394. Ok(buffer.pubkey())
  2395. }
  2396. // Serialize and compress the idl.
  2397. fn serialize_idl(idl: &Idl) -> Result<Vec<u8>> {
  2398. let json_bytes = serde_json::to_vec(idl)?;
  2399. let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
  2400. e.write_all(&json_bytes)?;
  2401. e.finish().map_err(Into::into)
  2402. }
  2403. fn serialize_idl_ix(ix_inner: anchor_lang::idl::IdlInstruction) -> Result<Vec<u8>> {
  2404. let mut data = anchor_lang::idl::IDL_IX_TAG.to_le_bytes().to_vec();
  2405. data.append(&mut ix_inner.try_to_vec()?);
  2406. Ok(data)
  2407. }
  2408. fn migrate(cfg_override: &ConfigOverride) -> Result<()> {
  2409. with_workspace(cfg_override, |cfg| {
  2410. println!("Running migration deploy script");
  2411. let url = cluster_url(cfg, &cfg.test_validator);
  2412. let cur_dir = std::env::current_dir()?;
  2413. let use_ts =
  2414. Path::new("tsconfig.json").exists() && Path::new("migrations/deploy.ts").exists();
  2415. if !Path::new(".anchor").exists() {
  2416. fs::create_dir(".anchor")?;
  2417. }
  2418. std::env::set_current_dir(".anchor")?;
  2419. let exit = if use_ts {
  2420. let module_path = cur_dir.join("migrations/deploy.ts");
  2421. let deploy_script_host_str =
  2422. template::deploy_ts_script_host(&url, &module_path.display().to_string());
  2423. fs::write("deploy.ts", deploy_script_host_str)?;
  2424. std::process::Command::new("ts-node")
  2425. .arg("deploy.ts")
  2426. .env("ANCHOR_WALLET", cfg.provider.wallet.to_string())
  2427. .stdout(Stdio::inherit())
  2428. .stderr(Stdio::inherit())
  2429. .output()?
  2430. } else {
  2431. let module_path = cur_dir.join("migrations/deploy.js");
  2432. let deploy_script_host_str =
  2433. template::deploy_js_script_host(&url, &module_path.display().to_string());
  2434. fs::write("deploy.js", deploy_script_host_str)?;
  2435. std::process::Command::new("node")
  2436. .arg("deploy.js")
  2437. .env("ANCHOR_WALLET", cfg.provider.wallet.to_string())
  2438. .stdout(Stdio::inherit())
  2439. .stderr(Stdio::inherit())
  2440. .output()?
  2441. };
  2442. if !exit.status.success() {
  2443. println!("Deploy failed.");
  2444. std::process::exit(exit.status.code().unwrap());
  2445. }
  2446. println!("Deploy complete.");
  2447. Ok(())
  2448. })
  2449. }
  2450. fn set_workspace_dir_or_exit() {
  2451. let d = match Config::discover(&ConfigOverride::default()) {
  2452. Err(err) => {
  2453. println!("Workspace configuration error: {}", err);
  2454. std::process::exit(1);
  2455. }
  2456. Ok(d) => d,
  2457. };
  2458. match d {
  2459. None => {
  2460. println!("Not in anchor workspace.");
  2461. std::process::exit(1);
  2462. }
  2463. Some(cfg) => {
  2464. match cfg.path().parent() {
  2465. None => {
  2466. println!("Unable to make new program");
  2467. }
  2468. Some(parent) => {
  2469. if std::env::set_current_dir(&parent).is_err() {
  2470. println!("Not in anchor workspace.");
  2471. std::process::exit(1);
  2472. }
  2473. }
  2474. };
  2475. }
  2476. }
  2477. }
  2478. #[cfg(feature = "dev")]
  2479. fn airdrop(cfg_override: &ConfigOverride) -> Result<()> {
  2480. let url = cfg_override
  2481. .cluster
  2482. .as_ref()
  2483. .unwrap_or_else(|| &Cluster::Devnet)
  2484. .url();
  2485. loop {
  2486. let exit = std::process::Command::new("solana")
  2487. .arg("airdrop")
  2488. .arg("10")
  2489. .arg("--url")
  2490. .arg(&url)
  2491. .stdout(Stdio::inherit())
  2492. .stderr(Stdio::inherit())
  2493. .output()
  2494. .expect("Must airdrop");
  2495. if !exit.status.success() {
  2496. println!("There was a problem airdropping: {:?}.", exit);
  2497. std::process::exit(exit.status.code().unwrap_or(1));
  2498. }
  2499. std::thread::sleep(std::time::Duration::from_millis(10000));
  2500. }
  2501. }
  2502. fn cluster(_cmd: ClusterCommand) -> Result<()> {
  2503. println!("Cluster Endpoints:\n");
  2504. println!("* Mainnet - https://solana-api.projectserum.com");
  2505. println!("* Mainnet - https://api.mainnet-beta.solana.com");
  2506. println!("* Devnet - https://api.devnet.solana.com");
  2507. println!("* Testnet - https://api.testnet.solana.com");
  2508. Ok(())
  2509. }
  2510. fn shell(cfg_override: &ConfigOverride) -> Result<()> {
  2511. with_workspace(cfg_override, |cfg| {
  2512. let programs = {
  2513. // Create idl map from all workspace programs.
  2514. let mut idls: HashMap<String, Idl> = cfg
  2515. .read_all_programs()?
  2516. .iter()
  2517. .filter(|program| program.idl.is_some())
  2518. .map(|program| {
  2519. (
  2520. program.idl.as_ref().unwrap().name.clone(),
  2521. program.idl.clone().unwrap(),
  2522. )
  2523. })
  2524. .collect();
  2525. // Insert all manually specified idls into the idl map.
  2526. if let Some(programs) = cfg.programs.get(&cfg.provider.cluster) {
  2527. let _ = programs
  2528. .iter()
  2529. .map(|(name, pd)| {
  2530. if let Some(idl_fp) = &pd.idl {
  2531. let file_str =
  2532. fs::read_to_string(idl_fp).expect("Unable to read IDL file");
  2533. let idl = serde_json::from_str(&file_str).expect("Idl not readable");
  2534. idls.insert(name.clone(), idl);
  2535. }
  2536. })
  2537. .collect::<Vec<_>>();
  2538. }
  2539. // Finalize program list with all programs with IDLs.
  2540. match cfg.programs.get(&cfg.provider.cluster) {
  2541. None => Vec::new(),
  2542. Some(programs) => programs
  2543. .iter()
  2544. .filter_map(|(name, program_deployment)| {
  2545. Some(ProgramWorkspace {
  2546. name: name.to_string(),
  2547. program_id: program_deployment.address,
  2548. idl: match idls.get(name) {
  2549. None => return None,
  2550. Some(idl) => idl.clone(),
  2551. },
  2552. })
  2553. })
  2554. .collect::<Vec<ProgramWorkspace>>(),
  2555. }
  2556. };
  2557. let url = cluster_url(cfg, &cfg.test_validator);
  2558. let js_code = template::node_shell(&url, &cfg.provider.wallet.to_string(), programs)?;
  2559. let mut child = std::process::Command::new("node")
  2560. .args(&["-e", &js_code, "-i", "--experimental-repl-await"])
  2561. .stdout(Stdio::inherit())
  2562. .stderr(Stdio::inherit())
  2563. .spawn()
  2564. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  2565. if !child.wait()?.success() {
  2566. println!("Error running node shell");
  2567. return Ok(());
  2568. }
  2569. Ok(())
  2570. })
  2571. }
  2572. fn run(cfg_override: &ConfigOverride, script: String) -> Result<()> {
  2573. with_workspace(cfg_override, |cfg| {
  2574. let url = cluster_url(cfg, &cfg.test_validator);
  2575. let script = cfg
  2576. .scripts
  2577. .get(&script)
  2578. .ok_or_else(|| anyhow!("Unable to find script"))?;
  2579. let exit = std::process::Command::new("bash")
  2580. .arg("-c")
  2581. .arg(&script)
  2582. .env("ANCHOR_PROVIDER_URL", url)
  2583. .env("ANCHOR_WALLET", cfg.provider.wallet.to_string())
  2584. .stdout(Stdio::inherit())
  2585. .stderr(Stdio::inherit())
  2586. .output()
  2587. .unwrap();
  2588. if !exit.status.success() {
  2589. std::process::exit(exit.status.code().unwrap_or(1));
  2590. }
  2591. Ok(())
  2592. })
  2593. }
  2594. fn login(_cfg_override: &ConfigOverride, token: String) -> Result<()> {
  2595. let dir = shellexpand::tilde("~/.config/anchor");
  2596. if !Path::new(&dir.to_string()).exists() {
  2597. fs::create_dir(dir.to_string())?;
  2598. }
  2599. std::env::set_current_dir(dir.to_string())?;
  2600. // Freely overwrite the entire file since it's not used for anything else.
  2601. let mut file = File::create("credentials")?;
  2602. file.write_all(template::credentials(&token).as_bytes())?;
  2603. Ok(())
  2604. }
  2605. fn publish(
  2606. cfg_override: &ConfigOverride,
  2607. program_name: String,
  2608. cargo_args: Vec<String>,
  2609. ) -> Result<()> {
  2610. // Discover the various workspace configs.
  2611. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  2612. let program = cfg
  2613. .get_program(&program_name)?
  2614. .ok_or_else(|| anyhow!("Workspace member not found"))?;
  2615. let program_cargo_lock = pathdiff::diff_paths(
  2616. program.path().join("Cargo.lock"),
  2617. cfg.path().parent().unwrap(),
  2618. )
  2619. .ok_or_else(|| anyhow!("Unable to diff Cargo.lock path"))?;
  2620. let cargo_lock = Path::new("Cargo.lock");
  2621. // There must be a Cargo.lock
  2622. if !program_cargo_lock.exists() && !cargo_lock.exists() {
  2623. return Err(anyhow!("Cargo.lock must exist for a verifiable build"));
  2624. }
  2625. println!("Publishing will make your code public. Are you sure? Enter (yes)/no:");
  2626. let answer = std::io::stdin().lock().lines().next().unwrap().unwrap();
  2627. if answer != "yes" {
  2628. println!("Aborting");
  2629. return Ok(());
  2630. }
  2631. let anchor_package = AnchorPackage::from(program_name.clone(), &cfg)?;
  2632. let anchor_package_bytes = serde_json::to_vec(&anchor_package)?;
  2633. // Set directory to top of the workspace.
  2634. let workspace_dir = cfg.path().parent().unwrap();
  2635. std::env::set_current_dir(workspace_dir)?;
  2636. // Create the workspace tarball.
  2637. let dot_anchor = workspace_dir.join(".anchor");
  2638. fs::create_dir_all(&dot_anchor)?;
  2639. let tarball_filename = dot_anchor.join(format!("{}.tar.gz", program_name));
  2640. let tar_gz = File::create(&tarball_filename)?;
  2641. let enc = GzEncoder::new(tar_gz, Compression::default());
  2642. let mut tar = tar::Builder::new(enc);
  2643. // Files that will always be included if they exist.
  2644. println!("PACKING: Anchor.toml");
  2645. tar.append_path("Anchor.toml")?;
  2646. if cargo_lock.exists() {
  2647. println!("PACKING: Cargo.lock");
  2648. tar.append_path(cargo_lock)?;
  2649. }
  2650. if Path::new("Cargo.toml").exists() {
  2651. println!("PACKING: Cargo.toml");
  2652. tar.append_path("Cargo.toml")?;
  2653. }
  2654. if Path::new("LICENSE").exists() {
  2655. println!("PACKING: LICENSE");
  2656. tar.append_path("LICENSE")?;
  2657. }
  2658. if Path::new("README.md").exists() {
  2659. println!("PACKING: README.md");
  2660. tar.append_path("README.md")?;
  2661. }
  2662. // All workspace programs.
  2663. for path in cfg.get_program_list()? {
  2664. let mut dirs = walkdir::WalkDir::new(&path)
  2665. .into_iter()
  2666. .filter_entry(|e| !is_hidden(e));
  2667. // Skip the parent dir.
  2668. let _ = dirs.next().unwrap()?;
  2669. for entry in dirs {
  2670. let e = entry.map_err(|e| anyhow!("{:?}", e))?;
  2671. let e = pathdiff::diff_paths(e.path(), cfg.path().parent().unwrap())
  2672. .ok_or_else(|| anyhow!("Unable to diff paths"))?;
  2673. let path_str = e.display().to_string();
  2674. // Skip target dir.
  2675. if !path_str.contains("target/") && !path_str.contains("/target") {
  2676. // Only add the file if it's not empty.
  2677. let metadata = fs::File::open(&e)?.metadata()?;
  2678. if metadata.len() > 0 {
  2679. println!("PACKING: {}", e.display());
  2680. if e.is_dir() {
  2681. tar.append_dir_all(&e, &e)?;
  2682. } else {
  2683. tar.append_path(&e)?;
  2684. }
  2685. }
  2686. }
  2687. }
  2688. }
  2689. // Tar pack complete.
  2690. tar.into_inner()?;
  2691. // Create tmp directory for workspace.
  2692. let ws_dir = dot_anchor.join("workspace");
  2693. if Path::exists(&ws_dir) {
  2694. fs::remove_dir_all(&ws_dir)?;
  2695. }
  2696. fs::create_dir_all(&ws_dir)?;
  2697. // Unpack the archive into the new workspace directory.
  2698. std::env::set_current_dir(&ws_dir)?;
  2699. unpack_archive(&tarball_filename)?;
  2700. // Build the program before sending it to the server.
  2701. build(
  2702. cfg_override,
  2703. None,
  2704. None,
  2705. true,
  2706. false,
  2707. Some(program_name),
  2708. None,
  2709. None,
  2710. BootstrapMode::None,
  2711. None,
  2712. None,
  2713. cargo_args,
  2714. true,
  2715. )?;
  2716. // Success. Now we can finally upload to the server without worrying
  2717. // about a build failure.
  2718. // Upload the tarball to the server.
  2719. let token = registry_api_token(cfg_override)?;
  2720. let form = Form::new()
  2721. .part("manifest", Part::bytes(anchor_package_bytes))
  2722. .part("workspace", {
  2723. let file = File::open(&tarball_filename)?;
  2724. Part::reader(file)
  2725. });
  2726. let client = Client::new();
  2727. let resp = client
  2728. .post(&format!("{}/api/v0/build", cfg.registry.url))
  2729. .bearer_auth(token)
  2730. .multipart(form)
  2731. .send()?;
  2732. if resp.status() == 200 {
  2733. println!("Build triggered");
  2734. } else {
  2735. println!(
  2736. "{:?}",
  2737. resp.text().unwrap_or_else(|_| "Server error".to_string())
  2738. );
  2739. }
  2740. Ok(())
  2741. }
  2742. // Unpacks the tarball into the current directory.
  2743. fn unpack_archive(tar_path: impl AsRef<Path>) -> Result<()> {
  2744. let tar = GzDecoder::new(std::fs::File::open(tar_path)?);
  2745. let mut archive = Archive::new(tar);
  2746. archive.unpack(".")?;
  2747. archive.into_inner();
  2748. Ok(())
  2749. }
  2750. fn registry_api_token(_cfg_override: &ConfigOverride) -> Result<String> {
  2751. #[derive(Debug, Deserialize)]
  2752. struct Registry {
  2753. token: String,
  2754. }
  2755. #[derive(Debug, Deserialize)]
  2756. struct Credentials {
  2757. registry: Registry,
  2758. }
  2759. let filename = shellexpand::tilde("~/.config/anchor/credentials");
  2760. let mut file = File::open(filename.to_string())?;
  2761. let mut contents = String::new();
  2762. file.read_to_string(&mut contents)?;
  2763. let credentials_toml: Credentials = toml::from_str(&contents)?;
  2764. Ok(credentials_toml.registry.token)
  2765. }
  2766. fn keys(cfg_override: &ConfigOverride, cmd: KeysCommand) -> Result<()> {
  2767. match cmd {
  2768. KeysCommand::List => keys_list(cfg_override),
  2769. }
  2770. }
  2771. fn keys_list(cfg_override: &ConfigOverride) -> Result<()> {
  2772. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  2773. for program in cfg.read_all_programs()? {
  2774. let pubkey = program.pubkey()?;
  2775. println!("{}: {}", program.lib_name, pubkey);
  2776. }
  2777. Ok(())
  2778. }
  2779. fn localnet(
  2780. cfg_override: &ConfigOverride,
  2781. skip_build: bool,
  2782. skip_deploy: bool,
  2783. skip_lint: bool,
  2784. cargo_args: Vec<String>,
  2785. ) -> Result<()> {
  2786. with_workspace(cfg_override, |cfg| {
  2787. // Build if needed.
  2788. if !skip_build {
  2789. build(
  2790. cfg_override,
  2791. None,
  2792. None,
  2793. false,
  2794. skip_lint,
  2795. None,
  2796. None,
  2797. None,
  2798. BootstrapMode::None,
  2799. None,
  2800. None,
  2801. cargo_args,
  2802. false,
  2803. )?;
  2804. }
  2805. let flags = match skip_deploy {
  2806. true => None,
  2807. false => Some(validator_flags(cfg, &cfg.test_validator)?),
  2808. };
  2809. let validator_handle = &mut start_test_validator(cfg, &cfg.test_validator, flags, false)?;
  2810. // Setup log reader.
  2811. let url = test_validator_rpc_url(&cfg.test_validator);
  2812. let log_streams = stream_logs(cfg, &url);
  2813. std::io::stdin().lock().lines().next().unwrap().unwrap();
  2814. // Check all errors and shut down.
  2815. if let Err(err) = validator_handle.kill() {
  2816. println!(
  2817. "Failed to kill subprocess {}: {}",
  2818. validator_handle.id(),
  2819. err
  2820. );
  2821. }
  2822. for mut child in log_streams? {
  2823. if let Err(err) = child.kill() {
  2824. println!("Failed to kill subprocess {}: {}", child.id(), err);
  2825. }
  2826. }
  2827. Ok(())
  2828. })
  2829. }
  2830. // with_workspace ensures the current working directory is always the top level
  2831. // workspace directory, i.e., where the `Anchor.toml` file is located, before
  2832. // and after the closure invocation.
  2833. //
  2834. // The closure passed into this function must never change the working directory
  2835. // to be outside the workspace. Doing so will have undefined behavior.
  2836. fn with_workspace<R>(
  2837. cfg_override: &ConfigOverride,
  2838. f: impl FnOnce(&mut WithPath<Config>) -> R,
  2839. ) -> R {
  2840. set_workspace_dir_or_exit();
  2841. let mut cfg = Config::discover(cfg_override)
  2842. .expect("Previously set the workspace dir")
  2843. .expect("Anchor.toml must always exist");
  2844. let r = f(&mut cfg);
  2845. set_workspace_dir_or_exit();
  2846. r
  2847. }
  2848. fn is_hidden(entry: &walkdir::DirEntry) -> bool {
  2849. entry
  2850. .file_name()
  2851. .to_str()
  2852. .map(|s| s == "." || s.starts_with('.') || s == "target")
  2853. .unwrap_or(false)
  2854. }
  2855. fn get_node_version() -> Result<Version> {
  2856. let node_version = std::process::Command::new("node")
  2857. .arg("--version")
  2858. .stderr(Stdio::inherit())
  2859. .output()
  2860. .map_err(|e| anyhow::format_err!("node failed: {}", e.to_string()))?;
  2861. let output = std::str::from_utf8(&node_version.stdout)?
  2862. .strip_prefix('v')
  2863. .unwrap()
  2864. .trim();
  2865. Version::parse(output).map_err(Into::into)
  2866. }
  2867. fn get_node_dns_option() -> Result<&'static str> {
  2868. let version = get_node_version()?;
  2869. let req = VersionReq::parse(">=16.4.0").unwrap();
  2870. let option = match req.matches(&version) {
  2871. true => "--dns-result-order=ipv4first",
  2872. false => "",
  2873. };
  2874. Ok(option)
  2875. }