lib.rs 155 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766
  1. use crate::config::{
  2. AnchorPackage, BootstrapMode, BuildConfig, Config, ConfigOverride, Manifest, ProgramArch,
  3. ProgramDeployment, ProgramWorkspace, ScriptsConfig, TestValidator, WithPath,
  4. DEFAULT_LEDGER_PATH, SHUTDOWN_WAIT, STARTUP_WAIT,
  5. };
  6. use anchor_client::Cluster;
  7. use anchor_lang::idl::{IdlAccount, IdlInstruction, ERASED_AUTHORITY};
  8. use anchor_lang::{AccountDeserialize, AnchorDeserialize, AnchorSerialize, Discriminator};
  9. use anchor_lang_idl::convert::convert_idl;
  10. use anchor_lang_idl::types::{Idl, IdlArrayLen, IdlDefinedFields, IdlType, IdlTypeDefTy};
  11. use anyhow::{anyhow, Context, Result};
  12. use checks::{check_anchor_version, check_idl_build_feature, check_overflow};
  13. use clap::Parser;
  14. use dirs::home_dir;
  15. use flate2::read::GzDecoder;
  16. use flate2::read::ZlibDecoder;
  17. use flate2::write::{GzEncoder, ZlibEncoder};
  18. use flate2::Compression;
  19. use heck::{ToKebabCase, ToLowerCamelCase, ToPascalCase, ToSnakeCase};
  20. use regex::{Regex, RegexBuilder};
  21. use reqwest::blocking::multipart::{Form, Part};
  22. use reqwest::blocking::Client;
  23. use rust_template::{ProgramTemplate, TestTemplate};
  24. use semver::{Version, VersionReq};
  25. use serde::Deserialize;
  26. use serde_json::{json, Map, Value as JsonValue};
  27. use solana_client::rpc_client::RpcClient;
  28. use solana_program::instruction::{AccountMeta, Instruction};
  29. use solana_sdk::account_utils::StateMut;
  30. use solana_sdk::bpf_loader;
  31. use solana_sdk::bpf_loader_deprecated;
  32. use solana_sdk::bpf_loader_upgradeable::{self, UpgradeableLoaderState};
  33. use solana_sdk::commitment_config::CommitmentConfig;
  34. use solana_sdk::compute_budget::ComputeBudgetInstruction;
  35. use solana_sdk::pubkey::Pubkey;
  36. use solana_sdk::signature::Keypair;
  37. use solana_sdk::signature::Signer;
  38. use solana_sdk::sysvar;
  39. use solana_sdk::transaction::Transaction;
  40. use std::collections::BTreeMap;
  41. use std::collections::HashMap;
  42. use std::collections::HashSet;
  43. use std::ffi::OsString;
  44. use std::fs::{self, File};
  45. use std::io::prelude::*;
  46. use std::path::{Path, PathBuf};
  47. use std::process::{Child, Stdio};
  48. use std::str::FromStr;
  49. use std::string::ToString;
  50. use tar::Archive;
  51. mod checks;
  52. pub mod config;
  53. pub mod rust_template;
  54. pub mod solidity_template;
  55. // Version of the docker image.
  56. pub const VERSION: &str = env!("CARGO_PKG_VERSION");
  57. pub const DOCKER_BUILDER_VERSION: &str = VERSION;
  58. #[derive(Debug, Parser)]
  59. #[clap(version = VERSION)]
  60. pub struct Opts {
  61. #[clap(flatten)]
  62. pub cfg_override: ConfigOverride,
  63. #[clap(subcommand)]
  64. pub command: Command,
  65. }
  66. #[derive(Debug, Parser)]
  67. pub enum Command {
  68. /// Initializes a workspace.
  69. Init {
  70. /// Workspace name
  71. name: String,
  72. /// Use JavaScript instead of TypeScript
  73. #[clap(short, long)]
  74. javascript: bool,
  75. /// Use Solidity instead of Rust
  76. #[clap(short, long)]
  77. solidity: bool,
  78. /// Don't install JavaScript dependencies
  79. #[clap(long)]
  80. no_install: bool,
  81. /// Don't initialize git
  82. #[clap(long)]
  83. no_git: bool,
  84. /// Rust program template to use
  85. #[clap(value_enum, short, long, default_value = "single")]
  86. template: ProgramTemplate,
  87. /// Test template to use
  88. #[clap(value_enum, long, default_value = "mocha")]
  89. test_template: TestTemplate,
  90. /// Initialize even if there are files
  91. #[clap(long, action)]
  92. force: bool,
  93. },
  94. /// Builds the workspace.
  95. #[clap(name = "build", alias = "b")]
  96. Build {
  97. /// True if the build should not fail even if there are no "CHECK" comments
  98. #[clap(long)]
  99. skip_lint: bool,
  100. /// Do not build the IDL
  101. #[clap(long)]
  102. no_idl: bool,
  103. /// Output directory for the IDL.
  104. #[clap(short, long)]
  105. idl: Option<String>,
  106. /// Output directory for the TypeScript IDL.
  107. #[clap(short = 't', long)]
  108. idl_ts: Option<String>,
  109. /// True if the build artifact needs to be deterministic and verifiable.
  110. #[clap(short, long)]
  111. verifiable: bool,
  112. /// Name of the program to build
  113. #[clap(short, long)]
  114. program_name: Option<String>,
  115. /// Version of the Solana toolchain to use. For --verifiable builds
  116. /// only.
  117. #[clap(short, long)]
  118. solana_version: Option<String>,
  119. /// Docker image to use. For --verifiable builds only.
  120. #[clap(short, long)]
  121. docker_image: Option<String>,
  122. /// Bootstrap docker image from scratch, installing all requirements for
  123. /// verifiable builds. Only works for debian-based images.
  124. #[clap(value_enum, short, long, default_value = "none")]
  125. bootstrap: BootstrapMode,
  126. /// Environment variables to pass into the docker container
  127. #[clap(short, long, required = false)]
  128. env: Vec<String>,
  129. /// Arguments to pass to the underlying `cargo build-sbf` command
  130. #[clap(required = false, last = true)]
  131. cargo_args: Vec<String>,
  132. /// Suppress doc strings in IDL output
  133. #[clap(long)]
  134. no_docs: bool,
  135. /// Architecture to use when building the program
  136. #[clap(value_enum, long, default_value = "sbf")]
  137. arch: ProgramArch,
  138. },
  139. /// Expands macros (wrapper around cargo expand)
  140. ///
  141. /// Use it in a program folder to expand program
  142. ///
  143. /// Use it in a workspace but outside a program
  144. /// folder to expand the entire workspace
  145. Expand {
  146. /// Expand only this program
  147. #[clap(short, long)]
  148. program_name: Option<String>,
  149. /// Arguments to pass to the underlying `cargo expand` command
  150. #[clap(required = false, last = true)]
  151. cargo_args: Vec<String>,
  152. },
  153. /// Verifies the on-chain bytecode matches the locally compiled artifact.
  154. /// Run this command inside a program subdirectory, i.e., in the dir
  155. /// containing the program's Cargo.toml.
  156. Verify {
  157. /// The deployed program to compare against.
  158. program_id: Pubkey,
  159. #[clap(short, long)]
  160. program_name: Option<String>,
  161. /// Version of the Solana toolchain to use. For --verifiable builds
  162. /// only.
  163. #[clap(short, long)]
  164. solana_version: Option<String>,
  165. /// Docker image to use. For --verifiable builds only.
  166. #[clap(short, long)]
  167. docker_image: Option<String>,
  168. /// Bootstrap docker image from scratch, installing all requirements for
  169. /// verifiable builds. Only works for debian-based images.
  170. #[clap(value_enum, short, long, default_value = "none")]
  171. bootstrap: BootstrapMode,
  172. /// Architecture to use when building the program
  173. #[clap(value_enum, long, default_value = "sbf")]
  174. arch: ProgramArch,
  175. /// Environment variables to pass into the docker container
  176. #[clap(short, long, required = false)]
  177. env: Vec<String>,
  178. /// Arguments to pass to the underlying `cargo build-sbf` command.
  179. #[clap(required = false, last = true)]
  180. cargo_args: Vec<String>,
  181. /// Flag to skip building the program in the workspace,
  182. /// use this to save time when running verify and the program code is already built.
  183. #[clap(long, required = false)]
  184. skip_build: bool,
  185. },
  186. #[clap(name = "test", alias = "t")]
  187. /// Runs integration tests.
  188. Test {
  189. /// Build and test only this program
  190. #[clap(short, long)]
  191. program_name: Option<String>,
  192. /// Use this flag if you want to run tests against previously deployed
  193. /// programs.
  194. #[clap(long)]
  195. skip_deploy: bool,
  196. /// True if the build should not fail even if there are
  197. /// no "CHECK" comments where normally required
  198. #[clap(long)]
  199. skip_lint: bool,
  200. /// Flag to skip starting a local validator, if the configured cluster
  201. /// url is a localnet.
  202. #[clap(long)]
  203. skip_local_validator: bool,
  204. /// Flag to skip building the program in the workspace,
  205. /// use this to save time when running test and the program code is not altered.
  206. #[clap(long)]
  207. skip_build: bool,
  208. /// Do not build the IDL
  209. #[clap(long)]
  210. no_idl: bool,
  211. /// Architecture to use when building the program
  212. #[clap(value_enum, long, default_value = "sbf")]
  213. arch: ProgramArch,
  214. /// Flag to keep the local validator running after tests
  215. /// to be able to check the transactions.
  216. #[clap(long)]
  217. detach: bool,
  218. /// Run the test suites under the specified path
  219. #[clap(long)]
  220. run: Vec<String>,
  221. args: Vec<String>,
  222. /// Environment variables to pass into the docker container
  223. #[clap(short, long, required = false)]
  224. env: Vec<String>,
  225. /// Arguments to pass to the underlying `cargo build-sbf` command.
  226. #[clap(required = false, last = true)]
  227. cargo_args: Vec<String>,
  228. },
  229. /// Creates a new program.
  230. New {
  231. /// Program name
  232. name: String,
  233. /// Use Solidity instead of Rust
  234. #[clap(short, long)]
  235. solidity: bool,
  236. /// Rust program template to use
  237. #[clap(value_enum, short, long, default_value = "single")]
  238. template: ProgramTemplate,
  239. /// Create new program even if there is already one
  240. #[clap(long, action)]
  241. force: bool,
  242. },
  243. /// Commands for interacting with interface definitions.
  244. Idl {
  245. #[clap(subcommand)]
  246. subcmd: IdlCommand,
  247. },
  248. /// Remove all artifacts from the target directory except program keypairs.
  249. Clean,
  250. /// Deploys each program in the workspace.
  251. Deploy {
  252. /// Only deploy this program
  253. #[clap(short, long)]
  254. program_name: Option<String>,
  255. /// Keypair of the program (filepath) (requires program-name)
  256. #[clap(long, requires = "program_name")]
  257. program_keypair: Option<String>,
  258. /// If true, deploy from path target/verifiable
  259. #[clap(short, long)]
  260. verifiable: bool,
  261. /// Arguments to pass to the underlying `solana program deploy` command.
  262. #[clap(required = false, last = true)]
  263. solana_args: Vec<String>,
  264. },
  265. /// Runs the deploy migration script.
  266. Migrate,
  267. /// Deploys, initializes an IDL, and migrates all in one command.
  268. /// Upgrades a single program. The configured wallet must be the upgrade
  269. /// authority.
  270. Upgrade {
  271. /// The program to upgrade.
  272. #[clap(short, long)]
  273. program_id: Pubkey,
  274. /// Filepath to the new program binary.
  275. program_filepath: String,
  276. /// Arguments to pass to the underlying `solana program deploy` command.
  277. #[clap(required = false, last = true)]
  278. solana_args: Vec<String>,
  279. },
  280. #[cfg(feature = "dev")]
  281. /// Runs an airdrop loop, continuously funding the configured wallet.
  282. Airdrop {
  283. #[clap(short, long)]
  284. url: Option<String>,
  285. },
  286. /// Cluster commands.
  287. Cluster {
  288. #[clap(subcommand)]
  289. subcmd: ClusterCommand,
  290. },
  291. /// Starts a node shell with an Anchor client setup according to the local
  292. /// config.
  293. Shell,
  294. /// Runs the script defined by the current workspace's Anchor.toml.
  295. Run {
  296. /// The name of the script to run.
  297. script: String,
  298. /// Argument to pass to the underlying script.
  299. #[clap(required = false, last = true)]
  300. script_args: Vec<String>,
  301. },
  302. /// Saves an api token from the registry locally.
  303. Login {
  304. /// API access token.
  305. token: String,
  306. },
  307. /// Publishes a verified build to the Anchor registry.
  308. Publish {
  309. /// The name of the program to publish.
  310. program: String,
  311. /// Environment variables to pass into the docker container
  312. #[clap(short, long, required = false)]
  313. env: Vec<String>,
  314. /// Arguments to pass to the underlying `cargo build-sbf` command.
  315. #[clap(required = false, last = true)]
  316. cargo_args: Vec<String>,
  317. /// Flag to skip building the program in the workspace,
  318. /// use this to save time when publishing the program
  319. #[clap(long)]
  320. skip_build: bool,
  321. /// Architecture to use when building the program
  322. #[clap(value_enum, long, default_value = "sbf")]
  323. arch: ProgramArch,
  324. },
  325. /// Keypair commands.
  326. Keys {
  327. #[clap(subcommand)]
  328. subcmd: KeysCommand,
  329. },
  330. /// Localnet commands.
  331. Localnet {
  332. /// Flag to skip building the program in the workspace,
  333. /// use this to save time when running test and the program code is not altered.
  334. #[clap(long)]
  335. skip_build: bool,
  336. /// Use this flag if you want to run tests against previously deployed
  337. /// programs.
  338. #[clap(long)]
  339. skip_deploy: bool,
  340. /// True if the build should not fail even if there are
  341. /// no "CHECK" comments where normally required
  342. #[clap(long)]
  343. skip_lint: bool,
  344. /// Architecture to use when building the program
  345. #[clap(value_enum, long, default_value = "sbf")]
  346. arch: ProgramArch,
  347. /// Environment variables to pass into the docker container
  348. #[clap(short, long, required = false)]
  349. env: Vec<String>,
  350. /// Arguments to pass to the underlying `cargo build-sbf` command.
  351. #[clap(required = false, last = true)]
  352. cargo_args: Vec<String>,
  353. },
  354. /// Fetch and deserialize an account using the IDL provided.
  355. Account {
  356. /// Account struct to deserialize
  357. account_type: String,
  358. /// Address of the account to deserialize
  359. address: Pubkey,
  360. /// IDL to use (defaults to workspace IDL)
  361. #[clap(long)]
  362. idl: Option<String>,
  363. },
  364. }
  365. #[derive(Debug, Parser)]
  366. pub enum KeysCommand {
  367. /// List all of the program keys.
  368. List,
  369. /// Sync the program's `declare_id!` pubkey with the program's actual pubkey.
  370. Sync {
  371. /// Only sync the given program instead of all programs
  372. #[clap(short, long)]
  373. program_name: Option<String>,
  374. },
  375. }
  376. #[derive(Debug, Parser)]
  377. pub enum IdlCommand {
  378. /// Initializes a program's IDL account. Can only be run once.
  379. Init {
  380. program_id: Pubkey,
  381. #[clap(short, long)]
  382. filepath: String,
  383. #[clap(long)]
  384. priority_fee: Option<u64>,
  385. },
  386. Close {
  387. program_id: Pubkey,
  388. /// The IDL account to close. If none is given, then the IDL account derived from program_id is used.
  389. #[clap(long)]
  390. idl_address: Option<Pubkey>,
  391. /// When used, the content of the instruction will only be printed in base64 form and not executed.
  392. /// Useful for multisig execution when the local wallet keypair is not available.
  393. #[clap(long)]
  394. print_only: bool,
  395. #[clap(long)]
  396. priority_fee: Option<u64>,
  397. },
  398. /// Writes an IDL into a buffer account. This can be used with SetBuffer
  399. /// to perform an upgrade.
  400. WriteBuffer {
  401. program_id: Pubkey,
  402. #[clap(short, long)]
  403. filepath: String,
  404. #[clap(long)]
  405. priority_fee: Option<u64>,
  406. },
  407. /// Sets a new IDL buffer for the program.
  408. SetBuffer {
  409. program_id: Pubkey,
  410. /// Address of the buffer account to set as the idl on the program.
  411. #[clap(short, long)]
  412. buffer: Pubkey,
  413. /// When used, the content of the instruction will only be printed in base64 form and not executed.
  414. /// Useful for multisig execution when the local wallet keypair is not available.
  415. #[clap(long)]
  416. print_only: bool,
  417. #[clap(long)]
  418. priority_fee: Option<u64>,
  419. },
  420. /// Upgrades the IDL to the new file. An alias for first writing and then
  421. /// then setting the idl buffer account.
  422. Upgrade {
  423. program_id: Pubkey,
  424. #[clap(short, long)]
  425. filepath: String,
  426. #[clap(long)]
  427. priority_fee: Option<u64>,
  428. },
  429. /// Sets a new authority on the IDL account.
  430. SetAuthority {
  431. /// The IDL account buffer to set the authority of. If none is given,
  432. /// then the canonical IDL account is used.
  433. address: Option<Pubkey>,
  434. /// Program to change the IDL authority.
  435. #[clap(short, long)]
  436. program_id: Pubkey,
  437. /// New authority of the IDL account.
  438. #[clap(short, long)]
  439. new_authority: Pubkey,
  440. /// When used, the content of the instruction will only be printed in base64 form and not executed.
  441. /// Useful for multisig execution when the local wallet keypair is not available.
  442. #[clap(long)]
  443. print_only: bool,
  444. #[clap(long)]
  445. priority_fee: Option<u64>,
  446. },
  447. /// Command to remove the ability to modify the IDL account. This should
  448. /// likely be used in conjection with eliminating an "upgrade authority" on
  449. /// the program.
  450. EraseAuthority {
  451. #[clap(short, long)]
  452. program_id: Pubkey,
  453. #[clap(long)]
  454. priority_fee: Option<u64>,
  455. },
  456. /// Outputs the authority for the IDL account.
  457. Authority {
  458. /// The program to view.
  459. program_id: Pubkey,
  460. },
  461. /// Generates the IDL for the program using the compilation method.
  462. Build {
  463. // Program name to build the IDL of(current dir's program if not specified)
  464. #[clap(short, long)]
  465. program_name: Option<String>,
  466. /// Output file for the IDL (stdout if not specified)
  467. #[clap(short, long)]
  468. out: Option<String>,
  469. /// Output file for the TypeScript IDL
  470. #[clap(short = 't', long)]
  471. out_ts: Option<String>,
  472. /// Suppress doc strings in output
  473. #[clap(long)]
  474. no_docs: bool,
  475. /// Do not check for safety comments
  476. #[clap(long)]
  477. skip_lint: bool,
  478. /// Arguments to pass to the underlying `cargo test` command
  479. #[clap(required = false, last = true)]
  480. cargo_args: Vec<String>,
  481. },
  482. /// Fetches an IDL for the given address from a cluster.
  483. /// The address can be a program, IDL account, or IDL buffer.
  484. Fetch {
  485. address: Pubkey,
  486. /// Output file for the IDL (stdout if not specified).
  487. #[clap(short, long)]
  488. out: Option<String>,
  489. },
  490. /// Convert legacy IDLs (pre Anchor 0.30) to the new IDL spec
  491. Convert {
  492. /// Path to the IDL file
  493. path: String,
  494. /// Output file for the IDL (stdout if not specified)
  495. #[clap(short, long)]
  496. out: Option<String>,
  497. },
  498. /// Generate TypeScript type for the IDL
  499. Type {
  500. /// Path to the IDL file
  501. path: String,
  502. /// Output file for the IDL (stdout if not specified)
  503. #[clap(short, long)]
  504. out: Option<String>,
  505. },
  506. }
  507. #[derive(Debug, Parser)]
  508. pub enum ClusterCommand {
  509. /// Prints common cluster urls.
  510. List,
  511. }
  512. fn get_keypair(path: &str) -> Result<Keypair> {
  513. solana_sdk::signature::read_keypair_file(path)
  514. .map_err(|_| anyhow!("Unable to read keypair file ({path})"))
  515. }
  516. pub fn entry(opts: Opts) -> Result<()> {
  517. let restore_cbs = override_toolchain(&opts.cfg_override)?;
  518. let result = process_command(opts);
  519. restore_toolchain(restore_cbs)?;
  520. result
  521. }
  522. /// Functions to restore toolchain entries
  523. type RestoreToolchainCallbacks = Vec<Box<dyn FnOnce() -> Result<()>>>;
  524. /// Override the toolchain from `Anchor.toml`.
  525. ///
  526. /// Returns the previous versions to restore back to.
  527. fn override_toolchain(cfg_override: &ConfigOverride) -> Result<RestoreToolchainCallbacks> {
  528. let mut restore_cbs: RestoreToolchainCallbacks = vec![];
  529. let cfg = Config::discover(cfg_override)?;
  530. if let Some(cfg) = cfg {
  531. fn parse_version(text: &str) -> String {
  532. Regex::new(r"(\d+\.\d+\.\S+)")
  533. .unwrap()
  534. .captures_iter(text)
  535. .next()
  536. .unwrap()
  537. .get(0)
  538. .unwrap()
  539. .as_str()
  540. .to_string()
  541. }
  542. fn get_current_version(cmd_name: &str) -> Result<String> {
  543. let output = std::process::Command::new(cmd_name)
  544. .arg("--version")
  545. .output()?;
  546. if !output.status.success() {
  547. return Err(anyhow!("Failed to run `{cmd_name} --version`"));
  548. }
  549. let output_version = std::str::from_utf8(&output.stdout)?;
  550. let version = parse_version(output_version);
  551. Ok(version)
  552. }
  553. if let Some(solana_version) = &cfg.toolchain.solana_version {
  554. let current_version = get_current_version("solana")?;
  555. if solana_version != &current_version {
  556. // We are overriding with `solana-install` command instead of using the binaries
  557. // from `~/.local/share/solana/install/releases` because we use multiple Solana
  558. // binaries in various commands.
  559. fn override_solana_version(version: String) -> Result<bool> {
  560. let output = std::process::Command::new("solana-install")
  561. .arg("list")
  562. .output()?;
  563. if !output.status.success() {
  564. return Err(anyhow!("Failed to list installed `solana` versions"));
  565. }
  566. // Hide the installation progress if the version is already installed
  567. let is_installed = std::str::from_utf8(&output.stdout)?
  568. .lines()
  569. .any(|line| parse_version(line) == version);
  570. let (stderr, stdout) = if is_installed {
  571. (Stdio::null(), Stdio::null())
  572. } else {
  573. (Stdio::inherit(), Stdio::inherit())
  574. };
  575. std::process::Command::new("solana-install")
  576. .arg("init")
  577. .arg(&version)
  578. .stderr(stderr)
  579. .stdout(stdout)
  580. .spawn()?
  581. .wait()
  582. .map(|status| status.success())
  583. .map_err(|err| anyhow!("Failed to run `solana-install` command: {err}"))
  584. }
  585. match override_solana_version(solana_version.to_owned())? {
  586. true => restore_cbs.push(Box::new(|| {
  587. match override_solana_version(current_version)? {
  588. true => Ok(()),
  589. false => Err(anyhow!("Failed to restore `solana` version")),
  590. }
  591. })),
  592. false => eprintln!(
  593. "Failed to override `solana` version to {solana_version}, \
  594. using {current_version} instead"
  595. ),
  596. }
  597. }
  598. }
  599. // Anchor version override should be handled last
  600. if let Some(anchor_version) = &cfg.toolchain.anchor_version {
  601. // Anchor binary name prefix(applies to binaries that are installed via `avm`)
  602. const ANCHOR_BINARY_PREFIX: &str = "anchor-";
  603. // Get the current version from the executing binary name if possible because commit
  604. // based toolchain overrides do not have version information.
  605. let current_version = std::env::args()
  606. .next()
  607. .expect("First arg should exist")
  608. .parse::<PathBuf>()?
  609. .file_name()
  610. .and_then(|name| name.to_str())
  611. .expect("File name should be valid Unicode")
  612. .split_once(ANCHOR_BINARY_PREFIX)
  613. .map(|(_, version)| version)
  614. .unwrap_or(VERSION)
  615. .to_owned();
  616. if anchor_version != &current_version {
  617. let binary_path = home_dir()
  618. .unwrap()
  619. .join(".avm")
  620. .join("bin")
  621. .join(format!("{ANCHOR_BINARY_PREFIX}{anchor_version}"));
  622. if !binary_path.exists() {
  623. eprintln!(
  624. "`anchor` {anchor_version} is not installed with `avm`. Installing...\n"
  625. );
  626. let exit_status = std::process::Command::new("avm")
  627. .arg("install")
  628. .arg(anchor_version)
  629. .spawn()?
  630. .wait()?;
  631. if !exit_status.success() {
  632. eprintln!(
  633. "Failed to install `anchor` {anchor_version}, \
  634. using {current_version} instead"
  635. );
  636. return Ok(restore_cbs);
  637. }
  638. }
  639. let exit_code = std::process::Command::new(binary_path)
  640. .args(std::env::args_os().skip(1))
  641. .spawn()?
  642. .wait()?
  643. .code()
  644. .unwrap_or(1);
  645. restore_toolchain(restore_cbs)?;
  646. std::process::exit(exit_code);
  647. }
  648. }
  649. }
  650. Ok(restore_cbs)
  651. }
  652. /// Restore toolchain to how it was before the command was run.
  653. fn restore_toolchain(restore_cbs: RestoreToolchainCallbacks) -> Result<()> {
  654. for restore_toolchain in restore_cbs {
  655. if let Err(e) = restore_toolchain() {
  656. eprintln!("Toolchain error: {e}");
  657. }
  658. }
  659. Ok(())
  660. }
  661. /// Get the system's default license - what 'npm init' would use.
  662. fn get_npm_init_license() -> Result<String> {
  663. let npm_init_license_output = std::process::Command::new("npm")
  664. .arg("config")
  665. .arg("get")
  666. .arg("init-license")
  667. .output()?;
  668. if !npm_init_license_output.status.success() {
  669. return Err(anyhow!("Failed to get npm init license"));
  670. }
  671. let license = String::from_utf8(npm_init_license_output.stdout)?;
  672. Ok(license.trim().to_string())
  673. }
  674. fn process_command(opts: Opts) -> Result<()> {
  675. match opts.command {
  676. Command::Init {
  677. name,
  678. javascript,
  679. solidity,
  680. no_install,
  681. no_git,
  682. template,
  683. test_template,
  684. force,
  685. } => init(
  686. &opts.cfg_override,
  687. name,
  688. javascript,
  689. solidity,
  690. no_install,
  691. no_git,
  692. template,
  693. test_template,
  694. force,
  695. ),
  696. Command::New {
  697. solidity,
  698. name,
  699. template,
  700. force,
  701. } => new(&opts.cfg_override, solidity, name, template, force),
  702. Command::Build {
  703. no_idl,
  704. idl,
  705. idl_ts,
  706. verifiable,
  707. program_name,
  708. solana_version,
  709. docker_image,
  710. bootstrap,
  711. cargo_args,
  712. env,
  713. skip_lint,
  714. no_docs,
  715. arch,
  716. } => build(
  717. &opts.cfg_override,
  718. no_idl,
  719. idl,
  720. idl_ts,
  721. verifiable,
  722. skip_lint,
  723. program_name,
  724. solana_version,
  725. docker_image,
  726. bootstrap,
  727. None,
  728. None,
  729. env,
  730. cargo_args,
  731. no_docs,
  732. arch,
  733. ),
  734. Command::Verify {
  735. program_id,
  736. program_name,
  737. solana_version,
  738. docker_image,
  739. bootstrap,
  740. env,
  741. cargo_args,
  742. skip_build,
  743. arch,
  744. } => verify(
  745. &opts.cfg_override,
  746. program_id,
  747. program_name,
  748. solana_version,
  749. docker_image,
  750. bootstrap,
  751. env,
  752. cargo_args,
  753. skip_build,
  754. arch,
  755. ),
  756. Command::Clean => clean(&opts.cfg_override),
  757. Command::Deploy {
  758. program_name,
  759. program_keypair,
  760. verifiable,
  761. solana_args,
  762. } => deploy(
  763. &opts.cfg_override,
  764. program_name,
  765. program_keypair,
  766. verifiable,
  767. solana_args,
  768. ),
  769. Command::Expand {
  770. program_name,
  771. cargo_args,
  772. } => expand(&opts.cfg_override, program_name, &cargo_args),
  773. Command::Upgrade {
  774. program_id,
  775. program_filepath,
  776. solana_args,
  777. } => upgrade(
  778. &opts.cfg_override,
  779. program_id,
  780. program_filepath,
  781. solana_args,
  782. ),
  783. Command::Idl { subcmd } => idl(&opts.cfg_override, subcmd),
  784. Command::Migrate => migrate(&opts.cfg_override),
  785. Command::Test {
  786. program_name,
  787. skip_deploy,
  788. skip_local_validator,
  789. skip_build,
  790. no_idl,
  791. detach,
  792. run,
  793. args,
  794. env,
  795. cargo_args,
  796. skip_lint,
  797. arch,
  798. } => test(
  799. &opts.cfg_override,
  800. program_name,
  801. skip_deploy,
  802. skip_local_validator,
  803. skip_build,
  804. skip_lint,
  805. no_idl,
  806. detach,
  807. run,
  808. args,
  809. env,
  810. cargo_args,
  811. arch,
  812. ),
  813. #[cfg(feature = "dev")]
  814. Command::Airdrop { .. } => airdrop(&opts.cfg_override),
  815. Command::Cluster { subcmd } => cluster(subcmd),
  816. Command::Shell => shell(&opts.cfg_override),
  817. Command::Run {
  818. script,
  819. script_args,
  820. } => run(&opts.cfg_override, script, script_args),
  821. Command::Login { token } => login(&opts.cfg_override, token),
  822. Command::Publish {
  823. program,
  824. env,
  825. cargo_args,
  826. skip_build,
  827. arch,
  828. } => publish(
  829. &opts.cfg_override,
  830. program,
  831. env,
  832. cargo_args,
  833. skip_build,
  834. arch,
  835. ),
  836. Command::Keys { subcmd } => keys(&opts.cfg_override, subcmd),
  837. Command::Localnet {
  838. skip_build,
  839. skip_deploy,
  840. skip_lint,
  841. env,
  842. cargo_args,
  843. arch,
  844. } => localnet(
  845. &opts.cfg_override,
  846. skip_build,
  847. skip_deploy,
  848. skip_lint,
  849. env,
  850. cargo_args,
  851. arch,
  852. ),
  853. Command::Account {
  854. account_type,
  855. address,
  856. idl,
  857. } => account(&opts.cfg_override, account_type, address, idl),
  858. }
  859. }
  860. #[allow(clippy::too_many_arguments)]
  861. fn init(
  862. cfg_override: &ConfigOverride,
  863. name: String,
  864. javascript: bool,
  865. solidity: bool,
  866. no_install: bool,
  867. no_git: bool,
  868. template: ProgramTemplate,
  869. test_template: TestTemplate,
  870. force: bool,
  871. ) -> Result<()> {
  872. if !force && Config::discover(cfg_override)?.is_some() {
  873. return Err(anyhow!("Workspace already initialized"));
  874. }
  875. // We need to format different cases for the dir and the name
  876. let rust_name = name.to_snake_case();
  877. let project_name = if name == rust_name {
  878. rust_name.clone()
  879. } else {
  880. name.to_kebab_case()
  881. };
  882. // Additional keywords that have not been added to the `syn` crate as reserved words
  883. // https://github.com/dtolnay/syn/pull/1098
  884. let extra_keywords = ["async", "await", "try"];
  885. // Anchor converts to snake case before writing the program name
  886. if syn::parse_str::<syn::Ident>(&rust_name).is_err()
  887. || extra_keywords.contains(&rust_name.as_str())
  888. {
  889. return Err(anyhow!(
  890. "Anchor workspace name must be a valid Rust identifier. It may not be a Rust reserved word, start with a digit, or include certain disallowed characters. See https://doc.rust-lang.org/reference/identifiers.html for more detail.",
  891. ));
  892. }
  893. if force {
  894. fs::create_dir_all(&project_name)?;
  895. } else {
  896. fs::create_dir(&project_name)?;
  897. }
  898. std::env::set_current_dir(&project_name)?;
  899. fs::create_dir_all("app")?;
  900. let mut cfg = Config::default();
  901. let test_script = test_template.get_test_script(javascript);
  902. cfg.scripts
  903. .insert("test".to_owned(), test_script.to_owned());
  904. let mut localnet = BTreeMap::new();
  905. let program_id = rust_template::get_or_create_program_id(&rust_name);
  906. localnet.insert(
  907. rust_name,
  908. ProgramDeployment {
  909. address: program_id,
  910. path: None,
  911. idl: None,
  912. },
  913. );
  914. cfg.programs.insert(Cluster::Localnet, localnet);
  915. let toml = cfg.to_string();
  916. fs::write("Anchor.toml", toml)?;
  917. // Initialize .gitignore file
  918. fs::write(".gitignore", rust_template::git_ignore())?;
  919. // Initialize .prettierignore file
  920. fs::write(".prettierignore", rust_template::prettier_ignore())?;
  921. // Remove the default program if `--force` is passed
  922. if force {
  923. fs::remove_dir_all(
  924. std::env::current_dir()?
  925. .join(if solidity { "solidity" } else { "programs" })
  926. .join(&project_name),
  927. )?;
  928. }
  929. // Build the program.
  930. if solidity {
  931. solidity_template::create_program(&project_name)?;
  932. } else {
  933. rust_template::create_program(&project_name, template)?;
  934. }
  935. // Build the migrations directory.
  936. fs::create_dir_all("migrations")?;
  937. let license = get_npm_init_license()?;
  938. let jest = TestTemplate::Jest == test_template;
  939. if javascript {
  940. // Build javascript config
  941. let mut package_json = File::create("package.json")?;
  942. package_json.write_all(rust_template::package_json(jest, license).as_bytes())?;
  943. let mut deploy = File::create("migrations/deploy.js")?;
  944. deploy.write_all(rust_template::deploy_script().as_bytes())?;
  945. } else {
  946. // Build typescript config
  947. let mut ts_config = File::create("tsconfig.json")?;
  948. ts_config.write_all(rust_template::ts_config(jest).as_bytes())?;
  949. let mut ts_package_json = File::create("package.json")?;
  950. ts_package_json.write_all(rust_template::ts_package_json(jest, license).as_bytes())?;
  951. let mut deploy = File::create("migrations/deploy.ts")?;
  952. deploy.write_all(rust_template::ts_deploy_script().as_bytes())?;
  953. }
  954. test_template.create_test_files(
  955. &project_name,
  956. javascript,
  957. solidity,
  958. &program_id.to_string(),
  959. )?;
  960. if !no_install {
  961. let yarn_result = install_node_modules("yarn")?;
  962. if !yarn_result.status.success() {
  963. println!("Failed yarn install will attempt to npm install");
  964. install_node_modules("npm")?;
  965. }
  966. }
  967. if !no_git {
  968. let git_result = std::process::Command::new("git")
  969. .arg("init")
  970. .stdout(Stdio::inherit())
  971. .stderr(Stdio::inherit())
  972. .output()
  973. .map_err(|e| anyhow::format_err!("git init failed: {}", e.to_string()))?;
  974. if !git_result.status.success() {
  975. eprintln!("Failed to automatically initialize a new git repository");
  976. }
  977. }
  978. println!("{project_name} initialized");
  979. Ok(())
  980. }
  981. fn install_node_modules(cmd: &str) -> Result<std::process::Output> {
  982. if cfg!(target_os = "windows") {
  983. std::process::Command::new("cmd")
  984. .arg(format!("/C {cmd} install"))
  985. .stdout(Stdio::inherit())
  986. .stderr(Stdio::inherit())
  987. .output()
  988. .map_err(|e| anyhow::format_err!("{} install failed: {}", cmd, e.to_string()))
  989. } else {
  990. std::process::Command::new(cmd)
  991. .arg("install")
  992. .stdout(Stdio::inherit())
  993. .stderr(Stdio::inherit())
  994. .output()
  995. .map_err(|e| anyhow::format_err!("{} install failed: {}", cmd, e.to_string()))
  996. }
  997. }
  998. // Creates a new program crate in the `programs/<name>` directory.
  999. fn new(
  1000. cfg_override: &ConfigOverride,
  1001. solidity: bool,
  1002. name: String,
  1003. template: ProgramTemplate,
  1004. force: bool,
  1005. ) -> Result<()> {
  1006. with_workspace(cfg_override, |cfg| {
  1007. match cfg.path().parent() {
  1008. None => {
  1009. println!("Unable to make new program");
  1010. }
  1011. Some(parent) => {
  1012. std::env::set_current_dir(parent)?;
  1013. let cluster = cfg.provider.cluster.clone();
  1014. let programs = cfg.programs.entry(cluster).or_default();
  1015. if programs.contains_key(&name) {
  1016. if !force {
  1017. return Err(anyhow!("Program already exists"));
  1018. }
  1019. // Delete all files within the program folder
  1020. fs::remove_dir_all(
  1021. std::env::current_dir()?
  1022. .join(if solidity { "solidity" } else { "programs" })
  1023. .join(&name),
  1024. )?;
  1025. }
  1026. if solidity {
  1027. solidity_template::create_program(&name)?;
  1028. } else {
  1029. rust_template::create_program(&name, template)?;
  1030. }
  1031. programs.insert(
  1032. name.clone(),
  1033. ProgramDeployment {
  1034. address: rust_template::get_or_create_program_id(&name),
  1035. path: None,
  1036. idl: None,
  1037. },
  1038. );
  1039. let toml = cfg.to_string();
  1040. fs::write("Anchor.toml", toml)?;
  1041. println!("Created new program.");
  1042. }
  1043. };
  1044. Ok(())
  1045. })
  1046. }
  1047. /// Array of (path, content) tuple.
  1048. pub type Files = Vec<(PathBuf, String)>;
  1049. /// Create files from the given (path, content) tuple array.
  1050. ///
  1051. /// # Example
  1052. ///
  1053. /// ```ignore
  1054. /// crate_files(vec![("programs/my_program/src/lib.rs".into(), "// Content".into())])?;
  1055. /// ```
  1056. pub fn create_files(files: &Files) -> Result<()> {
  1057. for (path, content) in files {
  1058. let path = Path::new(path);
  1059. if path.exists() {
  1060. continue;
  1061. }
  1062. match path.extension() {
  1063. Some(_) => {
  1064. fs::create_dir_all(path.parent().unwrap())?;
  1065. fs::write(path, content)?;
  1066. }
  1067. None => fs::create_dir_all(path)?,
  1068. }
  1069. }
  1070. Ok(())
  1071. }
  1072. /// Override or create files from the given (path, content) tuple array.
  1073. ///
  1074. /// # Example
  1075. ///
  1076. /// ```ignore
  1077. /// override_or_create_files(vec![("programs/my_program/src/lib.rs".into(), "// Content".into())])?;
  1078. /// ```
  1079. pub fn override_or_create_files(files: &Files) -> Result<()> {
  1080. for (path, content) in files {
  1081. let path = Path::new(path);
  1082. if path.exists() {
  1083. let mut f = fs::OpenOptions::new()
  1084. .write(true)
  1085. .truncate(true)
  1086. .open(path)?;
  1087. f.write_all(content.as_bytes())?;
  1088. f.flush()?;
  1089. } else {
  1090. fs::create_dir_all(path.parent().unwrap())?;
  1091. fs::write(path, content)?;
  1092. }
  1093. }
  1094. Ok(())
  1095. }
  1096. pub fn expand(
  1097. cfg_override: &ConfigOverride,
  1098. program_name: Option<String>,
  1099. cargo_args: &[String],
  1100. ) -> Result<()> {
  1101. // Change to the workspace member directory, if needed.
  1102. if let Some(program_name) = program_name.as_ref() {
  1103. cd_member(cfg_override, program_name)?;
  1104. }
  1105. let workspace_cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  1106. let cfg_parent = workspace_cfg.path().parent().expect("Invalid Anchor.toml");
  1107. let cargo = Manifest::discover()?;
  1108. let expansions_path = cfg_parent.join(".anchor/expanded-macros");
  1109. fs::create_dir_all(&expansions_path)?;
  1110. match cargo {
  1111. // No Cargo.toml found, expand entire workspace
  1112. None => expand_all(&workspace_cfg, expansions_path, cargo_args),
  1113. // Cargo.toml is at root of workspace, expand entire workspace
  1114. Some(cargo) if cargo.path().parent() == workspace_cfg.path().parent() => {
  1115. expand_all(&workspace_cfg, expansions_path, cargo_args)
  1116. }
  1117. // Reaching this arm means Cargo.toml belongs to a single package. Expand it.
  1118. Some(cargo) => expand_program(
  1119. // If we found Cargo.toml, it must be in a directory so unwrap is safe
  1120. cargo.path().parent().unwrap().to_path_buf(),
  1121. expansions_path,
  1122. cargo_args,
  1123. ),
  1124. }
  1125. }
  1126. fn expand_all(
  1127. workspace_cfg: &WithPath<Config>,
  1128. expansions_path: PathBuf,
  1129. cargo_args: &[String],
  1130. ) -> Result<()> {
  1131. let cur_dir = std::env::current_dir()?;
  1132. for p in workspace_cfg.get_rust_program_list()? {
  1133. expand_program(p, expansions_path.clone(), cargo_args)?;
  1134. }
  1135. std::env::set_current_dir(cur_dir)?;
  1136. Ok(())
  1137. }
  1138. fn expand_program(
  1139. program_path: PathBuf,
  1140. expansions_path: PathBuf,
  1141. cargo_args: &[String],
  1142. ) -> Result<()> {
  1143. let cargo = Manifest::from_path(program_path.join("Cargo.toml"))
  1144. .map_err(|_| anyhow!("Could not find Cargo.toml for program"))?;
  1145. let target_dir_arg = {
  1146. let mut target_dir_arg = OsString::from("--target-dir=");
  1147. target_dir_arg.push(expansions_path.join("expand-target"));
  1148. target_dir_arg
  1149. };
  1150. let package_name = &cargo
  1151. .package
  1152. .as_ref()
  1153. .ok_or_else(|| anyhow!("Cargo config is missing a package"))?
  1154. .name;
  1155. let program_expansions_path = expansions_path.join(package_name);
  1156. fs::create_dir_all(&program_expansions_path)?;
  1157. let exit = std::process::Command::new("cargo")
  1158. .arg("expand")
  1159. .arg(target_dir_arg)
  1160. .arg(&format!("--package={package_name}"))
  1161. .args(cargo_args)
  1162. .stderr(Stdio::inherit())
  1163. .output()
  1164. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  1165. if !exit.status.success() {
  1166. eprintln!("'anchor expand' failed. Perhaps you have not installed 'cargo-expand'? https://github.com/dtolnay/cargo-expand#installation");
  1167. std::process::exit(exit.status.code().unwrap_or(1));
  1168. }
  1169. let version = cargo.version();
  1170. let time = chrono::Utc::now().to_string().replace(' ', "_");
  1171. let file_path = program_expansions_path.join(format!("{package_name}-{version}-{time}.rs"));
  1172. fs::write(&file_path, &exit.stdout).map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  1173. println!(
  1174. "Expanded {} into file {}\n",
  1175. package_name,
  1176. file_path.to_string_lossy()
  1177. );
  1178. Ok(())
  1179. }
  1180. #[allow(clippy::too_many_arguments)]
  1181. pub fn build(
  1182. cfg_override: &ConfigOverride,
  1183. no_idl: bool,
  1184. idl: Option<String>,
  1185. idl_ts: Option<String>,
  1186. verifiable: bool,
  1187. skip_lint: bool,
  1188. program_name: Option<String>,
  1189. solana_version: Option<String>,
  1190. docker_image: Option<String>,
  1191. bootstrap: BootstrapMode,
  1192. stdout: Option<File>, // Used for the package registry server.
  1193. stderr: Option<File>, // Used for the package registry server.
  1194. env_vars: Vec<String>,
  1195. cargo_args: Vec<String>,
  1196. no_docs: bool,
  1197. arch: ProgramArch,
  1198. ) -> Result<()> {
  1199. // Change to the workspace member directory, if needed.
  1200. if let Some(program_name) = program_name.as_ref() {
  1201. cd_member(cfg_override, program_name)?;
  1202. }
  1203. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  1204. let cfg_parent = cfg.path().parent().expect("Invalid Anchor.toml");
  1205. // Require overflow checks
  1206. let workspace_cargo_toml_path = cfg_parent.join("Cargo.toml");
  1207. if workspace_cargo_toml_path.exists() {
  1208. check_overflow(workspace_cargo_toml_path)?;
  1209. }
  1210. // Check whether there is a mismatch between CLI and crate/package versions
  1211. check_anchor_version(&cfg).ok();
  1212. let idl_out = match idl {
  1213. Some(idl) => Some(PathBuf::from(idl)),
  1214. None => Some(cfg_parent.join("target/idl")),
  1215. };
  1216. fs::create_dir_all(idl_out.as_ref().unwrap())?;
  1217. let idl_ts_out = match idl_ts {
  1218. Some(idl_ts) => Some(PathBuf::from(idl_ts)),
  1219. None => Some(cfg_parent.join("target/types")),
  1220. };
  1221. fs::create_dir_all(idl_ts_out.as_ref().unwrap())?;
  1222. if !cfg.workspace.types.is_empty() {
  1223. fs::create_dir_all(cfg_parent.join(&cfg.workspace.types))?;
  1224. };
  1225. let cargo = Manifest::discover()?;
  1226. let build_config = BuildConfig {
  1227. verifiable,
  1228. solana_version: solana_version.or_else(|| cfg.toolchain.solana_version.clone()),
  1229. docker_image: docker_image.unwrap_or_else(|| cfg.docker()),
  1230. bootstrap,
  1231. };
  1232. match cargo {
  1233. // No Cargo.toml so build the entire workspace.
  1234. None => build_all(
  1235. &cfg,
  1236. cfg.path(),
  1237. no_idl,
  1238. idl_out,
  1239. idl_ts_out,
  1240. &build_config,
  1241. stdout,
  1242. stderr,
  1243. env_vars,
  1244. cargo_args,
  1245. skip_lint,
  1246. no_docs,
  1247. arch,
  1248. )?,
  1249. // If the Cargo.toml is at the root, build the entire workspace.
  1250. Some(cargo) if cargo.path().parent() == cfg.path().parent() => build_all(
  1251. &cfg,
  1252. cfg.path(),
  1253. no_idl,
  1254. idl_out,
  1255. idl_ts_out,
  1256. &build_config,
  1257. stdout,
  1258. stderr,
  1259. env_vars,
  1260. cargo_args,
  1261. skip_lint,
  1262. no_docs,
  1263. arch,
  1264. )?,
  1265. // Cargo.toml represents a single package. Build it.
  1266. Some(cargo) => build_rust_cwd(
  1267. &cfg,
  1268. cargo.path().to_path_buf(),
  1269. no_idl,
  1270. idl_out,
  1271. idl_ts_out,
  1272. &build_config,
  1273. stdout,
  1274. stderr,
  1275. env_vars,
  1276. cargo_args,
  1277. skip_lint,
  1278. no_docs,
  1279. &arch,
  1280. )?,
  1281. }
  1282. set_workspace_dir_or_exit();
  1283. Ok(())
  1284. }
  1285. #[allow(clippy::too_many_arguments)]
  1286. fn build_all(
  1287. cfg: &WithPath<Config>,
  1288. cfg_path: &Path,
  1289. no_idl: bool,
  1290. idl_out: Option<PathBuf>,
  1291. idl_ts_out: Option<PathBuf>,
  1292. build_config: &BuildConfig,
  1293. stdout: Option<File>, // Used for the package registry server.
  1294. stderr: Option<File>, // Used for the package registry server.
  1295. env_vars: Vec<String>,
  1296. cargo_args: Vec<String>,
  1297. skip_lint: bool,
  1298. no_docs: bool,
  1299. arch: ProgramArch,
  1300. ) -> Result<()> {
  1301. let cur_dir = std::env::current_dir()?;
  1302. let r = match cfg_path.parent() {
  1303. None => Err(anyhow!("Invalid Anchor.toml at {}", cfg_path.display())),
  1304. Some(_parent) => {
  1305. for p in cfg.get_rust_program_list()? {
  1306. build_rust_cwd(
  1307. cfg,
  1308. p.join("Cargo.toml"),
  1309. no_idl,
  1310. idl_out.clone(),
  1311. idl_ts_out.clone(),
  1312. build_config,
  1313. stdout.as_ref().map(|f| f.try_clone()).transpose()?,
  1314. stderr.as_ref().map(|f| f.try_clone()).transpose()?,
  1315. env_vars.clone(),
  1316. cargo_args.clone(),
  1317. skip_lint,
  1318. no_docs,
  1319. &arch,
  1320. )?;
  1321. }
  1322. for (name, path) in cfg.get_solidity_program_list()? {
  1323. build_solidity_cwd(
  1324. cfg,
  1325. name,
  1326. path,
  1327. idl_out.clone(),
  1328. idl_ts_out.clone(),
  1329. build_config,
  1330. stdout.as_ref().map(|f| f.try_clone()).transpose()?,
  1331. stderr.as_ref().map(|f| f.try_clone()).transpose()?,
  1332. cargo_args.clone(),
  1333. )?;
  1334. }
  1335. Ok(())
  1336. }
  1337. };
  1338. std::env::set_current_dir(cur_dir)?;
  1339. r
  1340. }
  1341. // Runs the build command outside of a workspace.
  1342. #[allow(clippy::too_many_arguments)]
  1343. fn build_rust_cwd(
  1344. cfg: &WithPath<Config>,
  1345. cargo_toml: PathBuf,
  1346. no_idl: bool,
  1347. idl_out: Option<PathBuf>,
  1348. idl_ts_out: Option<PathBuf>,
  1349. build_config: &BuildConfig,
  1350. stdout: Option<File>,
  1351. stderr: Option<File>,
  1352. env_vars: Vec<String>,
  1353. cargo_args: Vec<String>,
  1354. skip_lint: bool,
  1355. no_docs: bool,
  1356. arch: &ProgramArch,
  1357. ) -> Result<()> {
  1358. match cargo_toml.parent() {
  1359. None => return Err(anyhow!("Unable to find parent")),
  1360. Some(p) => std::env::set_current_dir(p)?,
  1361. };
  1362. match build_config.verifiable {
  1363. false => _build_rust_cwd(
  1364. cfg, no_idl, idl_out, idl_ts_out, skip_lint, no_docs, arch, cargo_args,
  1365. ),
  1366. true => build_cwd_verifiable(
  1367. cfg,
  1368. cargo_toml,
  1369. build_config,
  1370. stdout,
  1371. stderr,
  1372. skip_lint,
  1373. env_vars,
  1374. cargo_args,
  1375. no_docs,
  1376. arch,
  1377. ),
  1378. }
  1379. }
  1380. // Runs the build command outside of a workspace.
  1381. #[allow(clippy::too_many_arguments)]
  1382. fn build_solidity_cwd(
  1383. cfg: &WithPath<Config>,
  1384. name: String,
  1385. path: PathBuf,
  1386. idl_out: Option<PathBuf>,
  1387. idl_ts_out: Option<PathBuf>,
  1388. build_config: &BuildConfig,
  1389. stdout: Option<File>,
  1390. stderr: Option<File>,
  1391. cargo_args: Vec<String>,
  1392. ) -> Result<()> {
  1393. match path.parent() {
  1394. None => return Err(anyhow!("Unable to find parent")),
  1395. Some(p) => std::env::set_current_dir(p)?,
  1396. };
  1397. match build_config.verifiable {
  1398. false => _build_solidity_cwd(
  1399. cfg, &name, &path, idl_out, idl_ts_out, stdout, stderr, cargo_args,
  1400. ),
  1401. true => panic!("verifiable solidity not supported"),
  1402. }
  1403. }
  1404. // Builds an anchor program in a docker image and copies the build artifacts
  1405. // into the `target/` directory.
  1406. #[allow(clippy::too_many_arguments)]
  1407. fn build_cwd_verifiable(
  1408. cfg: &WithPath<Config>,
  1409. cargo_toml: PathBuf,
  1410. build_config: &BuildConfig,
  1411. stdout: Option<File>,
  1412. stderr: Option<File>,
  1413. skip_lint: bool,
  1414. env_vars: Vec<String>,
  1415. cargo_args: Vec<String>,
  1416. no_docs: bool,
  1417. arch: &ProgramArch,
  1418. ) -> Result<()> {
  1419. // Create output dirs.
  1420. let workspace_dir = cfg.path().parent().unwrap().canonicalize()?;
  1421. fs::create_dir_all(workspace_dir.join("target/verifiable"))?;
  1422. fs::create_dir_all(workspace_dir.join("target/idl"))?;
  1423. fs::create_dir_all(workspace_dir.join("target/types"))?;
  1424. if !&cfg.workspace.types.is_empty() {
  1425. fs::create_dir_all(workspace_dir.join(&cfg.workspace.types))?;
  1426. }
  1427. let container_name = "anchor-program";
  1428. // Build the binary in docker.
  1429. let result = docker_build(
  1430. cfg,
  1431. container_name,
  1432. cargo_toml,
  1433. build_config,
  1434. stdout,
  1435. stderr,
  1436. env_vars,
  1437. cargo_args.clone(),
  1438. arch,
  1439. );
  1440. match &result {
  1441. Err(e) => {
  1442. eprintln!("Error during Docker build: {e:?}");
  1443. }
  1444. Ok(_) => {
  1445. // Build the idl.
  1446. println!("Extracting the IDL");
  1447. let idl = generate_idl(cfg, skip_lint, no_docs, &cargo_args)?;
  1448. // Write out the JSON file.
  1449. println!("Writing the IDL file");
  1450. let out_file = workspace_dir.join(format!("target/idl/{}.json", idl.metadata.name));
  1451. write_idl(&idl, OutFile::File(out_file))?;
  1452. // Write out the TypeScript type.
  1453. println!("Writing the .ts file");
  1454. let ts_file = workspace_dir.join(format!("target/types/{}.ts", idl.metadata.name));
  1455. fs::write(&ts_file, idl_ts(&idl)?)?;
  1456. // Copy out the TypeScript type.
  1457. if !&cfg.workspace.types.is_empty() {
  1458. fs::copy(
  1459. ts_file,
  1460. workspace_dir
  1461. .join(&cfg.workspace.types)
  1462. .join(idl.metadata.name)
  1463. .with_extension("ts"),
  1464. )?;
  1465. }
  1466. println!("Build success");
  1467. }
  1468. }
  1469. result
  1470. }
  1471. #[allow(clippy::too_many_arguments)]
  1472. fn docker_build(
  1473. cfg: &WithPath<Config>,
  1474. container_name: &str,
  1475. cargo_toml: PathBuf,
  1476. build_config: &BuildConfig,
  1477. stdout: Option<File>,
  1478. stderr: Option<File>,
  1479. env_vars: Vec<String>,
  1480. cargo_args: Vec<String>,
  1481. arch: &ProgramArch,
  1482. ) -> Result<()> {
  1483. let binary_name = Manifest::from_path(&cargo_toml)?.lib_name()?;
  1484. // Docker vars.
  1485. let workdir = Path::new("/workdir");
  1486. let volume_mount = format!(
  1487. "{}:{}",
  1488. cfg.path().parent().unwrap().canonicalize()?.display(),
  1489. workdir.to_str().unwrap(),
  1490. );
  1491. println!("Using image {:?}", build_config.docker_image);
  1492. // Start the docker image running detached in the background.
  1493. let target_dir = workdir.join("docker-target");
  1494. println!("Run docker image");
  1495. let exit = std::process::Command::new("docker")
  1496. .args([
  1497. "run",
  1498. "-it",
  1499. "-d",
  1500. "--name",
  1501. container_name,
  1502. "--env",
  1503. &format!(
  1504. "CARGO_TARGET_DIR={}",
  1505. target_dir.as_path().to_str().unwrap()
  1506. ),
  1507. "-v",
  1508. &volume_mount,
  1509. "-w",
  1510. workdir.to_str().unwrap(),
  1511. &build_config.docker_image,
  1512. "bash",
  1513. ])
  1514. .stdout(Stdio::inherit())
  1515. .stderr(Stdio::inherit())
  1516. .output()
  1517. .map_err(|e| anyhow::format_err!("Docker build failed: {}", e.to_string()))?;
  1518. if !exit.status.success() {
  1519. return Err(anyhow!("Failed to build program"));
  1520. }
  1521. let result = docker_prep(container_name, build_config).and_then(|_| {
  1522. let cfg_parent = cfg.path().parent().unwrap();
  1523. docker_build_bpf(
  1524. container_name,
  1525. cargo_toml.as_path(),
  1526. cfg_parent,
  1527. target_dir.as_path(),
  1528. binary_name,
  1529. stdout,
  1530. stderr,
  1531. env_vars,
  1532. cargo_args,
  1533. arch,
  1534. )
  1535. });
  1536. // Cleanup regardless of errors
  1537. docker_cleanup(container_name, target_dir.as_path())?;
  1538. // Done.
  1539. result
  1540. }
  1541. fn docker_prep(container_name: &str, build_config: &BuildConfig) -> Result<()> {
  1542. // Set the solana version in the container, if given. Otherwise use the
  1543. // default.
  1544. match build_config.bootstrap {
  1545. BootstrapMode::Debian => {
  1546. // Install build requirements
  1547. docker_exec(container_name, &["apt", "update"])?;
  1548. docker_exec(
  1549. container_name,
  1550. &["apt", "install", "-y", "curl", "build-essential"],
  1551. )?;
  1552. // Install Rust
  1553. docker_exec(
  1554. container_name,
  1555. &["curl", "https://sh.rustup.rs", "-sfo", "rustup.sh"],
  1556. )?;
  1557. docker_exec(container_name, &["sh", "rustup.sh", "-y"])?;
  1558. docker_exec(container_name, &["rm", "-f", "rustup.sh"])?;
  1559. }
  1560. BootstrapMode::None => {}
  1561. }
  1562. if let Some(solana_version) = &build_config.solana_version {
  1563. println!("Using solana version: {solana_version}");
  1564. // Install Solana CLI
  1565. docker_exec(
  1566. container_name,
  1567. &[
  1568. "curl",
  1569. "-sSfL",
  1570. &format!("https://release.solana.com/v{solana_version}/install",),
  1571. "-o",
  1572. "solana_installer.sh",
  1573. ],
  1574. )?;
  1575. docker_exec(container_name, &["sh", "solana_installer.sh"])?;
  1576. docker_exec(container_name, &["rm", "-f", "solana_installer.sh"])?;
  1577. }
  1578. Ok(())
  1579. }
  1580. #[allow(clippy::too_many_arguments)]
  1581. fn docker_build_bpf(
  1582. container_name: &str,
  1583. cargo_toml: &Path,
  1584. cfg_parent: &Path,
  1585. target_dir: &Path,
  1586. binary_name: String,
  1587. stdout: Option<File>,
  1588. stderr: Option<File>,
  1589. env_vars: Vec<String>,
  1590. cargo_args: Vec<String>,
  1591. arch: &ProgramArch,
  1592. ) -> Result<()> {
  1593. let manifest_path =
  1594. pathdiff::diff_paths(cargo_toml.canonicalize()?, cfg_parent.canonicalize()?)
  1595. .ok_or_else(|| anyhow!("Unable to diff paths"))?;
  1596. println!(
  1597. "Building {} manifest: {:?}",
  1598. binary_name,
  1599. manifest_path.display()
  1600. );
  1601. let subcommand = arch.build_subcommand();
  1602. // Execute the build.
  1603. let exit = std::process::Command::new("docker")
  1604. .args([
  1605. "exec",
  1606. "--env",
  1607. "PATH=/root/.local/share/solana/install/active_release/bin:/root/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  1608. ])
  1609. .args(env_vars
  1610. .iter()
  1611. .map(|x| ["--env", x.as_str()])
  1612. .collect::<Vec<[&str; 2]>>()
  1613. .concat())
  1614. .args([
  1615. container_name,
  1616. "cargo",
  1617. subcommand,
  1618. "--manifest-path",
  1619. &manifest_path.display().to_string(),
  1620. ])
  1621. .args(cargo_args)
  1622. .stdout(match stdout {
  1623. None => Stdio::inherit(),
  1624. Some(f) => f.into(),
  1625. })
  1626. .stderr(match stderr {
  1627. None => Stdio::inherit(),
  1628. Some(f) => f.into(),
  1629. })
  1630. .output()
  1631. .map_err(|e| anyhow::format_err!("Docker build failed: {}", e.to_string()))?;
  1632. if !exit.status.success() {
  1633. return Err(anyhow!("Failed to build program"));
  1634. }
  1635. // Copy the binary out of the docker image.
  1636. println!("Copying out the build artifacts");
  1637. let out_file = cfg_parent
  1638. .canonicalize()?
  1639. .join(format!("target/verifiable/{binary_name}.so"))
  1640. .display()
  1641. .to_string();
  1642. // This requires the target directory of any built program to be located at
  1643. // the root of the workspace.
  1644. let mut bin_path = target_dir.join("deploy");
  1645. bin_path.push(format!("{binary_name}.so"));
  1646. let bin_artifact = format!(
  1647. "{}:{}",
  1648. container_name,
  1649. bin_path.as_path().to_str().unwrap()
  1650. );
  1651. let exit = std::process::Command::new("docker")
  1652. .args(["cp", &bin_artifact, &out_file])
  1653. .stdout(Stdio::inherit())
  1654. .stderr(Stdio::inherit())
  1655. .output()
  1656. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  1657. if !exit.status.success() {
  1658. Err(anyhow!(
  1659. "Failed to copy binary out of docker. Is the target directory set correctly?"
  1660. ))
  1661. } else {
  1662. Ok(())
  1663. }
  1664. }
  1665. fn docker_cleanup(container_name: &str, target_dir: &Path) -> Result<()> {
  1666. // Wipe the generated docker-target dir.
  1667. println!("Cleaning up the docker target directory");
  1668. docker_exec(container_name, &["rm", "-rf", target_dir.to_str().unwrap()])?;
  1669. // Remove the docker image.
  1670. println!("Removing the docker container");
  1671. let exit = std::process::Command::new("docker")
  1672. .args(["rm", "-f", container_name])
  1673. .stdout(Stdio::inherit())
  1674. .stderr(Stdio::inherit())
  1675. .output()
  1676. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  1677. if !exit.status.success() {
  1678. println!("Unable to remove the docker container");
  1679. std::process::exit(exit.status.code().unwrap_or(1));
  1680. }
  1681. Ok(())
  1682. }
  1683. fn docker_exec(container_name: &str, args: &[&str]) -> Result<()> {
  1684. let exit = std::process::Command::new("docker")
  1685. .args([&["exec", container_name], args].concat())
  1686. .stdout(Stdio::inherit())
  1687. .stderr(Stdio::inherit())
  1688. .output()
  1689. .map_err(|e| anyhow!("Failed to run command \"{:?}\": {:?}", args, e))?;
  1690. if !exit.status.success() {
  1691. Err(anyhow!("Failed to run command: {:?}", args))
  1692. } else {
  1693. Ok(())
  1694. }
  1695. }
  1696. #[allow(clippy::too_many_arguments)]
  1697. fn _build_rust_cwd(
  1698. cfg: &WithPath<Config>,
  1699. no_idl: bool,
  1700. idl_out: Option<PathBuf>,
  1701. idl_ts_out: Option<PathBuf>,
  1702. skip_lint: bool,
  1703. no_docs: bool,
  1704. arch: &ProgramArch,
  1705. cargo_args: Vec<String>,
  1706. ) -> Result<()> {
  1707. let exit = std::process::Command::new("cargo")
  1708. .arg(arch.build_subcommand())
  1709. .args(cargo_args.clone())
  1710. .stdout(Stdio::inherit())
  1711. .stderr(Stdio::inherit())
  1712. .output()
  1713. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  1714. if !exit.status.success() {
  1715. std::process::exit(exit.status.code().unwrap_or(1));
  1716. }
  1717. // Generate IDL
  1718. if !no_idl {
  1719. let idl = generate_idl(cfg, skip_lint, no_docs, &cargo_args)?;
  1720. // JSON out path.
  1721. let out = match idl_out {
  1722. None => PathBuf::from(".")
  1723. .join(&idl.metadata.name)
  1724. .with_extension("json"),
  1725. Some(o) => PathBuf::from(&o.join(&idl.metadata.name).with_extension("json")),
  1726. };
  1727. // TS out path.
  1728. let ts_out = match idl_ts_out {
  1729. None => PathBuf::from(".")
  1730. .join(&idl.metadata.name)
  1731. .with_extension("ts"),
  1732. Some(o) => PathBuf::from(&o.join(&idl.metadata.name).with_extension("ts")),
  1733. };
  1734. // Write out the JSON file.
  1735. write_idl(&idl, OutFile::File(out))?;
  1736. // Write out the TypeScript type.
  1737. fs::write(&ts_out, idl_ts(&idl)?)?;
  1738. // Copy out the TypeScript type.
  1739. let cfg_parent = cfg.path().parent().expect("Invalid Anchor.toml");
  1740. if !&cfg.workspace.types.is_empty() {
  1741. fs::copy(
  1742. &ts_out,
  1743. cfg_parent
  1744. .join(&cfg.workspace.types)
  1745. .join(&idl.metadata.name)
  1746. .with_extension("ts"),
  1747. )?;
  1748. }
  1749. }
  1750. Ok(())
  1751. }
  1752. #[allow(clippy::too_many_arguments)]
  1753. fn _build_solidity_cwd(
  1754. cfg: &WithPath<Config>,
  1755. name: &str,
  1756. path: &Path,
  1757. idl_out: Option<PathBuf>,
  1758. idl_ts_out: Option<PathBuf>,
  1759. stdout: Option<File>,
  1760. stderr: Option<File>,
  1761. solang_args: Vec<String>,
  1762. ) -> Result<()> {
  1763. let mut cmd = std::process::Command::new("solang");
  1764. let cmd = cmd.args(["compile", "--target", "solana", "--contract", name]);
  1765. if let Some(idl_out) = &idl_out {
  1766. cmd.arg("--output-meta");
  1767. cmd.arg(idl_out);
  1768. }
  1769. let target_bin = cfg.path().parent().unwrap().join("target").join("deploy");
  1770. cmd.arg("--output");
  1771. cmd.arg(target_bin);
  1772. cmd.arg("--verbose");
  1773. cmd.arg(path);
  1774. let exit = cmd
  1775. .args(solang_args)
  1776. .stdout(match stdout {
  1777. None => Stdio::inherit(),
  1778. Some(f) => f.into(),
  1779. })
  1780. .stderr(match stderr {
  1781. None => Stdio::inherit(),
  1782. Some(f) => f.into(),
  1783. })
  1784. .output()
  1785. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  1786. if !exit.status.success() {
  1787. std::process::exit(exit.status.code().unwrap_or(1));
  1788. }
  1789. // idl is written to idl_out or .
  1790. let idl_path = idl_out
  1791. .unwrap_or(PathBuf::from("."))
  1792. .join(format!("{}.json", name));
  1793. let idl = fs::read_to_string(idl_path)?;
  1794. let idl: Idl = serde_json::from_str(&idl)?;
  1795. // TS out path.
  1796. let ts_out = match idl_ts_out {
  1797. None => PathBuf::from(".")
  1798. .join(&idl.metadata.name)
  1799. .with_extension("ts"),
  1800. Some(o) => PathBuf::from(&o.join(&idl.metadata.name).with_extension("ts")),
  1801. };
  1802. // Write out the TypeScript type.
  1803. fs::write(&ts_out, idl_ts(&idl)?)?;
  1804. // Copy out the TypeScript type.
  1805. let cfg_parent = cfg.path().parent().expect("Invalid Anchor.toml");
  1806. if !&cfg.workspace.types.is_empty() {
  1807. fs::copy(
  1808. &ts_out,
  1809. cfg_parent
  1810. .join(&cfg.workspace.types)
  1811. .join(&idl.metadata.name)
  1812. .with_extension("ts"),
  1813. )?;
  1814. }
  1815. Ok(())
  1816. }
  1817. #[allow(clippy::too_many_arguments)]
  1818. fn verify(
  1819. cfg_override: &ConfigOverride,
  1820. program_id: Pubkey,
  1821. program_name: Option<String>,
  1822. solana_version: Option<String>,
  1823. docker_image: Option<String>,
  1824. bootstrap: BootstrapMode,
  1825. env_vars: Vec<String>,
  1826. cargo_args: Vec<String>,
  1827. skip_build: bool,
  1828. arch: ProgramArch,
  1829. ) -> Result<()> {
  1830. // Change to the workspace member directory, if needed.
  1831. if let Some(program_name) = program_name.as_ref() {
  1832. cd_member(cfg_override, program_name)?;
  1833. }
  1834. // Proceed with the command.
  1835. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  1836. let cargo = Manifest::discover()?.ok_or_else(|| anyhow!("Cargo.toml not found"))?;
  1837. // Build the program we want to verify.
  1838. let cur_dir = std::env::current_dir()?;
  1839. if !skip_build {
  1840. build(
  1841. cfg_override,
  1842. false,
  1843. None,
  1844. None,
  1845. true,
  1846. true,
  1847. None,
  1848. solana_version.or_else(|| cfg.toolchain.solana_version.clone()),
  1849. docker_image,
  1850. bootstrap,
  1851. None,
  1852. None,
  1853. env_vars,
  1854. cargo_args.clone(),
  1855. false,
  1856. arch,
  1857. )?;
  1858. }
  1859. std::env::set_current_dir(cur_dir)?;
  1860. // Verify binary.
  1861. let binary_name = cargo.lib_name()?;
  1862. let bin_path = cfg
  1863. .path()
  1864. .parent()
  1865. .ok_or_else(|| anyhow!("Unable to find workspace root"))?
  1866. .join("target/verifiable/")
  1867. .join(format!("{binary_name}.so"));
  1868. let url = cluster_url(&cfg, &cfg.test_validator);
  1869. let bin_ver = verify_bin(program_id, &bin_path, &url)?;
  1870. if !bin_ver.is_verified {
  1871. println!("Error: Binaries don't match");
  1872. std::process::exit(1);
  1873. }
  1874. // Verify IDL (only if it's not a buffer account).
  1875. let local_idl = generate_idl(&cfg, true, false, &cargo_args)?;
  1876. if bin_ver.state != BinVerificationState::Buffer {
  1877. let deployed_idl = fetch_idl(cfg_override, program_id)?;
  1878. if local_idl != deployed_idl {
  1879. println!("Error: IDLs don't match");
  1880. std::process::exit(1);
  1881. }
  1882. }
  1883. println!("{program_id} is verified.");
  1884. Ok(())
  1885. }
  1886. fn cd_member(cfg_override: &ConfigOverride, program_name: &str) -> Result<()> {
  1887. // Change directories to the given `program_name`, if given.
  1888. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  1889. for program in cfg.read_all_programs()? {
  1890. if program.solidity {
  1891. if let Some(path) = program.path.parent() {
  1892. std::env::set_current_dir(path)?;
  1893. return Ok(());
  1894. }
  1895. } else {
  1896. let cargo_toml = program.path.join("Cargo.toml");
  1897. if !cargo_toml.exists() {
  1898. return Err(anyhow!(
  1899. "Did not find Cargo.toml at the path: {}",
  1900. program.path.display()
  1901. ));
  1902. }
  1903. let manifest = Manifest::from_path(&cargo_toml)?;
  1904. let pkg_name = manifest.package().name();
  1905. let lib_name = manifest.lib_name()?;
  1906. if program_name == pkg_name || program_name == lib_name {
  1907. std::env::set_current_dir(&program.path)?;
  1908. return Ok(());
  1909. }
  1910. }
  1911. }
  1912. Err(anyhow!("{} is not part of the workspace", program_name,))
  1913. }
  1914. pub fn verify_bin(program_id: Pubkey, bin_path: &Path, cluster: &str) -> Result<BinVerification> {
  1915. // Use `finalized` state for verify
  1916. let client = RpcClient::new_with_commitment(cluster, CommitmentConfig::finalized());
  1917. // Get the deployed build artifacts.
  1918. let (deployed_bin, state) = {
  1919. let account = client.get_account(&program_id)?;
  1920. if account.owner == bpf_loader::id() || account.owner == bpf_loader_deprecated::id() {
  1921. let bin = account.data.to_vec();
  1922. let state = BinVerificationState::ProgramData {
  1923. slot: 0, // Need to look through the transaction history.
  1924. upgrade_authority_address: None,
  1925. };
  1926. (bin, state)
  1927. } else if account.owner == bpf_loader_upgradeable::id() {
  1928. match account.state()? {
  1929. UpgradeableLoaderState::Program {
  1930. programdata_address,
  1931. } => {
  1932. let account = client.get_account(&programdata_address)?;
  1933. let bin = account.data
  1934. [UpgradeableLoaderState::size_of_programdata_metadata()..]
  1935. .to_vec();
  1936. if let UpgradeableLoaderState::ProgramData {
  1937. slot,
  1938. upgrade_authority_address,
  1939. } = account.state()?
  1940. {
  1941. let state = BinVerificationState::ProgramData {
  1942. slot,
  1943. upgrade_authority_address,
  1944. };
  1945. (bin, state)
  1946. } else {
  1947. return Err(anyhow!("Expected program data"));
  1948. }
  1949. }
  1950. UpgradeableLoaderState::Buffer { .. } => {
  1951. let offset = UpgradeableLoaderState::size_of_buffer_metadata();
  1952. (
  1953. account.data[offset..].to_vec(),
  1954. BinVerificationState::Buffer,
  1955. )
  1956. }
  1957. _ => {
  1958. return Err(anyhow!(
  1959. "Invalid program id, not a buffer or program account"
  1960. ))
  1961. }
  1962. }
  1963. } else {
  1964. return Err(anyhow!(
  1965. "Invalid program id, not owned by any loader program"
  1966. ));
  1967. }
  1968. };
  1969. let mut local_bin = {
  1970. let mut f = File::open(bin_path)?;
  1971. let mut contents = vec![];
  1972. f.read_to_end(&mut contents)?;
  1973. contents
  1974. };
  1975. // The deployed program probably has zero bytes appended. The default is
  1976. // 2x the binary size in case of an upgrade.
  1977. if local_bin.len() < deployed_bin.len() {
  1978. local_bin.append(&mut vec![0; deployed_bin.len() - local_bin.len()]);
  1979. }
  1980. // Finally, check the bytes.
  1981. let is_verified = local_bin == deployed_bin;
  1982. Ok(BinVerification { state, is_verified })
  1983. }
  1984. #[derive(PartialEq, Eq)]
  1985. pub struct BinVerification {
  1986. pub state: BinVerificationState,
  1987. pub is_verified: bool,
  1988. }
  1989. #[derive(PartialEq, Eq)]
  1990. pub enum BinVerificationState {
  1991. Buffer,
  1992. ProgramData {
  1993. slot: u64,
  1994. upgrade_authority_address: Option<Pubkey>,
  1995. },
  1996. }
  1997. fn idl(cfg_override: &ConfigOverride, subcmd: IdlCommand) -> Result<()> {
  1998. match subcmd {
  1999. IdlCommand::Init {
  2000. program_id,
  2001. filepath,
  2002. priority_fee,
  2003. } => idl_init(cfg_override, program_id, filepath, priority_fee),
  2004. IdlCommand::Close {
  2005. program_id,
  2006. idl_address,
  2007. print_only,
  2008. priority_fee,
  2009. } => {
  2010. let closed_address = idl_close(
  2011. cfg_override,
  2012. program_id,
  2013. idl_address,
  2014. print_only,
  2015. priority_fee,
  2016. )?;
  2017. if !print_only {
  2018. println!("Idl account closed: {closed_address}");
  2019. }
  2020. Ok(())
  2021. }
  2022. IdlCommand::WriteBuffer {
  2023. program_id,
  2024. filepath,
  2025. priority_fee,
  2026. } => {
  2027. let idl_buffer = idl_write_buffer(cfg_override, program_id, filepath, priority_fee)?;
  2028. println!("Idl buffer created: {idl_buffer}");
  2029. Ok(())
  2030. }
  2031. IdlCommand::SetBuffer {
  2032. program_id,
  2033. buffer,
  2034. print_only,
  2035. priority_fee,
  2036. } => idl_set_buffer(cfg_override, program_id, buffer, print_only, priority_fee).map(|_| ()),
  2037. IdlCommand::Upgrade {
  2038. program_id,
  2039. filepath,
  2040. priority_fee,
  2041. } => idl_upgrade(cfg_override, program_id, filepath, priority_fee),
  2042. IdlCommand::SetAuthority {
  2043. program_id,
  2044. address,
  2045. new_authority,
  2046. print_only,
  2047. priority_fee,
  2048. } => idl_set_authority(
  2049. cfg_override,
  2050. program_id,
  2051. address,
  2052. new_authority,
  2053. print_only,
  2054. priority_fee,
  2055. ),
  2056. IdlCommand::EraseAuthority {
  2057. program_id,
  2058. priority_fee,
  2059. } => idl_erase_authority(cfg_override, program_id, priority_fee),
  2060. IdlCommand::Authority { program_id } => idl_authority(cfg_override, program_id),
  2061. IdlCommand::Build {
  2062. program_name,
  2063. out,
  2064. out_ts,
  2065. no_docs,
  2066. skip_lint,
  2067. cargo_args,
  2068. } => idl_build(
  2069. cfg_override,
  2070. program_name,
  2071. out,
  2072. out_ts,
  2073. no_docs,
  2074. skip_lint,
  2075. cargo_args,
  2076. ),
  2077. IdlCommand::Fetch { address, out } => idl_fetch(cfg_override, address, out),
  2078. IdlCommand::Convert { path, out } => idl_convert(path, out),
  2079. IdlCommand::Type { path, out } => idl_type(path, out),
  2080. }
  2081. }
  2082. /// Fetch an IDL for the given program id.
  2083. fn fetch_idl(cfg_override: &ConfigOverride, idl_addr: Pubkey) -> Result<Idl> {
  2084. let url = match Config::discover(cfg_override)? {
  2085. Some(cfg) => cluster_url(&cfg, &cfg.test_validator),
  2086. None => {
  2087. // If the command is not run inside a workspace,
  2088. // cluster_url will be used from default solana config
  2089. // provider.cluster option can be used to override this
  2090. if let Some(cluster) = cfg_override.cluster.clone() {
  2091. cluster.url().to_string()
  2092. } else {
  2093. config::get_solana_cfg_url()?
  2094. }
  2095. }
  2096. };
  2097. let client = create_client(url);
  2098. let mut account = client.get_account(&idl_addr)?;
  2099. if account.executable {
  2100. let idl_addr = IdlAccount::address(&idl_addr);
  2101. account = client.get_account(&idl_addr)?;
  2102. }
  2103. // Cut off account discriminator.
  2104. let mut d: &[u8] = &account.data[IdlAccount::DISCRIMINATOR.len()..];
  2105. let idl_account: IdlAccount = AnchorDeserialize::deserialize(&mut d)?;
  2106. let compressed_len: usize = idl_account.data_len.try_into().unwrap();
  2107. let compressed_bytes = &account.data[44..44 + compressed_len];
  2108. let mut z = ZlibDecoder::new(compressed_bytes);
  2109. let mut s = Vec::new();
  2110. z.read_to_end(&mut s)?;
  2111. serde_json::from_slice(&s[..]).map_err(Into::into)
  2112. }
  2113. fn get_idl_account(client: &RpcClient, idl_address: &Pubkey) -> Result<IdlAccount> {
  2114. let account = client.get_account(idl_address)?;
  2115. let mut data: &[u8] = &account.data;
  2116. AccountDeserialize::try_deserialize(&mut data).map_err(|e| anyhow!("{:?}", e))
  2117. }
  2118. fn idl_init(
  2119. cfg_override: &ConfigOverride,
  2120. program_id: Pubkey,
  2121. idl_filepath: String,
  2122. priority_fee: Option<u64>,
  2123. ) -> Result<()> {
  2124. with_workspace(cfg_override, |cfg| {
  2125. let keypair = cfg.provider.wallet.to_string();
  2126. let bytes = fs::read(idl_filepath)?;
  2127. let idl: Idl = serde_json::from_reader(&*bytes)?;
  2128. let idl_address = create_idl_account(cfg, &keypair, &program_id, &idl, priority_fee)?;
  2129. println!("Idl account created: {idl_address:?}");
  2130. Ok(())
  2131. })
  2132. }
  2133. fn idl_close(
  2134. cfg_override: &ConfigOverride,
  2135. program_id: Pubkey,
  2136. idl_address: Option<Pubkey>,
  2137. print_only: bool,
  2138. priority_fee: Option<u64>,
  2139. ) -> Result<Pubkey> {
  2140. with_workspace(cfg_override, |cfg| {
  2141. let idl_address = idl_address.unwrap_or_else(|| IdlAccount::address(&program_id));
  2142. idl_close_account(cfg, &program_id, idl_address, print_only, priority_fee)?;
  2143. Ok(idl_address)
  2144. })
  2145. }
  2146. fn idl_write_buffer(
  2147. cfg_override: &ConfigOverride,
  2148. program_id: Pubkey,
  2149. idl_filepath: String,
  2150. priority_fee: Option<u64>,
  2151. ) -> Result<Pubkey> {
  2152. with_workspace(cfg_override, |cfg| {
  2153. let keypair = cfg.provider.wallet.to_string();
  2154. let bytes = fs::read(idl_filepath)?;
  2155. let idl: Idl = serde_json::from_reader(&*bytes)?;
  2156. let idl_buffer = create_idl_buffer(cfg, &keypair, &program_id, &idl, priority_fee)?;
  2157. idl_write(cfg, &program_id, &idl, idl_buffer, priority_fee)?;
  2158. Ok(idl_buffer)
  2159. })
  2160. }
  2161. fn idl_set_buffer(
  2162. cfg_override: &ConfigOverride,
  2163. program_id: Pubkey,
  2164. buffer: Pubkey,
  2165. print_only: bool,
  2166. priority_fee: Option<u64>,
  2167. ) -> Result<Pubkey> {
  2168. with_workspace(cfg_override, |cfg| {
  2169. let keypair = get_keypair(&cfg.provider.wallet.to_string())?;
  2170. let url = cluster_url(cfg, &cfg.test_validator);
  2171. let client = create_client(url);
  2172. let idl_address = IdlAccount::address(&program_id);
  2173. let idl_authority = if print_only {
  2174. get_idl_account(&client, &idl_address)?.authority
  2175. } else {
  2176. keypair.pubkey()
  2177. };
  2178. // Instruction to set the buffer onto the IdlAccount.
  2179. let ix = {
  2180. let accounts = vec![
  2181. AccountMeta::new(buffer, false),
  2182. AccountMeta::new(idl_address, false),
  2183. AccountMeta::new(idl_authority, true),
  2184. ];
  2185. let mut data = anchor_lang::idl::IDL_IX_TAG.to_le_bytes().to_vec();
  2186. data.append(&mut IdlInstruction::SetBuffer.try_to_vec()?);
  2187. Instruction {
  2188. program_id,
  2189. accounts,
  2190. data,
  2191. }
  2192. };
  2193. if print_only {
  2194. print_idl_instruction("SetBuffer", &ix, &idl_address)?;
  2195. } else {
  2196. // Build the transaction.
  2197. let instructions = prepend_compute_unit_ix(vec![ix], &client, priority_fee)?;
  2198. // Send the transaction.
  2199. let mut latest_hash = client.get_latest_blockhash()?;
  2200. for retries in 0..20 {
  2201. if !client.is_blockhash_valid(&latest_hash, client.commitment())? {
  2202. latest_hash = client.get_latest_blockhash()?;
  2203. }
  2204. let tx = Transaction::new_signed_with_payer(
  2205. &instructions,
  2206. Some(&keypair.pubkey()),
  2207. &[&keypair],
  2208. latest_hash,
  2209. );
  2210. match client.send_and_confirm_transaction_with_spinner(&tx) {
  2211. Ok(_) => break,
  2212. Err(e) => {
  2213. if retries == 19 {
  2214. return Err(anyhow!("Error: {e}. Failed to send transaction."));
  2215. }
  2216. println!("Error: {e}. Retrying transaction.");
  2217. }
  2218. }
  2219. }
  2220. }
  2221. Ok(idl_address)
  2222. })
  2223. }
  2224. fn idl_upgrade(
  2225. cfg_override: &ConfigOverride,
  2226. program_id: Pubkey,
  2227. idl_filepath: String,
  2228. priority_fee: Option<u64>,
  2229. ) -> Result<()> {
  2230. let buffer_address = idl_write_buffer(cfg_override, program_id, idl_filepath, priority_fee)?;
  2231. let idl_address = idl_set_buffer(
  2232. cfg_override,
  2233. program_id,
  2234. buffer_address,
  2235. false,
  2236. priority_fee,
  2237. )?;
  2238. idl_close(
  2239. cfg_override,
  2240. program_id,
  2241. Some(buffer_address),
  2242. false,
  2243. priority_fee,
  2244. )?;
  2245. println!("Idl account {idl_address} successfully upgraded");
  2246. Ok(())
  2247. }
  2248. fn idl_authority(cfg_override: &ConfigOverride, program_id: Pubkey) -> Result<()> {
  2249. with_workspace(cfg_override, |cfg| {
  2250. let url = cluster_url(cfg, &cfg.test_validator);
  2251. let client = create_client(url);
  2252. let idl_address = {
  2253. let account = client.get_account(&program_id)?;
  2254. if account.executable {
  2255. IdlAccount::address(&program_id)
  2256. } else {
  2257. program_id
  2258. }
  2259. };
  2260. let idl_account = get_idl_account(&client, &idl_address)?;
  2261. println!("{:?}", idl_account.authority);
  2262. Ok(())
  2263. })
  2264. }
  2265. fn idl_set_authority(
  2266. cfg_override: &ConfigOverride,
  2267. program_id: Pubkey,
  2268. address: Option<Pubkey>,
  2269. new_authority: Pubkey,
  2270. print_only: bool,
  2271. priority_fee: Option<u64>,
  2272. ) -> Result<()> {
  2273. with_workspace(cfg_override, |cfg| {
  2274. // Misc.
  2275. let idl_address = match address {
  2276. None => IdlAccount::address(&program_id),
  2277. Some(addr) => addr,
  2278. };
  2279. let keypair = get_keypair(&cfg.provider.wallet.to_string())?;
  2280. let url = cluster_url(cfg, &cfg.test_validator);
  2281. let client = create_client(url);
  2282. let idl_authority = if print_only {
  2283. get_idl_account(&client, &idl_address)?.authority
  2284. } else {
  2285. keypair.pubkey()
  2286. };
  2287. // Instruction data.
  2288. let data =
  2289. serialize_idl_ix(anchor_lang::idl::IdlInstruction::SetAuthority { new_authority })?;
  2290. // Instruction accounts.
  2291. let accounts = vec![
  2292. AccountMeta::new(idl_address, false),
  2293. AccountMeta::new_readonly(idl_authority, true),
  2294. ];
  2295. // Instruction.
  2296. let ix = Instruction {
  2297. program_id,
  2298. accounts,
  2299. data,
  2300. };
  2301. if print_only {
  2302. print_idl_instruction("SetAuthority", &ix, &idl_address)?;
  2303. } else {
  2304. let instructions = prepend_compute_unit_ix(vec![ix], &client, priority_fee)?;
  2305. // Send transaction.
  2306. let latest_hash = client.get_latest_blockhash()?;
  2307. let tx = Transaction::new_signed_with_payer(
  2308. &instructions,
  2309. Some(&keypair.pubkey()),
  2310. &[&keypair],
  2311. latest_hash,
  2312. );
  2313. client.send_and_confirm_transaction_with_spinner(&tx)?;
  2314. println!("Authority update complete.");
  2315. }
  2316. Ok(())
  2317. })
  2318. }
  2319. fn idl_erase_authority(
  2320. cfg_override: &ConfigOverride,
  2321. program_id: Pubkey,
  2322. priority_fee: Option<u64>,
  2323. ) -> Result<()> {
  2324. println!("Are you sure you want to erase the IDL authority: [y/n]");
  2325. let stdin = std::io::stdin();
  2326. let mut stdin_lines = stdin.lock().lines();
  2327. let input = stdin_lines.next().unwrap().unwrap();
  2328. if input != "y" {
  2329. println!("Not erasing.");
  2330. return Ok(());
  2331. }
  2332. idl_set_authority(
  2333. cfg_override,
  2334. program_id,
  2335. None,
  2336. ERASED_AUTHORITY,
  2337. false,
  2338. priority_fee,
  2339. )?;
  2340. Ok(())
  2341. }
  2342. fn idl_close_account(
  2343. cfg: &Config,
  2344. program_id: &Pubkey,
  2345. idl_address: Pubkey,
  2346. print_only: bool,
  2347. priority_fee: Option<u64>,
  2348. ) -> Result<()> {
  2349. let keypair = get_keypair(&cfg.provider.wallet.to_string())?;
  2350. let url = cluster_url(cfg, &cfg.test_validator);
  2351. let client = create_client(url);
  2352. let idl_authority = if print_only {
  2353. get_idl_account(&client, &idl_address)?.authority
  2354. } else {
  2355. keypair.pubkey()
  2356. };
  2357. // Instruction accounts.
  2358. let accounts = vec![
  2359. AccountMeta::new(idl_address, false),
  2360. AccountMeta::new_readonly(idl_authority, true),
  2361. AccountMeta::new(keypair.pubkey(), false),
  2362. ];
  2363. // Instruction.
  2364. let ix = Instruction {
  2365. program_id: *program_id,
  2366. accounts,
  2367. data: { serialize_idl_ix(anchor_lang::idl::IdlInstruction::Close {})? },
  2368. };
  2369. if print_only {
  2370. print_idl_instruction("Close", &ix, &idl_address)?;
  2371. } else {
  2372. let instructions = prepend_compute_unit_ix(vec![ix], &client, priority_fee)?;
  2373. // Send transaction.
  2374. let latest_hash = client.get_latest_blockhash()?;
  2375. let tx = Transaction::new_signed_with_payer(
  2376. &instructions,
  2377. Some(&keypair.pubkey()),
  2378. &[&keypair],
  2379. latest_hash,
  2380. );
  2381. client.send_and_confirm_transaction_with_spinner(&tx)?;
  2382. }
  2383. Ok(())
  2384. }
  2385. // Write the idl to the account buffer, chopping up the IDL into pieces
  2386. // and sending multiple transactions in the event the IDL doesn't fit into
  2387. // a single transaction.
  2388. fn idl_write(
  2389. cfg: &Config,
  2390. program_id: &Pubkey,
  2391. idl: &Idl,
  2392. idl_address: Pubkey,
  2393. priority_fee: Option<u64>,
  2394. ) -> Result<()> {
  2395. // Misc.
  2396. let keypair = get_keypair(&cfg.provider.wallet.to_string())?;
  2397. let url = cluster_url(cfg, &cfg.test_validator);
  2398. let client = create_client(url);
  2399. // Serialize and compress the idl.
  2400. let idl_data = {
  2401. let json_bytes = serde_json::to_vec(idl)?;
  2402. let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
  2403. e.write_all(&json_bytes)?;
  2404. e.finish()?
  2405. };
  2406. println!("Idl data length: {:?} bytes", idl_data.len());
  2407. const MAX_WRITE_SIZE: usize = 600;
  2408. let mut offset = 0;
  2409. while offset < idl_data.len() {
  2410. println!("Step {offset}/{} ", idl_data.len());
  2411. // Instruction data.
  2412. let data = {
  2413. let start = offset;
  2414. let end = std::cmp::min(offset + MAX_WRITE_SIZE, idl_data.len());
  2415. serialize_idl_ix(anchor_lang::idl::IdlInstruction::Write {
  2416. data: idl_data[start..end].to_vec(),
  2417. })?
  2418. };
  2419. // Instruction accounts.
  2420. let accounts = vec![
  2421. AccountMeta::new(idl_address, false),
  2422. AccountMeta::new_readonly(keypair.pubkey(), true),
  2423. ];
  2424. // Instruction.
  2425. let ix = Instruction {
  2426. program_id: *program_id,
  2427. accounts,
  2428. data,
  2429. };
  2430. // Send transaction.
  2431. let instructions = prepend_compute_unit_ix(vec![ix], &client, priority_fee)?;
  2432. let mut latest_hash = client.get_latest_blockhash()?;
  2433. for retries in 0..20 {
  2434. if !client.is_blockhash_valid(&latest_hash, client.commitment())? {
  2435. latest_hash = client.get_latest_blockhash()?;
  2436. }
  2437. let tx = Transaction::new_signed_with_payer(
  2438. &instructions,
  2439. Some(&keypair.pubkey()),
  2440. &[&keypair],
  2441. latest_hash,
  2442. );
  2443. match client.send_and_confirm_transaction_with_spinner(&tx) {
  2444. Ok(_) => break,
  2445. Err(e) => {
  2446. if retries == 19 {
  2447. return Err(anyhow!("Error: {e}. Failed to send transaction."));
  2448. }
  2449. println!("Error: {e}. Retrying transaction.");
  2450. }
  2451. }
  2452. }
  2453. offset += MAX_WRITE_SIZE;
  2454. }
  2455. Ok(())
  2456. }
  2457. fn idl_build(
  2458. cfg_override: &ConfigOverride,
  2459. program_name: Option<String>,
  2460. out: Option<String>,
  2461. out_ts: Option<String>,
  2462. no_docs: bool,
  2463. skip_lint: bool,
  2464. cargo_args: Vec<String>,
  2465. ) -> Result<()> {
  2466. let cfg = Config::discover(cfg_override)?.expect("Not in workspace");
  2467. let program_path = match program_name {
  2468. Some(name) => cfg.get_program(&name)?.path,
  2469. None => {
  2470. let current_dir = std::env::current_dir()?;
  2471. cfg.read_all_programs()?
  2472. .into_iter()
  2473. .find(|program| program.path == current_dir)
  2474. .ok_or_else(|| anyhow!("Not in a program directory"))?
  2475. .path
  2476. }
  2477. };
  2478. check_idl_build_feature().ok();
  2479. let idl = anchor_lang_idl::build::build_idl_with_cargo_args(
  2480. program_path,
  2481. cfg.features.resolution,
  2482. cfg.features.skip_lint || skip_lint,
  2483. no_docs,
  2484. &cargo_args,
  2485. )?;
  2486. let out = match out {
  2487. Some(path) => OutFile::File(PathBuf::from(path)),
  2488. None => OutFile::Stdout,
  2489. };
  2490. write_idl(&idl, out)?;
  2491. if let Some(path) = out_ts {
  2492. fs::write(path, idl_ts(&idl)?)?;
  2493. }
  2494. Ok(())
  2495. }
  2496. /// Generate IDL with method decided by whether manifest file has `idl-build` feature or not.
  2497. fn generate_idl(
  2498. cfg: &WithPath<Config>,
  2499. skip_lint: bool,
  2500. no_docs: bool,
  2501. cargo_args: &[String],
  2502. ) -> Result<Idl> {
  2503. // Check whether the manifest has `idl-build` feature
  2504. let manifest = Manifest::discover()?.ok_or_else(|| anyhow!("Cargo.toml not found"))?;
  2505. let is_idl_build = manifest
  2506. .features
  2507. .iter()
  2508. .any(|(feature, _)| feature == "idl-build");
  2509. if !is_idl_build {
  2510. let path = manifest.path().display();
  2511. let anchor_spl_idl_build = manifest
  2512. .dependencies
  2513. .iter()
  2514. .any(|dep| dep.0 == "anchor-spl")
  2515. .then_some(r#", "anchor-spl/idl-build""#)
  2516. .unwrap_or_default();
  2517. return Err(anyhow!(
  2518. r#"`idl-build` feature is missing. To solve, add
  2519. [features]
  2520. idl-build = ["anchor-lang/idl-build"{anchor_spl_idl_build}]
  2521. in `{path}`."#
  2522. ));
  2523. }
  2524. check_idl_build_feature().ok();
  2525. anchor_lang_idl::build::build_idl_with_cargo_args(
  2526. std::env::current_dir()?,
  2527. cfg.features.resolution,
  2528. cfg.features.skip_lint || skip_lint,
  2529. no_docs,
  2530. cargo_args,
  2531. )
  2532. }
  2533. fn idl_fetch(cfg_override: &ConfigOverride, address: Pubkey, out: Option<String>) -> Result<()> {
  2534. let idl = fetch_idl(cfg_override, address)?;
  2535. let out = match out {
  2536. None => OutFile::Stdout,
  2537. Some(out) => OutFile::File(PathBuf::from(out)),
  2538. };
  2539. write_idl(&idl, out)
  2540. }
  2541. fn idl_convert(path: String, out: Option<String>) -> Result<()> {
  2542. let idl = fs::read(path)?;
  2543. let idl = convert_idl(&idl)?;
  2544. let out = match out {
  2545. None => OutFile::Stdout,
  2546. Some(out) => OutFile::File(PathBuf::from(out)),
  2547. };
  2548. write_idl(&idl, out)
  2549. }
  2550. fn idl_type(path: String, out: Option<String>) -> Result<()> {
  2551. let idl = fs::read(path)?;
  2552. let idl = convert_idl(&idl)?;
  2553. let types = idl_ts(&idl)?;
  2554. match out {
  2555. Some(out) => fs::write(out, types)?,
  2556. _ => println!("{types}"),
  2557. };
  2558. Ok(())
  2559. }
  2560. fn idl_ts(idl: &Idl) -> Result<String> {
  2561. let idl_name = &idl.metadata.name;
  2562. let type_name = idl_name.to_pascal_case();
  2563. let idl = serde_json::to_string(idl)?;
  2564. // Convert every field of the IDL to camelCase
  2565. let camel_idl = Regex::new(r#""\w+":"([\w\d]+)""#)?
  2566. .captures_iter(&idl)
  2567. .fold(idl.clone(), |acc, cur| {
  2568. let name = cur.get(1).unwrap().as_str();
  2569. // Do not modify pubkeys
  2570. if Pubkey::from_str(name).is_ok() {
  2571. return acc;
  2572. }
  2573. let camel_name = name.to_lower_camel_case();
  2574. acc.replace(&format!(r#""{name}""#), &format!(r#""{camel_name}""#))
  2575. });
  2576. // Pretty format
  2577. let camel_idl = serde_json::to_string_pretty(&serde_json::from_str::<Idl>(&camel_idl)?)?;
  2578. Ok(format!(
  2579. r#"/**
  2580. * Program IDL in camelCase format in order to be used in JS/TS.
  2581. *
  2582. * Note that this is only a type helper and is not the actual IDL. The original
  2583. * IDL can be found at `target/idl/{idl_name}.json`.
  2584. */
  2585. export type {type_name} = {camel_idl};
  2586. "#
  2587. ))
  2588. }
  2589. fn write_idl(idl: &Idl, out: OutFile) -> Result<()> {
  2590. let idl_json = serde_json::to_string_pretty(idl)?;
  2591. match out {
  2592. OutFile::Stdout => println!("{idl_json}"),
  2593. OutFile::File(out) => fs::write(out, idl_json)?,
  2594. };
  2595. Ok(())
  2596. }
  2597. /// Print `base64+borsh` encoded IDL instruction.
  2598. fn print_idl_instruction(ix_name: &str, ix: &Instruction, idl_address: &Pubkey) -> Result<()> {
  2599. use base64::engine::general_purpose::STANDARD;
  2600. use base64::Engine;
  2601. println!("Print only mode. No execution!");
  2602. println!("Instruction: {ix_name}");
  2603. println!("IDL address: {idl_address}");
  2604. println!("Program: {}", ix.program_id);
  2605. // Serialize with `bincode` because `Instruction` does not implement `BorshSerialize`
  2606. let mut serialized_ix = bincode::serialize(ix)?;
  2607. // Remove extra bytes in order to make the serialized instruction `borsh` compatible
  2608. // `bincode` uses 8 bytes(LE) for length meanwhile `borsh` uses 4 bytes(LE)
  2609. let mut remove_extra_vec_bytes = |index: usize| {
  2610. serialized_ix.drain((index + 4)..(index + 8));
  2611. };
  2612. let accounts_index = std::mem::size_of_val(&ix.program_id);
  2613. remove_extra_vec_bytes(accounts_index);
  2614. let data_index = accounts_index + 4 + std::mem::size_of_val(&*ix.accounts);
  2615. remove_extra_vec_bytes(data_index);
  2616. println!(
  2617. "Base64 encoded instruction: {}",
  2618. STANDARD.encode(serialized_ix)
  2619. );
  2620. Ok(())
  2621. }
  2622. fn account(
  2623. cfg_override: &ConfigOverride,
  2624. account_type: String,
  2625. address: Pubkey,
  2626. idl_filepath: Option<String>,
  2627. ) -> Result<()> {
  2628. let (program_name, account_type_name) = account_type
  2629. .split_once('.') // Split at first occurrence of dot
  2630. .and_then(|(x, y)| y.find('.').map_or_else(|| Some((x, y)), |_| None)) // ensures no dots in second substring
  2631. .ok_or_else(|| {
  2632. anyhow!(
  2633. "Please enter the account struct in the following format: <program_name>.<Account>",
  2634. )
  2635. })?;
  2636. let idl = idl_filepath.map_or_else(
  2637. || {
  2638. Config::discover(cfg_override)
  2639. .expect("Error when detecting workspace.")
  2640. .expect("Not in workspace.")
  2641. .read_all_programs()
  2642. .expect("Workspace must contain atleast one program.")
  2643. .iter()
  2644. .find(|&p| p.lib_name == *program_name)
  2645. .unwrap_or_else(|| panic!("Program {program_name} not found in workspace."))
  2646. .idl
  2647. .as_ref()
  2648. .expect("IDL not found. Please build the program atleast once to generate the IDL.")
  2649. .clone()
  2650. },
  2651. |idl_path| {
  2652. let bytes = fs::read(idl_path).expect("Unable to read IDL.");
  2653. let idl: Idl = serde_json::from_reader(&*bytes).expect("Invalid IDL format.");
  2654. if idl.metadata.name != program_name {
  2655. panic!("IDL does not match program {program_name}.");
  2656. }
  2657. idl
  2658. },
  2659. );
  2660. let cluster = match &cfg_override.cluster {
  2661. Some(cluster) => cluster.clone(),
  2662. None => Config::discover(cfg_override)?
  2663. .map(|cfg| cfg.provider.cluster.clone())
  2664. .unwrap_or(Cluster::Localnet),
  2665. };
  2666. let data = create_client(cluster.url()).get_account_data(&address)?;
  2667. let disc_len = idl
  2668. .accounts
  2669. .iter()
  2670. .find(|acc| acc.name == account_type_name)
  2671. .map(|acc| acc.discriminator.len())
  2672. .ok_or_else(|| anyhow!("Account `{account_type_name}` not found in IDL"))?;
  2673. let mut data_view = &data[disc_len..];
  2674. let deserialized_json =
  2675. deserialize_idl_defined_type_to_json(&idl, account_type_name, &mut data_view)?;
  2676. println!(
  2677. "{}",
  2678. serde_json::to_string_pretty(&deserialized_json).unwrap()
  2679. );
  2680. Ok(())
  2681. }
  2682. // Deserializes user defined IDL types by munching the account data(recursively).
  2683. fn deserialize_idl_defined_type_to_json(
  2684. idl: &Idl,
  2685. defined_type_name: &str,
  2686. data: &mut &[u8],
  2687. ) -> Result<JsonValue, anyhow::Error> {
  2688. let defined_type = &idl
  2689. .accounts
  2690. .iter()
  2691. .find(|acc| acc.name == defined_type_name)
  2692. .and_then(|acc| idl.types.iter().find(|ty| ty.name == acc.name))
  2693. .or_else(|| idl.types.iter().find(|ty| ty.name == defined_type_name))
  2694. .ok_or_else(|| anyhow!("Type `{}` not found in IDL.", defined_type_name))?
  2695. .ty;
  2696. let mut deserialized_fields = Map::new();
  2697. match defined_type {
  2698. IdlTypeDefTy::Struct { fields } => {
  2699. if let Some(fields) = fields {
  2700. match fields {
  2701. IdlDefinedFields::Named(fields) => {
  2702. for field in fields {
  2703. deserialized_fields.insert(
  2704. field.name.clone(),
  2705. deserialize_idl_type_to_json(&field.ty, data, idl)?,
  2706. );
  2707. }
  2708. }
  2709. IdlDefinedFields::Tuple(fields) => {
  2710. let mut values = Vec::new();
  2711. for field in fields {
  2712. values.push(deserialize_idl_type_to_json(field, data, idl)?);
  2713. }
  2714. deserialized_fields
  2715. .insert(defined_type_name.to_owned(), JsonValue::Array(values));
  2716. }
  2717. }
  2718. }
  2719. }
  2720. IdlTypeDefTy::Enum { variants } => {
  2721. let repr = <u8 as AnchorDeserialize>::deserialize(data)?;
  2722. let variant = variants
  2723. .get(repr as usize)
  2724. .unwrap_or_else(|| panic!("Error while deserializing enum variant {repr}"));
  2725. let mut value = json!({});
  2726. if let Some(enum_field) = &variant.fields {
  2727. match enum_field {
  2728. IdlDefinedFields::Named(fields) => {
  2729. let mut values = Map::new();
  2730. for field in fields {
  2731. values.insert(
  2732. field.name.clone(),
  2733. deserialize_idl_type_to_json(&field.ty, data, idl)?,
  2734. );
  2735. }
  2736. value = JsonValue::Object(values);
  2737. }
  2738. IdlDefinedFields::Tuple(fields) => {
  2739. let mut values = Vec::new();
  2740. for field in fields {
  2741. values.push(deserialize_idl_type_to_json(field, data, idl)?);
  2742. }
  2743. value = JsonValue::Array(values);
  2744. }
  2745. }
  2746. }
  2747. deserialized_fields.insert(variant.name.clone(), value);
  2748. }
  2749. IdlTypeDefTy::Type { alias } => {
  2750. return deserialize_idl_type_to_json(alias, data, idl);
  2751. }
  2752. }
  2753. Ok(JsonValue::Object(deserialized_fields))
  2754. }
  2755. // Deserializes a primitive type using AnchorDeserialize
  2756. fn deserialize_idl_type_to_json(
  2757. idl_type: &IdlType,
  2758. data: &mut &[u8],
  2759. parent_idl: &Idl,
  2760. ) -> Result<JsonValue, anyhow::Error> {
  2761. if data.is_empty() {
  2762. return Err(anyhow::anyhow!("Unable to parse from empty bytes"));
  2763. }
  2764. Ok(match idl_type {
  2765. IdlType::Bool => json!(<bool as AnchorDeserialize>::deserialize(data)?),
  2766. IdlType::U8 => {
  2767. json!(<u8 as AnchorDeserialize>::deserialize(data)?)
  2768. }
  2769. IdlType::I8 => {
  2770. json!(<i8 as AnchorDeserialize>::deserialize(data)?)
  2771. }
  2772. IdlType::U16 => {
  2773. json!(<u16 as AnchorDeserialize>::deserialize(data)?)
  2774. }
  2775. IdlType::I16 => {
  2776. json!(<i16 as AnchorDeserialize>::deserialize(data)?)
  2777. }
  2778. IdlType::U32 => {
  2779. json!(<u32 as AnchorDeserialize>::deserialize(data)?)
  2780. }
  2781. IdlType::I32 => {
  2782. json!(<i32 as AnchorDeserialize>::deserialize(data)?)
  2783. }
  2784. IdlType::F32 => json!(<f32 as AnchorDeserialize>::deserialize(data)?),
  2785. IdlType::U64 => {
  2786. json!(<u64 as AnchorDeserialize>::deserialize(data)?)
  2787. }
  2788. IdlType::I64 => {
  2789. json!(<i64 as AnchorDeserialize>::deserialize(data)?)
  2790. }
  2791. IdlType::F64 => json!(<f64 as AnchorDeserialize>::deserialize(data)?),
  2792. IdlType::U128 => {
  2793. // TODO: Remove to_string once serde_json supports u128 deserialization
  2794. json!(<u128 as AnchorDeserialize>::deserialize(data)?.to_string())
  2795. }
  2796. IdlType::I128 => {
  2797. // TODO: Remove to_string once serde_json supports i128 deserialization
  2798. json!(<i128 as AnchorDeserialize>::deserialize(data)?.to_string())
  2799. }
  2800. IdlType::U256 => todo!("Upon completion of u256 IDL standard"),
  2801. IdlType::I256 => todo!("Upon completion of i256 IDL standard"),
  2802. IdlType::Bytes => JsonValue::Array(
  2803. <Vec<u8> as AnchorDeserialize>::deserialize(data)?
  2804. .iter()
  2805. .map(|i| json!(*i))
  2806. .collect(),
  2807. ),
  2808. IdlType::String => json!(<String as AnchorDeserialize>::deserialize(data)?),
  2809. IdlType::Pubkey => {
  2810. json!(<Pubkey as AnchorDeserialize>::deserialize(data)?.to_string())
  2811. }
  2812. IdlType::Array(ty, size) => match size {
  2813. IdlArrayLen::Value(size) => {
  2814. let mut array_data: Vec<JsonValue> = Vec::with_capacity(*size);
  2815. for _ in 0..*size {
  2816. array_data.push(deserialize_idl_type_to_json(ty, data, parent_idl)?);
  2817. }
  2818. JsonValue::Array(array_data)
  2819. }
  2820. // TODO:
  2821. IdlArrayLen::Generic(_) => unimplemented!("Generic array length is not yet supported"),
  2822. },
  2823. IdlType::Option(ty) => {
  2824. let is_present = <u8 as AnchorDeserialize>::deserialize(data)?;
  2825. if is_present == 0 {
  2826. JsonValue::String("None".to_string())
  2827. } else {
  2828. deserialize_idl_type_to_json(ty, data, parent_idl)?
  2829. }
  2830. }
  2831. IdlType::Vec(ty) => {
  2832. let size: usize = <u32 as AnchorDeserialize>::deserialize(data)?
  2833. .try_into()
  2834. .unwrap();
  2835. let mut vec_data: Vec<JsonValue> = Vec::with_capacity(size);
  2836. for _ in 0..size {
  2837. vec_data.push(deserialize_idl_type_to_json(ty, data, parent_idl)?);
  2838. }
  2839. JsonValue::Array(vec_data)
  2840. }
  2841. IdlType::Defined {
  2842. name,
  2843. generics: _generics,
  2844. } => {
  2845. // TODO: Generics
  2846. deserialize_idl_defined_type_to_json(parent_idl, name, data)?
  2847. }
  2848. IdlType::Generic(generic) => json!(generic),
  2849. _ => unimplemented!("{idl_type:?}"),
  2850. })
  2851. }
  2852. enum OutFile {
  2853. Stdout,
  2854. File(PathBuf),
  2855. }
  2856. // Builds, deploys, and tests all workspace programs in a single command.
  2857. #[allow(clippy::too_many_arguments)]
  2858. fn test(
  2859. cfg_override: &ConfigOverride,
  2860. program_name: Option<String>,
  2861. skip_deploy: bool,
  2862. skip_local_validator: bool,
  2863. skip_build: bool,
  2864. skip_lint: bool,
  2865. no_idl: bool,
  2866. detach: bool,
  2867. tests_to_run: Vec<String>,
  2868. extra_args: Vec<String>,
  2869. env_vars: Vec<String>,
  2870. cargo_args: Vec<String>,
  2871. arch: ProgramArch,
  2872. ) -> Result<()> {
  2873. let test_paths = tests_to_run
  2874. .iter()
  2875. .map(|path| {
  2876. PathBuf::from(path)
  2877. .canonicalize()
  2878. .map_err(|_| anyhow!("Wrong path {}", path))
  2879. })
  2880. .collect::<Result<Vec<_>, _>>()?;
  2881. with_workspace(cfg_override, |cfg| {
  2882. // Build if needed.
  2883. if !skip_build {
  2884. build(
  2885. cfg_override,
  2886. no_idl,
  2887. None,
  2888. None,
  2889. false,
  2890. skip_lint,
  2891. program_name.clone(),
  2892. None,
  2893. None,
  2894. BootstrapMode::None,
  2895. None,
  2896. None,
  2897. env_vars,
  2898. cargo_args,
  2899. false,
  2900. arch,
  2901. )?;
  2902. }
  2903. let root = cfg.path().parent().unwrap().to_owned();
  2904. cfg.add_test_config(root, test_paths)?;
  2905. // Run the deploy against the cluster in two cases:
  2906. //
  2907. // 1. The cluster is not localnet.
  2908. // 2. The cluster is localnet, but we're not booting a local validator.
  2909. //
  2910. // In either case, skip the deploy if the user specifies.
  2911. let is_localnet = cfg.provider.cluster == Cluster::Localnet;
  2912. if (!is_localnet || skip_local_validator) && !skip_deploy {
  2913. deploy(cfg_override, None, None, false, vec![])?;
  2914. }
  2915. let mut is_first_suite = true;
  2916. if let Some(test_script) = cfg.scripts.get_mut("test") {
  2917. is_first_suite = false;
  2918. match program_name {
  2919. Some(program_name) => {
  2920. if let Some((from, to)) = Regex::new("\\s(tests/\\S+\\.(js|ts))")
  2921. .unwrap()
  2922. .captures_iter(&test_script.clone())
  2923. .last()
  2924. .and_then(|c| c.get(1).and_then(|mtch| c.get(2).map(|ext| (mtch, ext))))
  2925. .map(|(mtch, ext)| {
  2926. (
  2927. mtch.as_str(),
  2928. format!("tests/{program_name}.{}", ext.as_str()),
  2929. )
  2930. })
  2931. {
  2932. println!("\nRunning tests of program `{program_name}`!");
  2933. // Replace the last path to the program name's path
  2934. *test_script = test_script.replace(from, &to);
  2935. }
  2936. }
  2937. _ => println!(
  2938. "\nFound a 'test' script in the Anchor.toml. Running it as a test suite!"
  2939. ),
  2940. }
  2941. run_test_suite(
  2942. cfg,
  2943. cfg.path(),
  2944. is_localnet,
  2945. skip_local_validator,
  2946. skip_deploy,
  2947. detach,
  2948. &cfg.test_validator,
  2949. &cfg.scripts,
  2950. &extra_args,
  2951. )?;
  2952. }
  2953. if let Some(test_config) = &cfg.test_config {
  2954. for test_suite in test_config.iter() {
  2955. if !is_first_suite {
  2956. std::thread::sleep(std::time::Duration::from_millis(
  2957. test_suite
  2958. .1
  2959. .test
  2960. .as_ref()
  2961. .map(|val| val.shutdown_wait)
  2962. .unwrap_or(SHUTDOWN_WAIT) as u64,
  2963. ));
  2964. } else {
  2965. is_first_suite = false;
  2966. }
  2967. run_test_suite(
  2968. cfg,
  2969. test_suite.0,
  2970. is_localnet,
  2971. skip_local_validator,
  2972. skip_deploy,
  2973. detach,
  2974. &test_suite.1.test,
  2975. &test_suite.1.scripts,
  2976. &extra_args,
  2977. )?;
  2978. }
  2979. }
  2980. Ok(())
  2981. })
  2982. }
  2983. #[allow(clippy::too_many_arguments)]
  2984. fn run_test_suite(
  2985. cfg: &WithPath<Config>,
  2986. test_suite_path: impl AsRef<Path>,
  2987. is_localnet: bool,
  2988. skip_local_validator: bool,
  2989. skip_deploy: bool,
  2990. detach: bool,
  2991. test_validator: &Option<TestValidator>,
  2992. scripts: &ScriptsConfig,
  2993. extra_args: &[String],
  2994. ) -> Result<()> {
  2995. println!("\nRunning test suite: {:#?}\n", test_suite_path.as_ref());
  2996. // Start local test validator, if needed.
  2997. let mut validator_handle = None;
  2998. if is_localnet && (!skip_local_validator) {
  2999. let flags = match skip_deploy {
  3000. true => None,
  3001. false => Some(validator_flags(cfg, test_validator)?),
  3002. };
  3003. validator_handle = Some(start_test_validator(cfg, test_validator, flags, true)?);
  3004. }
  3005. let url = cluster_url(cfg, test_validator);
  3006. let node_options = format!(
  3007. "{} {}",
  3008. match std::env::var_os("NODE_OPTIONS") {
  3009. Some(value) => value
  3010. .into_string()
  3011. .map_err(std::env::VarError::NotUnicode)?,
  3012. None => "".to_owned(),
  3013. },
  3014. get_node_dns_option()?,
  3015. );
  3016. // Setup log reader.
  3017. let log_streams = stream_logs(cfg, &url);
  3018. // Run the tests.
  3019. let test_result = {
  3020. let cmd = scripts
  3021. .get("test")
  3022. .expect("Not able to find script for `test`")
  3023. .clone();
  3024. let script_args = format!("{cmd} {}", extra_args.join(" "));
  3025. std::process::Command::new("bash")
  3026. .arg("-c")
  3027. .arg(script_args)
  3028. .env("ANCHOR_PROVIDER_URL", url)
  3029. .env("ANCHOR_WALLET", cfg.provider.wallet.to_string())
  3030. .env("NODE_OPTIONS", node_options)
  3031. .stdout(Stdio::inherit())
  3032. .stderr(Stdio::inherit())
  3033. .output()
  3034. .map_err(anyhow::Error::from)
  3035. .context(cmd)
  3036. };
  3037. // Keep validator running if needed.
  3038. if test_result.is_ok() && detach {
  3039. println!("Local validator still running. Press Ctrl + C quit.");
  3040. std::io::stdin().lock().lines().next().unwrap().unwrap();
  3041. }
  3042. // Check all errors and shut down.
  3043. if let Some(mut child) = validator_handle {
  3044. if let Err(err) = child.kill() {
  3045. println!("Failed to kill subprocess {}: {}", child.id(), err);
  3046. }
  3047. }
  3048. for mut child in log_streams? {
  3049. if let Err(err) = child.kill() {
  3050. println!("Failed to kill subprocess {}: {}", child.id(), err);
  3051. }
  3052. }
  3053. // Must exist *after* shutting down the validator and log streams.
  3054. match test_result {
  3055. Ok(exit) => {
  3056. if !exit.status.success() {
  3057. std::process::exit(exit.status.code().unwrap());
  3058. }
  3059. }
  3060. Err(err) => {
  3061. println!("Failed to run test: {err:#}");
  3062. return Err(err);
  3063. }
  3064. }
  3065. Ok(())
  3066. }
  3067. // Returns the solana-test-validator flags. This will embed the workspace
  3068. // programs in the genesis block so we don't have to deploy every time. It also
  3069. // allows control of other solana-test-validator features.
  3070. fn validator_flags(
  3071. cfg: &WithPath<Config>,
  3072. test_validator: &Option<TestValidator>,
  3073. ) -> Result<Vec<String>> {
  3074. let programs = cfg.programs.get(&Cluster::Localnet);
  3075. let test_upgradeable_program = test_validator
  3076. .as_ref()
  3077. .map(|test_validator| test_validator.upgradeable)
  3078. .unwrap_or(false);
  3079. let mut flags = Vec::new();
  3080. for mut program in cfg.read_all_programs()? {
  3081. let verifiable = false;
  3082. let binary_path = program.binary_path(verifiable).display().to_string();
  3083. // Use the [programs.cluster] override and fallback to the keypair
  3084. // files if no override is given.
  3085. let address = programs
  3086. .and_then(|m| m.get(&program.lib_name))
  3087. .map(|deployment| Ok(deployment.address.to_string()))
  3088. .unwrap_or_else(|| program.pubkey().map(|p| p.to_string()))?;
  3089. if test_upgradeable_program {
  3090. flags.push("--upgradeable-program".to_string());
  3091. flags.push(address.clone());
  3092. flags.push(binary_path);
  3093. flags.push(cfg.wallet_kp()?.pubkey().to_string());
  3094. } else {
  3095. flags.push("--bpf-program".to_string());
  3096. flags.push(address.clone());
  3097. flags.push(binary_path);
  3098. }
  3099. if let Some(idl) = program.idl.as_mut() {
  3100. // Add program address to the IDL.
  3101. idl.address = address;
  3102. // Persist it.
  3103. let idl_out = PathBuf::from("target/idl")
  3104. .join(&idl.metadata.name)
  3105. .with_extension("json");
  3106. write_idl(idl, OutFile::File(idl_out))?;
  3107. }
  3108. }
  3109. if let Some(test) = test_validator.as_ref() {
  3110. if let Some(genesis) = &test.genesis {
  3111. for entry in genesis {
  3112. let program_path = Path::new(&entry.program);
  3113. if !program_path.exists() {
  3114. return Err(anyhow!(
  3115. "Program in genesis configuration does not exist at path: {}",
  3116. program_path.display()
  3117. ));
  3118. }
  3119. if entry.upgradeable.unwrap_or(false) {
  3120. flags.push("--upgradeable-program".to_string());
  3121. flags.push(entry.address.clone());
  3122. flags.push(entry.program.clone());
  3123. flags.push(cfg.wallet_kp()?.pubkey().to_string());
  3124. } else {
  3125. flags.push("--bpf-program".to_string());
  3126. flags.push(entry.address.clone());
  3127. flags.push(entry.program.clone());
  3128. }
  3129. }
  3130. }
  3131. if let Some(validator) = &test.validator {
  3132. let entries = serde_json::to_value(validator)?;
  3133. for (key, value) in entries.as_object().unwrap() {
  3134. if key == "ledger" {
  3135. // Ledger flag is a special case as it is passed separately to the rest of
  3136. // these validator flags.
  3137. continue;
  3138. };
  3139. if key == "account" {
  3140. for entry in value.as_array().unwrap() {
  3141. // Push the account flag for each array entry
  3142. flags.push("--account".to_string());
  3143. flags.push(entry["address"].as_str().unwrap().to_string());
  3144. flags.push(entry["filename"].as_str().unwrap().to_string());
  3145. }
  3146. } else if key == "account_dir" {
  3147. for entry in value.as_array().unwrap() {
  3148. flags.push("--account-dir".to_string());
  3149. flags.push(entry["directory"].as_str().unwrap().to_string());
  3150. }
  3151. } else if key == "clone" {
  3152. // Client for fetching accounts data
  3153. let client = if let Some(url) = entries["url"].as_str() {
  3154. create_client(url)
  3155. } else {
  3156. return Err(anyhow!(
  3157. "Validator url for Solana's JSON RPC should be provided in order to clone accounts from it"
  3158. ));
  3159. };
  3160. let pubkeys = value
  3161. .as_array()
  3162. .unwrap()
  3163. .iter()
  3164. .map(|entry| {
  3165. let address = entry["address"].as_str().unwrap();
  3166. Pubkey::from_str(address)
  3167. .map_err(|_| anyhow!("Invalid pubkey {}", address))
  3168. })
  3169. .collect::<Result<HashSet<Pubkey>>>()?
  3170. .into_iter()
  3171. .collect::<Vec<_>>();
  3172. let accounts = client.get_multiple_accounts(&pubkeys)?;
  3173. for (pubkey, account) in pubkeys.into_iter().zip(accounts) {
  3174. match account {
  3175. Some(account) => {
  3176. // Use a different flag for program accounts to fix the problem
  3177. // described in https://github.com/anza-xyz/agave/issues/522
  3178. if account.owner == bpf_loader_upgradeable::id()
  3179. // Only programs are supported with `--clone-upgradeable-program`
  3180. && matches!(
  3181. account.deserialize_data::<UpgradeableLoaderState>()?,
  3182. UpgradeableLoaderState::Program { .. }
  3183. )
  3184. {
  3185. flags.push("--clone-upgradeable-program".to_string());
  3186. flags.push(pubkey.to_string());
  3187. } else {
  3188. flags.push("--clone".to_string());
  3189. flags.push(pubkey.to_string());
  3190. }
  3191. }
  3192. _ => return Err(anyhow!("Account {} not found", pubkey)),
  3193. }
  3194. }
  3195. } else if key == "deactivate_feature" {
  3196. // Verify that the feature flags are valid pubkeys
  3197. let pubkeys_result: Result<Vec<Pubkey>, _> = value
  3198. .as_array()
  3199. .unwrap()
  3200. .iter()
  3201. .map(|entry| {
  3202. let feature_flag = entry.as_str().unwrap();
  3203. Pubkey::from_str(feature_flag).map_err(|_| {
  3204. anyhow!("Invalid pubkey (feature flag) {}", feature_flag)
  3205. })
  3206. })
  3207. .collect();
  3208. let features = pubkeys_result?;
  3209. for feature in features {
  3210. flags.push("--deactivate-feature".to_string());
  3211. flags.push(feature.to_string());
  3212. }
  3213. } else {
  3214. // Remaining validator flags are non-array types
  3215. flags.push(format!("--{}", key.replace('_', "-")));
  3216. if let serde_json::Value::String(v) = value {
  3217. flags.push(v.to_string());
  3218. } else {
  3219. flags.push(value.to_string());
  3220. }
  3221. }
  3222. }
  3223. }
  3224. }
  3225. Ok(flags)
  3226. }
  3227. fn stream_logs(config: &WithPath<Config>, rpc_url: &str) -> Result<Vec<std::process::Child>> {
  3228. let program_logs_dir = ".anchor/program-logs";
  3229. if Path::new(program_logs_dir).exists() {
  3230. fs::remove_dir_all(program_logs_dir)?;
  3231. }
  3232. fs::create_dir_all(program_logs_dir)?;
  3233. let mut handles = vec![];
  3234. for program in config.read_all_programs()? {
  3235. let mut file = File::open(format!("target/idl/{}.json", program.lib_name))?;
  3236. let mut contents = vec![];
  3237. file.read_to_end(&mut contents)?;
  3238. let idl: Idl = serde_json::from_slice(&contents)?;
  3239. let log_file = File::create(format!(
  3240. "{}/{}.{}.log",
  3241. program_logs_dir, idl.address, program.lib_name,
  3242. ))?;
  3243. let stdio = std::process::Stdio::from(log_file);
  3244. let child = std::process::Command::new("solana")
  3245. .arg("logs")
  3246. .arg(idl.address)
  3247. .arg("--url")
  3248. .arg(rpc_url)
  3249. .stdout(stdio)
  3250. .spawn()?;
  3251. handles.push(child);
  3252. }
  3253. if let Some(test) = config.test_validator.as_ref() {
  3254. if let Some(genesis) = &test.genesis {
  3255. for entry in genesis {
  3256. let log_file = File::create(format!("{}/{}.log", program_logs_dir, entry.address))?;
  3257. let stdio = std::process::Stdio::from(log_file);
  3258. let child = std::process::Command::new("solana")
  3259. .arg("logs")
  3260. .arg(entry.address.clone())
  3261. .arg("--url")
  3262. .arg(rpc_url)
  3263. .stdout(stdio)
  3264. .spawn()?;
  3265. handles.push(child);
  3266. }
  3267. }
  3268. }
  3269. Ok(handles)
  3270. }
  3271. fn start_test_validator(
  3272. cfg: &Config,
  3273. test_validator: &Option<TestValidator>,
  3274. flags: Option<Vec<String>>,
  3275. test_log_stdout: bool,
  3276. ) -> Result<Child> {
  3277. let (test_ledger_directory, test_ledger_log_filename) =
  3278. test_validator_file_paths(test_validator)?;
  3279. // Start a validator for testing.
  3280. let (test_validator_stdout, test_validator_stderr) = match test_log_stdout {
  3281. true => {
  3282. let test_validator_stdout_file = File::create(&test_ledger_log_filename)?;
  3283. let test_validator_sterr_file = test_validator_stdout_file.try_clone()?;
  3284. (
  3285. Stdio::from(test_validator_stdout_file),
  3286. Stdio::from(test_validator_sterr_file),
  3287. )
  3288. }
  3289. false => (Stdio::inherit(), Stdio::inherit()),
  3290. };
  3291. let rpc_url = test_validator_rpc_url(test_validator);
  3292. let rpc_port = cfg
  3293. .test_validator
  3294. .as_ref()
  3295. .and_then(|test| test.validator.as_ref().map(|v| v.rpc_port))
  3296. .unwrap_or(solana_sdk::rpc_port::DEFAULT_RPC_PORT);
  3297. if !portpicker::is_free(rpc_port) {
  3298. return Err(anyhow!(
  3299. "Your configured rpc port: {rpc_port} is already in use"
  3300. ));
  3301. }
  3302. let faucet_port = cfg
  3303. .test_validator
  3304. .as_ref()
  3305. .and_then(|test| test.validator.as_ref().and_then(|v| v.faucet_port))
  3306. .unwrap_or(solana_faucet::faucet::FAUCET_PORT);
  3307. if !portpicker::is_free(faucet_port) {
  3308. return Err(anyhow!(
  3309. "Your configured faucet port: {faucet_port} is already in use"
  3310. ));
  3311. }
  3312. let mut validator_handle = std::process::Command::new("solana-test-validator")
  3313. .arg("--ledger")
  3314. .arg(test_ledger_directory)
  3315. .arg("--mint")
  3316. .arg(cfg.wallet_kp()?.pubkey().to_string())
  3317. .args(flags.unwrap_or_default())
  3318. .stdout(test_validator_stdout)
  3319. .stderr(test_validator_stderr)
  3320. .spawn()
  3321. .map_err(|e| anyhow!("Failed to spawn `solana-test-validator`: {e}"))?;
  3322. // Wait for the validator to be ready.
  3323. let client = create_client(rpc_url);
  3324. let mut count = 0;
  3325. let ms_wait = test_validator
  3326. .as_ref()
  3327. .map(|test| test.startup_wait)
  3328. .unwrap_or(STARTUP_WAIT);
  3329. while count < ms_wait {
  3330. let r = client.get_latest_blockhash();
  3331. if r.is_ok() {
  3332. break;
  3333. }
  3334. std::thread::sleep(std::time::Duration::from_millis(100));
  3335. count += 100;
  3336. }
  3337. if count >= ms_wait {
  3338. eprintln!(
  3339. "Unable to get latest blockhash. Test validator does not look started. \
  3340. Check {test_ledger_log_filename:?} for errors. Consider increasing [test.startup_wait] in Anchor.toml."
  3341. );
  3342. validator_handle.kill()?;
  3343. std::process::exit(1);
  3344. }
  3345. Ok(validator_handle)
  3346. }
  3347. // Return the URL that solana-test-validator should be running on given the
  3348. // configuration
  3349. fn test_validator_rpc_url(test_validator: &Option<TestValidator>) -> String {
  3350. match test_validator {
  3351. Some(TestValidator {
  3352. validator: Some(validator),
  3353. ..
  3354. }) => format!("http://{}:{}", validator.bind_address, validator.rpc_port),
  3355. _ => "http://127.0.0.1:8899".to_string(),
  3356. }
  3357. }
  3358. // Setup and return paths to the solana-test-validator ledger directory and log
  3359. // files given the configuration
  3360. fn test_validator_file_paths(test_validator: &Option<TestValidator>) -> Result<(PathBuf, PathBuf)> {
  3361. let ledger_path = match test_validator {
  3362. Some(TestValidator {
  3363. validator: Some(validator),
  3364. ..
  3365. }) => &validator.ledger,
  3366. _ => DEFAULT_LEDGER_PATH,
  3367. };
  3368. let ledger_path = Path::new(ledger_path);
  3369. if !ledger_path.is_relative() {
  3370. // Prevent absolute paths to avoid someone using / or similar, as the
  3371. // directory gets removed
  3372. eprintln!("Ledger directory {ledger_path:?} must be relative");
  3373. std::process::exit(1);
  3374. }
  3375. if ledger_path.exists() {
  3376. fs::remove_dir_all(ledger_path)?;
  3377. }
  3378. fs::create_dir_all(ledger_path)?;
  3379. Ok((
  3380. ledger_path.to_owned(),
  3381. ledger_path.join("test-ledger-log.txt"),
  3382. ))
  3383. }
  3384. fn cluster_url(cfg: &Config, test_validator: &Option<TestValidator>) -> String {
  3385. let is_localnet = cfg.provider.cluster == Cluster::Localnet;
  3386. match is_localnet {
  3387. // Cluster is Localnet, assume the intent is to use the configuration
  3388. // for solana-test-validator
  3389. true => test_validator_rpc_url(test_validator),
  3390. false => cfg.provider.cluster.url().to_string(),
  3391. }
  3392. }
  3393. fn clean(cfg_override: &ConfigOverride) -> Result<()> {
  3394. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  3395. let cfg_parent = cfg.path().parent().expect("Invalid Anchor.toml");
  3396. let target_dir = cfg_parent.join("target");
  3397. let deploy_dir = target_dir.join("deploy");
  3398. if target_dir.exists() {
  3399. for entry in fs::read_dir(target_dir)? {
  3400. let path = entry?.path();
  3401. if path.is_dir() && path != deploy_dir {
  3402. fs::remove_dir_all(&path)
  3403. .map_err(|e| anyhow!("Could not remove directory {}: {}", path.display(), e))?;
  3404. } else if path.is_file() {
  3405. fs::remove_file(&path)
  3406. .map_err(|e| anyhow!("Could not remove file {}: {}", path.display(), e))?;
  3407. }
  3408. }
  3409. } else {
  3410. println!("skipping target directory: not found")
  3411. }
  3412. if deploy_dir.exists() {
  3413. for file in fs::read_dir(deploy_dir)? {
  3414. let path = file?.path();
  3415. if path.extension() != Some(&OsString::from("json")) {
  3416. fs::remove_file(&path)
  3417. .map_err(|e| anyhow!("Could not remove file {}: {}", path.display(), e))?;
  3418. }
  3419. }
  3420. } else {
  3421. println!("skipping deploy directory: not found")
  3422. }
  3423. Ok(())
  3424. }
  3425. fn deploy(
  3426. cfg_override: &ConfigOverride,
  3427. program_name: Option<String>,
  3428. program_keypair: Option<String>,
  3429. verifiable: bool,
  3430. solana_args: Vec<String>,
  3431. ) -> Result<()> {
  3432. // Execute the code within the workspace
  3433. with_workspace(cfg_override, |cfg| {
  3434. let url = cluster_url(cfg, &cfg.test_validator);
  3435. let keypair = cfg.provider.wallet.to_string();
  3436. // Deploy the programs.
  3437. println!("Deploying cluster: {}", url);
  3438. println!("Upgrade authority: {}", keypair);
  3439. for mut program in cfg.get_programs(program_name)? {
  3440. let binary_path = program.binary_path(verifiable).display().to_string();
  3441. println!("Deploying program {:?}...", program.lib_name);
  3442. println!("Program path: {}...", binary_path);
  3443. let (program_keypair_filepath, program_id) = match &program_keypair {
  3444. Some(path) => (path.clone(), get_keypair(path)?.pubkey()),
  3445. None => (
  3446. program.keypair_file()?.path().display().to_string(),
  3447. program.pubkey()?,
  3448. ),
  3449. };
  3450. // Send deploy transactions using the Solana CLI
  3451. let exit = std::process::Command::new("solana")
  3452. .arg("program")
  3453. .arg("deploy")
  3454. .arg("--url")
  3455. .arg(&url)
  3456. .arg("--keypair")
  3457. .arg(&keypair)
  3458. .arg("--program-id")
  3459. .arg(strip_workspace_prefix(program_keypair_filepath))
  3460. .arg(strip_workspace_prefix(binary_path))
  3461. .args(&solana_args)
  3462. .stdout(Stdio::inherit())
  3463. .stderr(Stdio::inherit())
  3464. .output()
  3465. .expect("Must deploy");
  3466. // Check if deployment was successful
  3467. if !exit.status.success() {
  3468. println!("There was a problem deploying: {exit:?}.");
  3469. std::process::exit(exit.status.code().unwrap_or(1));
  3470. }
  3471. if let Some(idl) = program.idl.as_mut() {
  3472. // Add program address to the IDL.
  3473. idl.address = program_id.to_string();
  3474. // Persist it.
  3475. let idl_out = PathBuf::from("target/idl")
  3476. .join(&idl.metadata.name)
  3477. .with_extension("json");
  3478. write_idl(idl, OutFile::File(idl_out))?;
  3479. }
  3480. }
  3481. println!("Deploy success");
  3482. Ok(())
  3483. })
  3484. }
  3485. fn upgrade(
  3486. cfg_override: &ConfigOverride,
  3487. program_id: Pubkey,
  3488. program_filepath: String,
  3489. solana_args: Vec<String>,
  3490. ) -> Result<()> {
  3491. let path: PathBuf = program_filepath.parse().unwrap();
  3492. let program_filepath = path.canonicalize()?.display().to_string();
  3493. with_workspace(cfg_override, |cfg| {
  3494. let url = cluster_url(cfg, &cfg.test_validator);
  3495. let exit = std::process::Command::new("solana")
  3496. .arg("program")
  3497. .arg("deploy")
  3498. .arg("--url")
  3499. .arg(url)
  3500. .arg("--keypair")
  3501. .arg(cfg.provider.wallet.to_string())
  3502. .arg("--program-id")
  3503. .arg(strip_workspace_prefix(program_id.to_string()))
  3504. .arg(strip_workspace_prefix(program_filepath))
  3505. .args(&solana_args)
  3506. .stdout(Stdio::inherit())
  3507. .stderr(Stdio::inherit())
  3508. .output()
  3509. .expect("Must deploy");
  3510. if !exit.status.success() {
  3511. println!("There was a problem deploying: {exit:?}.");
  3512. std::process::exit(exit.status.code().unwrap_or(1));
  3513. }
  3514. Ok(())
  3515. })
  3516. }
  3517. fn create_idl_account(
  3518. cfg: &Config,
  3519. keypair_path: &str,
  3520. program_id: &Pubkey,
  3521. idl: &Idl,
  3522. priority_fee: Option<u64>,
  3523. ) -> Result<Pubkey> {
  3524. // Misc.
  3525. let idl_address = IdlAccount::address(program_id);
  3526. let keypair = get_keypair(keypair_path)?;
  3527. let url = cluster_url(cfg, &cfg.test_validator);
  3528. let client = create_client(url);
  3529. let idl_data = serialize_idl(idl)?;
  3530. // Run `Create instruction.
  3531. {
  3532. let pda_max_growth = 60_000;
  3533. let idl_header_size = 44;
  3534. let idl_data_len = idl_data.len() as u64;
  3535. // We're only going to support up to 6 instructions in one transaction
  3536. // because will anyone really have a >60kb IDL?
  3537. if idl_data_len > pda_max_growth {
  3538. return Err(anyhow!(
  3539. "Your IDL is over 60kb and this isn't supported right now"
  3540. ));
  3541. }
  3542. // Double for future growth.
  3543. let data_len = (idl_data_len * 2).min(pda_max_growth - idl_header_size);
  3544. let num_additional_instructions = data_len / 10000;
  3545. let mut instructions = Vec::new();
  3546. let data = serialize_idl_ix(anchor_lang::idl::IdlInstruction::Create { data_len })?;
  3547. let program_signer = Pubkey::find_program_address(&[], program_id).0;
  3548. let accounts = vec![
  3549. AccountMeta::new_readonly(keypair.pubkey(), true),
  3550. AccountMeta::new(idl_address, false),
  3551. AccountMeta::new_readonly(program_signer, false),
  3552. AccountMeta::new_readonly(solana_program::system_program::ID, false),
  3553. AccountMeta::new_readonly(*program_id, false),
  3554. AccountMeta::new_readonly(solana_program::sysvar::rent::ID, false),
  3555. ];
  3556. instructions.push(Instruction {
  3557. program_id: *program_id,
  3558. accounts,
  3559. data,
  3560. });
  3561. for _ in 0..num_additional_instructions {
  3562. let data = serialize_idl_ix(anchor_lang::idl::IdlInstruction::Resize { data_len })?;
  3563. instructions.push(Instruction {
  3564. program_id: *program_id,
  3565. accounts: vec![
  3566. AccountMeta::new(idl_address, false),
  3567. AccountMeta::new_readonly(keypair.pubkey(), true),
  3568. AccountMeta::new_readonly(solana_program::system_program::ID, false),
  3569. ],
  3570. data,
  3571. });
  3572. }
  3573. instructions = prepend_compute_unit_ix(instructions, &client, priority_fee)?;
  3574. let mut latest_hash = client.get_latest_blockhash()?;
  3575. for retries in 0..20 {
  3576. if !client.is_blockhash_valid(&latest_hash, client.commitment())? {
  3577. latest_hash = client.get_latest_blockhash()?;
  3578. }
  3579. let tx = Transaction::new_signed_with_payer(
  3580. &instructions,
  3581. Some(&keypair.pubkey()),
  3582. &[&keypair],
  3583. latest_hash,
  3584. );
  3585. match client.send_and_confirm_transaction_with_spinner(&tx) {
  3586. Ok(_) => break,
  3587. Err(err) => {
  3588. if retries == 19 {
  3589. return Err(anyhow!("Error creating IDL account: {}", err));
  3590. }
  3591. println!("Error creating IDL account: {}. Retrying...", err);
  3592. }
  3593. }
  3594. }
  3595. }
  3596. // Write directly to the IDL account buffer.
  3597. idl_write(
  3598. cfg,
  3599. program_id,
  3600. idl,
  3601. IdlAccount::address(program_id),
  3602. priority_fee,
  3603. )?;
  3604. Ok(idl_address)
  3605. }
  3606. fn create_idl_buffer(
  3607. cfg: &Config,
  3608. keypair_path: &str,
  3609. program_id: &Pubkey,
  3610. idl: &Idl,
  3611. priority_fee: Option<u64>,
  3612. ) -> Result<Pubkey> {
  3613. let keypair = get_keypair(keypair_path)?;
  3614. let url = cluster_url(cfg, &cfg.test_validator);
  3615. let client = create_client(url);
  3616. let buffer = Keypair::new();
  3617. // Creates the new buffer account with the system program.
  3618. let create_account_ix = {
  3619. let space = IdlAccount::DISCRIMINATOR.len() + 32 + 4 + serialize_idl(idl)?.len();
  3620. let lamports = client.get_minimum_balance_for_rent_exemption(space)?;
  3621. solana_sdk::system_instruction::create_account(
  3622. &keypair.pubkey(),
  3623. &buffer.pubkey(),
  3624. lamports,
  3625. space as u64,
  3626. program_id,
  3627. )
  3628. };
  3629. // Program instruction to create the buffer.
  3630. let create_buffer_ix = {
  3631. let accounts = vec![
  3632. AccountMeta::new(buffer.pubkey(), false),
  3633. AccountMeta::new_readonly(keypair.pubkey(), true),
  3634. AccountMeta::new_readonly(sysvar::rent::ID, false),
  3635. ];
  3636. let mut data = anchor_lang::idl::IDL_IX_TAG.to_le_bytes().to_vec();
  3637. data.append(&mut IdlInstruction::CreateBuffer.try_to_vec()?);
  3638. Instruction {
  3639. program_id: *program_id,
  3640. accounts,
  3641. data,
  3642. }
  3643. };
  3644. let instructions = prepend_compute_unit_ix(
  3645. vec![create_account_ix, create_buffer_ix],
  3646. &client,
  3647. priority_fee,
  3648. )?;
  3649. let mut latest_hash = client.get_latest_blockhash()?;
  3650. for retries in 0..20 {
  3651. if !client.is_blockhash_valid(&latest_hash, client.commitment())? {
  3652. latest_hash = client.get_latest_blockhash()?;
  3653. }
  3654. let tx = Transaction::new_signed_with_payer(
  3655. &instructions,
  3656. Some(&keypair.pubkey()),
  3657. &[&keypair, &buffer],
  3658. latest_hash,
  3659. );
  3660. match client.send_and_confirm_transaction_with_spinner(&tx) {
  3661. Ok(_) => break,
  3662. Err(err) => {
  3663. if retries == 19 {
  3664. return Err(anyhow!("Error creating buffer account: {}", err));
  3665. }
  3666. println!("Error creating buffer account: {}. Retrying...", err);
  3667. }
  3668. }
  3669. }
  3670. Ok(buffer.pubkey())
  3671. }
  3672. // Serialize and compress the idl.
  3673. fn serialize_idl(idl: &Idl) -> Result<Vec<u8>> {
  3674. let json_bytes = serde_json::to_vec(idl)?;
  3675. let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
  3676. e.write_all(&json_bytes)?;
  3677. e.finish().map_err(Into::into)
  3678. }
  3679. fn serialize_idl_ix(ix_inner: anchor_lang::idl::IdlInstruction) -> Result<Vec<u8>> {
  3680. let mut data = Vec::with_capacity(256);
  3681. data.extend_from_slice(&anchor_lang::idl::IDL_IX_TAG.to_le_bytes());
  3682. ix_inner.serialize(&mut data)?;
  3683. Ok(data)
  3684. }
  3685. fn migrate(cfg_override: &ConfigOverride) -> Result<()> {
  3686. with_workspace(cfg_override, |cfg| {
  3687. println!("Running migration deploy script");
  3688. let url = cluster_url(cfg, &cfg.test_validator);
  3689. let cur_dir = std::env::current_dir()?;
  3690. let migrations_dir = cur_dir.join("migrations");
  3691. let deploy_ts = Path::new("deploy.ts");
  3692. let use_ts = Path::new("tsconfig.json").exists() && migrations_dir.join(deploy_ts).exists();
  3693. if !Path::new(".anchor").exists() {
  3694. fs::create_dir(".anchor")?;
  3695. }
  3696. std::env::set_current_dir(".anchor")?;
  3697. let exit = if use_ts {
  3698. let module_path = migrations_dir.join(deploy_ts);
  3699. let deploy_script_host_str =
  3700. rust_template::deploy_ts_script_host(&url, &module_path.display().to_string());
  3701. fs::write(deploy_ts, deploy_script_host_str)?;
  3702. std::process::Command::new("yarn")
  3703. .args([
  3704. "run",
  3705. "ts-node",
  3706. &fs::canonicalize(deploy_ts)?.to_string_lossy(),
  3707. ])
  3708. .env("ANCHOR_WALLET", cfg.provider.wallet.to_string())
  3709. .stdout(Stdio::inherit())
  3710. .stderr(Stdio::inherit())
  3711. .output()?
  3712. } else {
  3713. let deploy_js = deploy_ts.with_extension("js");
  3714. let module_path = migrations_dir.join(&deploy_js);
  3715. let deploy_script_host_str =
  3716. rust_template::deploy_js_script_host(&url, &module_path.display().to_string());
  3717. fs::write(&deploy_js, deploy_script_host_str)?;
  3718. std::process::Command::new("node")
  3719. .arg(&deploy_js)
  3720. .env("ANCHOR_WALLET", cfg.provider.wallet.to_string())
  3721. .stdout(Stdio::inherit())
  3722. .stderr(Stdio::inherit())
  3723. .output()?
  3724. };
  3725. if !exit.status.success() {
  3726. eprintln!("Deploy failed.");
  3727. std::process::exit(exit.status.code().unwrap());
  3728. }
  3729. println!("Deploy complete.");
  3730. Ok(())
  3731. })
  3732. }
  3733. fn set_workspace_dir_or_exit() {
  3734. let d = match Config::discover(&ConfigOverride::default()) {
  3735. Err(err) => {
  3736. println!("Workspace configuration error: {err}");
  3737. std::process::exit(1);
  3738. }
  3739. Ok(d) => d,
  3740. };
  3741. match d {
  3742. None => {
  3743. println!("Not in anchor workspace.");
  3744. std::process::exit(1);
  3745. }
  3746. Some(cfg) => {
  3747. match cfg.path().parent() {
  3748. None => {
  3749. println!("Unable to make new program");
  3750. }
  3751. Some(parent) => {
  3752. if std::env::set_current_dir(parent).is_err() {
  3753. println!("Not in anchor workspace.");
  3754. std::process::exit(1);
  3755. }
  3756. }
  3757. };
  3758. }
  3759. }
  3760. }
  3761. #[cfg(feature = "dev")]
  3762. fn airdrop(cfg_override: &ConfigOverride) -> Result<()> {
  3763. let url = cfg_override
  3764. .cluster
  3765. .as_ref()
  3766. .unwrap_or_else(|| &Cluster::Devnet)
  3767. .url();
  3768. loop {
  3769. let exit = std::process::Command::new("solana")
  3770. .arg("airdrop")
  3771. .arg("10")
  3772. .arg("--url")
  3773. .arg(&url)
  3774. .stdout(Stdio::inherit())
  3775. .stderr(Stdio::inherit())
  3776. .output()
  3777. .expect("Must airdrop");
  3778. if !exit.status.success() {
  3779. println!("There was a problem airdropping: {:?}.", exit);
  3780. std::process::exit(exit.status.code().unwrap_or(1));
  3781. }
  3782. std::thread::sleep(std::time::Duration::from_millis(10000));
  3783. }
  3784. }
  3785. fn cluster(_cmd: ClusterCommand) -> Result<()> {
  3786. println!("Cluster Endpoints:\n");
  3787. println!("* Mainnet - https://api.mainnet-beta.solana.com");
  3788. println!("* Devnet - https://api.devnet.solana.com");
  3789. println!("* Testnet - https://api.testnet.solana.com");
  3790. Ok(())
  3791. }
  3792. fn shell(cfg_override: &ConfigOverride) -> Result<()> {
  3793. with_workspace(cfg_override, |cfg| {
  3794. let programs = {
  3795. // Create idl map from all workspace programs.
  3796. let mut idls: HashMap<String, Idl> = cfg
  3797. .read_all_programs()?
  3798. .iter()
  3799. .filter(|program| program.idl.is_some())
  3800. .map(|program| {
  3801. (
  3802. program.idl.as_ref().unwrap().metadata.name.clone(),
  3803. program.idl.clone().unwrap(),
  3804. )
  3805. })
  3806. .collect();
  3807. // Insert all manually specified idls into the idl map.
  3808. if let Some(programs) = cfg.programs.get(&cfg.provider.cluster) {
  3809. let _ = programs
  3810. .iter()
  3811. .map(|(name, pd)| {
  3812. if let Some(idl_fp) = &pd.idl {
  3813. let file_str =
  3814. fs::read_to_string(idl_fp).expect("Unable to read IDL file");
  3815. let idl = serde_json::from_str(&file_str).expect("Idl not readable");
  3816. idls.insert(name.clone(), idl);
  3817. }
  3818. })
  3819. .collect::<Vec<_>>();
  3820. }
  3821. // Finalize program list with all programs with IDLs.
  3822. match cfg.programs.get(&cfg.provider.cluster) {
  3823. None => Vec::new(),
  3824. Some(programs) => programs
  3825. .iter()
  3826. .filter_map(|(name, program_deployment)| {
  3827. Some(ProgramWorkspace {
  3828. name: name.to_string(),
  3829. program_id: program_deployment.address,
  3830. idl: match idls.get(name) {
  3831. None => return None,
  3832. Some(idl) => idl.clone(),
  3833. },
  3834. })
  3835. })
  3836. .collect::<Vec<ProgramWorkspace>>(),
  3837. }
  3838. };
  3839. let url = cluster_url(cfg, &cfg.test_validator);
  3840. let js_code = rust_template::node_shell(&url, &cfg.provider.wallet.to_string(), programs)?;
  3841. let mut child = std::process::Command::new("node")
  3842. .args(["-e", &js_code, "-i", "--experimental-repl-await"])
  3843. .stdout(Stdio::inherit())
  3844. .stderr(Stdio::inherit())
  3845. .spawn()
  3846. .map_err(|e| anyhow::format_err!("{}", e.to_string()))?;
  3847. if !child.wait()?.success() {
  3848. println!("Error running node shell");
  3849. return Ok(());
  3850. }
  3851. Ok(())
  3852. })
  3853. }
  3854. fn run(cfg_override: &ConfigOverride, script: String, script_args: Vec<String>) -> Result<()> {
  3855. with_workspace(cfg_override, |cfg| {
  3856. let url = cluster_url(cfg, &cfg.test_validator);
  3857. let script = cfg
  3858. .scripts
  3859. .get(&script)
  3860. .ok_or_else(|| anyhow!("Unable to find script"))?;
  3861. let script_with_args = format!("{script} {}", script_args.join(" "));
  3862. let exit = std::process::Command::new("bash")
  3863. .arg("-c")
  3864. .arg(&script_with_args)
  3865. .env("ANCHOR_PROVIDER_URL", url)
  3866. .env("ANCHOR_WALLET", cfg.provider.wallet.to_string())
  3867. .stdout(Stdio::inherit())
  3868. .stderr(Stdio::inherit())
  3869. .output()
  3870. .unwrap();
  3871. if !exit.status.success() {
  3872. std::process::exit(exit.status.code().unwrap_or(1));
  3873. }
  3874. Ok(())
  3875. })
  3876. }
  3877. fn login(_cfg_override: &ConfigOverride, token: String) -> Result<()> {
  3878. let dir = shellexpand::tilde("~/.config/anchor");
  3879. if !Path::new(&dir.to_string()).exists() {
  3880. fs::create_dir(dir.to_string())?;
  3881. }
  3882. std::env::set_current_dir(dir.to_string())?;
  3883. // Freely overwrite the entire file since it's not used for anything else.
  3884. let mut file = File::create("credentials")?;
  3885. file.write_all(rust_template::credentials(&token).as_bytes())?;
  3886. Ok(())
  3887. }
  3888. fn publish(
  3889. cfg_override: &ConfigOverride,
  3890. program_name: String,
  3891. env_vars: Vec<String>,
  3892. cargo_args: Vec<String>,
  3893. skip_build: bool,
  3894. arch: ProgramArch,
  3895. ) -> Result<()> {
  3896. // Discover the various workspace configs.
  3897. let cfg = Config::discover(cfg_override)?.expect("Not in workspace.");
  3898. let program = cfg.get_program(&program_name)?;
  3899. let program_cargo_lock = pathdiff::diff_paths(
  3900. program.path.join("Cargo.lock"),
  3901. cfg.path().parent().unwrap(),
  3902. )
  3903. .ok_or_else(|| anyhow!("Unable to diff Cargo.lock path"))?;
  3904. let cargo_lock = Path::new("Cargo.lock");
  3905. // There must be a Cargo.lock
  3906. if !program_cargo_lock.exists() && !cargo_lock.exists() {
  3907. return Err(anyhow!("Cargo.lock must exist for a verifiable build"));
  3908. }
  3909. println!("Publishing will make your code public. Are you sure? Enter (yes)/no:");
  3910. let answer = std::io::stdin().lock().lines().next().unwrap().unwrap();
  3911. if answer != "yes" {
  3912. println!("Aborting");
  3913. return Ok(());
  3914. }
  3915. let anchor_package = AnchorPackage::from(program_name.clone(), &cfg)?;
  3916. let anchor_package_bytes = serde_json::to_vec(&anchor_package)?;
  3917. // Set directory to top of the workspace.
  3918. let workspace_dir = cfg.path().parent().unwrap();
  3919. std::env::set_current_dir(workspace_dir)?;
  3920. // Create the workspace tarball.
  3921. let dot_anchor = workspace_dir.join(".anchor");
  3922. fs::create_dir_all(&dot_anchor)?;
  3923. let tarball_filename = dot_anchor.join(format!("{program_name}.tar.gz"));
  3924. let tar_gz = File::create(&tarball_filename)?;
  3925. let enc = GzEncoder::new(tar_gz, Compression::default());
  3926. let mut tar = tar::Builder::new(enc);
  3927. // Files that will always be included if they exist.
  3928. println!("PACKING: Anchor.toml");
  3929. tar.append_path("Anchor.toml")?;
  3930. if cargo_lock.exists() {
  3931. println!("PACKING: Cargo.lock");
  3932. tar.append_path(cargo_lock)?;
  3933. }
  3934. if Path::new("Cargo.toml").exists() {
  3935. println!("PACKING: Cargo.toml");
  3936. tar.append_path("Cargo.toml")?;
  3937. }
  3938. if Path::new("LICENSE").exists() {
  3939. println!("PACKING: LICENSE");
  3940. tar.append_path("LICENSE")?;
  3941. }
  3942. if Path::new("README.md").exists() {
  3943. println!("PACKING: README.md");
  3944. tar.append_path("README.md")?;
  3945. }
  3946. if Path::new("idl.json").exists() {
  3947. println!("PACKING: idl.json");
  3948. tar.append_path("idl.json")?;
  3949. }
  3950. // All workspace programs.
  3951. for path in cfg.get_rust_program_list()? {
  3952. let mut dirs = walkdir::WalkDir::new(path)
  3953. .into_iter()
  3954. .filter_entry(|e| !is_hidden(e));
  3955. // Skip the parent dir.
  3956. let _ = dirs.next().unwrap()?;
  3957. for entry in dirs {
  3958. let e = entry.map_err(|e| anyhow!("{:?}", e))?;
  3959. let e = pathdiff::diff_paths(e.path(), cfg.path().parent().unwrap())
  3960. .ok_or_else(|| anyhow!("Unable to diff paths"))?;
  3961. let path_str = e.display().to_string();
  3962. // Skip target dir.
  3963. if !path_str.contains("target/") && !path_str.contains("/target") {
  3964. // Only add the file if it's not empty.
  3965. let metadata = fs::File::open(&e)?.metadata()?;
  3966. if metadata.len() > 0 {
  3967. println!("PACKING: {}", e.display());
  3968. if e.is_dir() {
  3969. tar.append_dir_all(&e, &e)?;
  3970. } else {
  3971. tar.append_path(&e)?;
  3972. }
  3973. }
  3974. }
  3975. }
  3976. }
  3977. // Tar pack complete.
  3978. tar.into_inner()?;
  3979. // Create tmp directory for workspace.
  3980. let ws_dir = dot_anchor.join("workspace");
  3981. if Path::exists(&ws_dir) {
  3982. fs::remove_dir_all(&ws_dir)?;
  3983. }
  3984. fs::create_dir_all(&ws_dir)?;
  3985. // Unpack the archive into the new workspace directory.
  3986. std::env::set_current_dir(&ws_dir)?;
  3987. unpack_archive(&tarball_filename)?;
  3988. // Build the program before sending it to the server.
  3989. if !skip_build {
  3990. build(
  3991. cfg_override,
  3992. false,
  3993. None,
  3994. None,
  3995. true,
  3996. false,
  3997. Some(program_name),
  3998. None,
  3999. None,
  4000. BootstrapMode::None,
  4001. None,
  4002. None,
  4003. env_vars,
  4004. cargo_args,
  4005. true,
  4006. arch,
  4007. )?;
  4008. }
  4009. // Upload the tarball to the server.
  4010. let token = registry_api_token(cfg_override)?;
  4011. let form = Form::new()
  4012. .part("manifest", Part::bytes(anchor_package_bytes))
  4013. .part("workspace", {
  4014. let file = File::open(&tarball_filename)?;
  4015. Part::reader(file)
  4016. });
  4017. let client = Client::new();
  4018. let resp = client
  4019. .post(format!("{}/api/v0/build", cfg.registry.url))
  4020. .bearer_auth(token)
  4021. .multipart(form)
  4022. .send()?;
  4023. if resp.status() == 200 {
  4024. println!("Build triggered");
  4025. } else {
  4026. println!(
  4027. "{:?}",
  4028. resp.text().unwrap_or_else(|_| "Server error".to_string())
  4029. );
  4030. }
  4031. Ok(())
  4032. }
  4033. // Unpacks the tarball into the current directory.
  4034. fn unpack_archive(tar_path: impl AsRef<Path>) -> Result<()> {
  4035. let tar = GzDecoder::new(std::fs::File::open(tar_path)?);
  4036. let mut archive = Archive::new(tar);
  4037. archive.unpack(".")?;
  4038. archive.into_inner();
  4039. Ok(())
  4040. }
  4041. fn registry_api_token(_cfg_override: &ConfigOverride) -> Result<String> {
  4042. #[derive(Debug, Deserialize)]
  4043. struct Registry {
  4044. token: String,
  4045. }
  4046. #[derive(Debug, Deserialize)]
  4047. struct Credentials {
  4048. registry: Registry,
  4049. }
  4050. let filename = shellexpand::tilde("~/.config/anchor/credentials");
  4051. let mut file = File::open(filename.to_string())?;
  4052. let mut contents = String::new();
  4053. file.read_to_string(&mut contents)?;
  4054. let credentials_toml: Credentials = toml::from_str(&contents)?;
  4055. Ok(credentials_toml.registry.token)
  4056. }
  4057. fn keys(cfg_override: &ConfigOverride, cmd: KeysCommand) -> Result<()> {
  4058. match cmd {
  4059. KeysCommand::List => keys_list(cfg_override),
  4060. KeysCommand::Sync { program_name } => keys_sync(cfg_override, program_name),
  4061. }
  4062. }
  4063. fn keys_list(cfg_override: &ConfigOverride) -> Result<()> {
  4064. with_workspace(cfg_override, |cfg| {
  4065. for program in cfg.read_all_programs()? {
  4066. let pubkey = program.pubkey()?;
  4067. println!("{}: {}", program.lib_name, pubkey);
  4068. }
  4069. Ok(())
  4070. })
  4071. }
  4072. /// Sync the program's `declare_id!` pubkey with the pubkey from `target/deploy/<KEYPAIR>.json`.
  4073. fn keys_sync(cfg_override: &ConfigOverride, program_name: Option<String>) -> Result<()> {
  4074. with_workspace(cfg_override, |cfg| {
  4075. let declare_id_regex = RegexBuilder::new(r#"^(([\w]+::)*)declare_id!\("(\w*)"\)"#)
  4076. .multi_line(true)
  4077. .build()
  4078. .unwrap();
  4079. for program in cfg.get_programs(program_name)? {
  4080. // Get the pubkey from the keypair file
  4081. let actual_program_id = program.pubkey()?.to_string();
  4082. // Handle declaration in program files
  4083. let src_path = program.path.join("src");
  4084. let files_to_check = vec![src_path.join("lib.rs"), src_path.join("id.rs")];
  4085. for path in files_to_check {
  4086. let mut content = match fs::read_to_string(&path) {
  4087. Ok(content) => content,
  4088. Err(_) => continue,
  4089. };
  4090. let incorrect_program_id = declare_id_regex
  4091. .captures(&content)
  4092. .and_then(|captures| captures.get(3))
  4093. .filter(|program_id_match| program_id_match.as_str() != actual_program_id);
  4094. if let Some(program_id_match) = incorrect_program_id {
  4095. println!("Found incorrect program id declaration in {path:?}");
  4096. // Update the program id
  4097. content.replace_range(program_id_match.range(), &actual_program_id);
  4098. fs::write(&path, content)?;
  4099. println!("Updated to {actual_program_id}\n");
  4100. break;
  4101. }
  4102. }
  4103. // Handle declaration in Anchor.toml
  4104. 'outer: for programs in cfg.programs.values_mut() {
  4105. for (name, deployment) in programs {
  4106. // Skip other programs
  4107. if name != &program.lib_name {
  4108. continue;
  4109. }
  4110. if deployment.address.to_string() != actual_program_id {
  4111. println!("Found incorrect program id declaration in Anchor.toml for the program `{name}`");
  4112. // Update the program id
  4113. deployment.address = Pubkey::from_str(&actual_program_id).unwrap();
  4114. fs::write(cfg.path(), cfg.to_string())?;
  4115. println!("Updated to {actual_program_id}\n");
  4116. break 'outer;
  4117. }
  4118. }
  4119. }
  4120. }
  4121. println!("All program id declarations are synced.");
  4122. Ok(())
  4123. })
  4124. }
  4125. fn localnet(
  4126. cfg_override: &ConfigOverride,
  4127. skip_build: bool,
  4128. skip_deploy: bool,
  4129. skip_lint: bool,
  4130. env_vars: Vec<String>,
  4131. cargo_args: Vec<String>,
  4132. arch: ProgramArch,
  4133. ) -> Result<()> {
  4134. with_workspace(cfg_override, |cfg| {
  4135. // Build if needed.
  4136. if !skip_build {
  4137. build(
  4138. cfg_override,
  4139. false,
  4140. None,
  4141. None,
  4142. false,
  4143. skip_lint,
  4144. None,
  4145. None,
  4146. None,
  4147. BootstrapMode::None,
  4148. None,
  4149. None,
  4150. env_vars,
  4151. cargo_args,
  4152. false,
  4153. arch,
  4154. )?;
  4155. }
  4156. let flags = match skip_deploy {
  4157. true => None,
  4158. false => Some(validator_flags(cfg, &cfg.test_validator)?),
  4159. };
  4160. let validator_handle = &mut start_test_validator(cfg, &cfg.test_validator, flags, false)?;
  4161. // Setup log reader.
  4162. let url = test_validator_rpc_url(&cfg.test_validator);
  4163. let log_streams = stream_logs(cfg, &url);
  4164. std::io::stdin().lock().lines().next().unwrap().unwrap();
  4165. // Check all errors and shut down.
  4166. if let Err(err) = validator_handle.kill() {
  4167. println!(
  4168. "Failed to kill subprocess {}: {}",
  4169. validator_handle.id(),
  4170. err
  4171. );
  4172. }
  4173. for mut child in log_streams? {
  4174. if let Err(err) = child.kill() {
  4175. println!("Failed to kill subprocess {}: {}", child.id(), err);
  4176. }
  4177. }
  4178. Ok(())
  4179. })
  4180. }
  4181. // with_workspace ensures the current working directory is always the top level
  4182. // workspace directory, i.e., where the `Anchor.toml` file is located, before
  4183. // and after the closure invocation.
  4184. //
  4185. // The closure passed into this function must never change the working directory
  4186. // to be outside the workspace. Doing so will have undefined behavior.
  4187. fn with_workspace<R>(
  4188. cfg_override: &ConfigOverride,
  4189. f: impl FnOnce(&mut WithPath<Config>) -> R,
  4190. ) -> R {
  4191. set_workspace_dir_or_exit();
  4192. let mut cfg = Config::discover(cfg_override)
  4193. .expect("Previously set the workspace dir")
  4194. .expect("Anchor.toml must always exist");
  4195. let r = f(&mut cfg);
  4196. set_workspace_dir_or_exit();
  4197. r
  4198. }
  4199. fn is_hidden(entry: &walkdir::DirEntry) -> bool {
  4200. entry
  4201. .file_name()
  4202. .to_str()
  4203. .map(|s| s == "." || s.starts_with('.') || s == "target")
  4204. .unwrap_or(false)
  4205. }
  4206. fn get_node_version() -> Result<Version> {
  4207. let node_version = std::process::Command::new("node")
  4208. .arg("--version")
  4209. .stderr(Stdio::inherit())
  4210. .output()
  4211. .map_err(|e| anyhow::format_err!("node failed: {}", e.to_string()))?;
  4212. let output = std::str::from_utf8(&node_version.stdout)?
  4213. .strip_prefix('v')
  4214. .unwrap()
  4215. .trim();
  4216. Version::parse(output).map_err(Into::into)
  4217. }
  4218. fn get_recommended_micro_lamport_fee(client: &RpcClient, priority_fee: Option<u64>) -> Result<u64> {
  4219. if let Some(priority_fee) = priority_fee {
  4220. return Ok(priority_fee);
  4221. }
  4222. let mut fees = client.get_recent_prioritization_fees(&[])?;
  4223. // Get the median fee from the most recent recent 150 slots' prioritization fee
  4224. fees.sort_unstable_by_key(|fee| fee.prioritization_fee);
  4225. let median_index = fees.len() / 2;
  4226. let median_priority_fee = if fees.len() % 2 == 0 {
  4227. (fees[median_index - 1].prioritization_fee + fees[median_index].prioritization_fee) / 2
  4228. } else {
  4229. fees[median_index].prioritization_fee
  4230. };
  4231. Ok(median_priority_fee)
  4232. }
  4233. /// Prepend a compute unit ix, if the priority fee is greater than 0.
  4234. /// This helps to improve the chances that the transaction will land.
  4235. fn prepend_compute_unit_ix(
  4236. instructions: Vec<Instruction>,
  4237. client: &RpcClient,
  4238. priority_fee: Option<u64>,
  4239. ) -> Result<Vec<Instruction>> {
  4240. let priority_fee = get_recommended_micro_lamport_fee(client, priority_fee)?;
  4241. if priority_fee > 0 {
  4242. let mut instructions_appended = instructions.clone();
  4243. instructions_appended.insert(
  4244. 0,
  4245. ComputeBudgetInstruction::set_compute_unit_price(priority_fee),
  4246. );
  4247. Ok(instructions_appended)
  4248. } else {
  4249. Ok(instructions)
  4250. }
  4251. }
  4252. fn get_node_dns_option() -> Result<&'static str> {
  4253. let version = get_node_version()?;
  4254. let req = VersionReq::parse(">=16.4.0").unwrap();
  4255. let option = match req.matches(&version) {
  4256. true => "--dns-result-order=ipv4first",
  4257. false => "",
  4258. };
  4259. Ok(option)
  4260. }
  4261. // Remove the current workspace directory if it prefixes a string.
  4262. // This is used as a workaround for the Solana CLI using the uriparse crate to
  4263. // parse args but not handling percent encoding/decoding when using the path as
  4264. // a local filesystem path. Removing the workspace prefix handles most/all cases
  4265. // of spaces in keypair/binary paths, but this should be fixed in the Solana CLI
  4266. // and removed here.
  4267. fn strip_workspace_prefix(absolute_path: String) -> String {
  4268. let workspace_prefix = std::env::current_dir().unwrap().display().to_string() + "/";
  4269. absolute_path
  4270. .strip_prefix(&workspace_prefix)
  4271. .unwrap_or(&absolute_path)
  4272. .into()
  4273. }
  4274. /// Create a new [`RpcClient`] with `confirmed` commitment level instead of the default(finalized).
  4275. fn create_client<U: ToString>(url: U) -> RpcClient {
  4276. RpcClient::new_with_commitment(url, CommitmentConfig::confirmed())
  4277. }
  4278. #[cfg(test)]
  4279. mod tests {
  4280. use super::*;
  4281. #[test]
  4282. #[should_panic(expected = "Anchor workspace name must be a valid Rust identifier.")]
  4283. fn test_init_reserved_word() {
  4284. init(
  4285. &ConfigOverride {
  4286. cluster: None,
  4287. wallet: None,
  4288. },
  4289. "await".to_string(),
  4290. true,
  4291. false,
  4292. true,
  4293. false,
  4294. ProgramTemplate::default(),
  4295. TestTemplate::default(),
  4296. false,
  4297. )
  4298. .unwrap();
  4299. }
  4300. #[test]
  4301. #[should_panic(expected = "Anchor workspace name must be a valid Rust identifier.")]
  4302. fn test_init_reserved_word_from_syn() {
  4303. init(
  4304. &ConfigOverride {
  4305. cluster: None,
  4306. wallet: None,
  4307. },
  4308. "fn".to_string(),
  4309. true,
  4310. false,
  4311. true,
  4312. false,
  4313. ProgramTemplate::default(),
  4314. TestTemplate::default(),
  4315. false,
  4316. )
  4317. .unwrap();
  4318. }
  4319. #[test]
  4320. #[should_panic(expected = "Anchor workspace name must be a valid Rust identifier.")]
  4321. fn test_init_starting_with_digit() {
  4322. init(
  4323. &ConfigOverride {
  4324. cluster: None,
  4325. wallet: None,
  4326. },
  4327. "1project".to_string(),
  4328. true,
  4329. false,
  4330. true,
  4331. false,
  4332. ProgramTemplate::default(),
  4333. TestTemplate::default(),
  4334. false,
  4335. )
  4336. .unwrap();
  4337. }
  4338. }