lib.rs 158 KB

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