interactive.rs 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. fs::{File, OpenOptions},
  20. io::{stdin, BufRead, BufReader, ErrorKind, Read, Seek, SeekFrom, Write},
  21. str::FromStr,
  22. };
  23. use futures::{select, FutureExt};
  24. use libc::{fcntl, F_GETFL, F_SETFL, O_NONBLOCK};
  25. use linenoise_rs::{
  26. linenoise_history_add, linenoise_history_load, linenoise_history_save,
  27. linenoise_set_completion_callback, linenoise_set_hints_callback, LinenoiseState,
  28. };
  29. use prettytable::{format, row, Table};
  30. use rand::rngs::OsRng;
  31. use smol::channel::{unbounded, Receiver, Sender};
  32. use url::Url;
  33. use darkfi::{
  34. cli_desc,
  35. system::{msleep, ExecutorPtr, StoppableTask, StoppableTaskPtr},
  36. util::{
  37. encoding::base64,
  38. parse::{decode_base10, encode_base10},
  39. path::expand_path,
  40. },
  41. zk::halo2::Field,
  42. Error,
  43. };
  44. use darkfi_dao_contract::{blockwindow, model::DaoProposalBulla, DaoFunction};
  45. use darkfi_money_contract::model::{Coin, CoinAttributes, TokenId};
  46. use darkfi_sdk::{
  47. crypto::{
  48. note::AeadEncryptedNote, BaseBlind, FuncId, FuncRef, Keypair, PublicKey, SecretKey,
  49. DAO_CONTRACT_ID,
  50. },
  51. pasta::{group::ff::PrimeField, pallas},
  52. tx::TransactionHash,
  53. };
  54. use darkfi_serial::{deserialize_async, serialize_async};
  55. use crate::{
  56. cli_util::{
  57. append_or_print, generate_completions, kaching, parse_token_pair, parse_tx_from_input,
  58. parse_value_pair, print_output,
  59. },
  60. dao::{DaoParams, ProposalRecord},
  61. money::BALANCE_BASE10_DECIMALS,
  62. rpc::subscribe_blocks,
  63. swap::PartialSwapData,
  64. DrkPtr,
  65. };
  66. // TODO:
  67. // 1. Create a transactions cache in the wallet db, so you can use it to handle them.
  68. /// Auxiliary function to print the help message.
  69. fn help(output: &mut Vec<String>) {
  70. output.push(String::from(cli_desc!()));
  71. output.push(String::from("Commands:"));
  72. output.push(String::from("\thelp: Prints the help message"));
  73. output.push(String::from("\tkaching: Fun"));
  74. output.push(String::from("\tping: Send a ping request to the darkfid RPC endpoint"));
  75. output.push(String::from(
  76. "\tcompletions: Generate a SHELL completion script and print to stdout",
  77. ));
  78. output.push(String::from("\twallet: Wallet operations"));
  79. output.push(String::from(
  80. "\tspend: Read a transaction from stdin and mark its input coins as spent",
  81. ));
  82. output.push(String::from("\tunspend: Unspend a coin"));
  83. output.push(String::from("\ttransfer: Create a payment transaction"));
  84. output.push(String::from("\totc: OTC atomic swap"));
  85. output.push(String::from("\tdao: DAO functionalities"));
  86. output
  87. .push(String::from("\tattach-fee: Attach the fee call to a transaction given from stdin"));
  88. output.push(String::from("\tinspect: Inspect a transaction from stdin"));
  89. output.push(String::from("\tbroadcast: Read a transaction from stdin and broadcast it"));
  90. output.push(String::from(
  91. "\tsubscribe: Perform a scan and then subscribe to darkfid to listen for incoming blocks",
  92. ));
  93. output.push(String::from("\tunsubscribe: Stops the background subscription, if its active"));
  94. output.push(String::from("\tsnooze: Disables the background subscription messages printing"));
  95. output.push(String::from("\tunsnooze: Enables the background subscription messages printing"));
  96. output.push(String::from("\tscan: Scan the blockchain and parse relevant transactions"));
  97. output.push(String::from("\texplorer: Explorer related subcommands"));
  98. output.push(String::from("\talias: Token alias"));
  99. output.push(String::from("\ttoken: Token functionalities"));
  100. output.push(String::from("\tcontract: Contract functionalities"));
  101. }
  102. /// Auxiliary function to define the interactive shell completions.
  103. fn completion(buffer: &str, lc: &mut Vec<String>) {
  104. // Split commands so we always process the last one
  105. let commands: Vec<&str> = buffer.split('|').collect();
  106. // Grab the prefix
  107. let prefix = if commands.len() > 1 {
  108. commands[..commands.len() - 1].join("|") + "| "
  109. } else {
  110. String::from("")
  111. };
  112. let last = commands.last().unwrap().trim_start();
  113. // First we define the specific commands prefixes
  114. if last.starts_with("h") {
  115. lc.push(prefix + "help");
  116. return
  117. }
  118. if last.starts_with("k") {
  119. lc.push(prefix + "kaching");
  120. return
  121. }
  122. if last.starts_with("p") {
  123. lc.push(prefix + "ping");
  124. return
  125. }
  126. if last.starts_with("com") {
  127. lc.push(prefix + "completions");
  128. return
  129. }
  130. if last.starts_with("w") {
  131. lc.push(prefix.clone() + "wallet");
  132. lc.push(prefix.clone() + "wallet initialize");
  133. lc.push(prefix.clone() + "wallet keygen");
  134. lc.push(prefix.clone() + "wallet balance");
  135. lc.push(prefix.clone() + "wallet address");
  136. lc.push(prefix.clone() + "wallet addresses");
  137. lc.push(prefix.clone() + "wallet default-address");
  138. lc.push(prefix.clone() + "wallet secrets");
  139. lc.push(prefix.clone() + "wallet import-secrets");
  140. lc.push(prefix.clone() + "wallet tree");
  141. lc.push(prefix + "wallet coins");
  142. return
  143. }
  144. if last.starts_with("sp") {
  145. lc.push(prefix + "spend");
  146. return
  147. }
  148. if last.starts_with("unsp") {
  149. lc.push(prefix + "unspend");
  150. return
  151. }
  152. if last.starts_with("tr") {
  153. lc.push(prefix + "transfer");
  154. return
  155. }
  156. if last.starts_with("o") {
  157. lc.push(prefix.clone() + "otc");
  158. lc.push(prefix.clone() + "otc init");
  159. lc.push(prefix.clone() + "otc join");
  160. lc.push(prefix.clone() + "otc inspect");
  161. lc.push(prefix + "otc sign");
  162. return
  163. }
  164. if last.starts_with("d") {
  165. lc.push(prefix.clone() + "dao");
  166. lc.push(prefix.clone() + "dao create");
  167. lc.push(prefix.clone() + "dao view");
  168. lc.push(prefix.clone() + "dao import");
  169. lc.push(prefix.clone() + "dao update-keys");
  170. lc.push(prefix.clone() + "dao list");
  171. lc.push(prefix.clone() + "dao balance");
  172. lc.push(prefix.clone() + "dao mint");
  173. lc.push(prefix.clone() + "dao propose-transfer");
  174. lc.push(prefix.clone() + "dao propose-generic");
  175. lc.push(prefix.clone() + "dao proposals");
  176. lc.push(prefix.clone() + "dao proposal");
  177. lc.push(prefix.clone() + "dao proposal-import");
  178. lc.push(prefix.clone() + "dao vote");
  179. lc.push(prefix.clone() + "dao exec");
  180. lc.push(prefix + "dao spend-hook");
  181. return
  182. }
  183. if last.starts_with("at") {
  184. lc.push(prefix + "attach-fee");
  185. return
  186. }
  187. if last.starts_with("i") {
  188. lc.push(prefix + "inspect");
  189. return
  190. }
  191. if last.starts_with("b") {
  192. lc.push(prefix + "broadcast");
  193. return
  194. }
  195. if last.starts_with("su") {
  196. lc.push(prefix + "subscribe");
  197. return
  198. }
  199. if last.starts_with("unsu") {
  200. lc.push(prefix + "unsubscribe");
  201. return
  202. }
  203. if last.starts_with("sn") {
  204. lc.push(prefix + "snooze");
  205. return
  206. }
  207. if last.starts_with("unsn") {
  208. lc.push(prefix + "unsnooze");
  209. return
  210. }
  211. if last.starts_with("sc") {
  212. lc.push(prefix.clone() + "scan");
  213. lc.push(prefix + "scan --reset");
  214. return
  215. }
  216. if last.starts_with("e") {
  217. lc.push(prefix.clone() + "explorer");
  218. lc.push(prefix.clone() + "explorer fetch-tx");
  219. lc.push(prefix.clone() + "explorer simulate-tx");
  220. lc.push(prefix.clone() + "explorer txs-history");
  221. lc.push(prefix.clone() + "explorer clear-reverted");
  222. lc.push(prefix + "explorer scanned-blocks");
  223. return
  224. }
  225. if last.starts_with("al") {
  226. lc.push(prefix.clone() + "alias");
  227. lc.push(prefix.clone() + "alias add");
  228. lc.push(prefix.clone() + "alias show");
  229. lc.push(prefix + "alias remove");
  230. return
  231. }
  232. if last.starts_with("to") {
  233. lc.push(prefix.clone() + "token");
  234. lc.push(prefix.clone() + "token import");
  235. lc.push(prefix.clone() + "token generate-mint");
  236. lc.push(prefix.clone() + "token list");
  237. lc.push(prefix.clone() + "token mint");
  238. lc.push(prefix + "token freeze");
  239. return
  240. }
  241. if last.starts_with("con") {
  242. lc.push(prefix.clone() + "contract");
  243. lc.push(prefix.clone() + "contract generate-deploy");
  244. lc.push(prefix.clone() + "contract list");
  245. lc.push(prefix.clone() + "contract deploy");
  246. lc.push(prefix + "contract lock");
  247. return
  248. }
  249. // Now the catch alls
  250. if last.starts_with("a") {
  251. lc.push(prefix.clone() + "attach-fee");
  252. lc.push(prefix.clone() + "alias");
  253. lc.push(prefix.clone() + "alias add");
  254. lc.push(prefix.clone() + "alias show");
  255. lc.push(prefix + "alias remove");
  256. return
  257. }
  258. if last.starts_with("c") {
  259. lc.push(prefix.clone() + "completions");
  260. lc.push(prefix.clone() + "contract");
  261. lc.push(prefix.clone() + "contract generate-deploy");
  262. lc.push(prefix.clone() + "contract list");
  263. lc.push(prefix.clone() + "contract deploy");
  264. lc.push(prefix + "contract lock");
  265. return
  266. }
  267. if last.starts_with("s") {
  268. lc.push(prefix.clone() + "spend");
  269. lc.push(prefix.clone() + "subscribe");
  270. lc.push(prefix.clone() + "snooze");
  271. lc.push(prefix.clone() + "scan");
  272. lc.push(prefix + "scan --reset");
  273. return
  274. }
  275. if last.starts_with("t") {
  276. lc.push(prefix.clone() + "transfer");
  277. lc.push(prefix.clone() + "token");
  278. lc.push(prefix.clone() + "token import");
  279. lc.push(prefix.clone() + "token generate-mint");
  280. lc.push(prefix.clone() + "token list");
  281. lc.push(prefix.clone() + "token mint");
  282. lc.push(prefix + "token freeze");
  283. return
  284. }
  285. if last.starts_with("u") {
  286. lc.push(prefix.clone() + "unspend");
  287. lc.push(prefix.clone() + "unsubscribe");
  288. lc.push(prefix + "unsnooze");
  289. }
  290. }
  291. /// Auxiliary function to define the interactive shell hints.
  292. fn hints(buffer: &str) -> Option<(String, i32, bool)> {
  293. // Split commands so we always process the last one
  294. let commands: Vec<&str> = buffer.split('|').collect();
  295. let last = commands.last().unwrap().trim_start();
  296. let color = 35; // magenta
  297. let bold = false;
  298. match last {
  299. "completions " => Some(("<shell>".to_string(), color, bold)),
  300. "wallet " => Some(("(initialize|keygen|balance|address|addresses|default-address|secrets|import-secrets|tree|coins)".to_string(), color, bold)),
  301. "wallet default-address " => Some(("<index>".to_string(), color, bold)),
  302. "unspend " => Some(("<coin>".to_string(), color, bold)),
  303. "transfer " => Some(("[--half-split] <amount> <token> <recipient> [spend_hook] [user_data]".to_string(), color, bold)),
  304. "otc " => Some(("(init|join|inspect|sign)".to_string(), color, bold)),
  305. "otc init " => Some(("<value_pair> <token_pair>".to_string(), color, bold)),
  306. "dao " => Some(("(create|view|import|update-keys|list|balance|mint|propose-transfer|propose-generic|proposals|proposal|proposal-import|vote|exec|spend-hook)".to_string(), color, bold)),
  307. "dao create " => Some(("<proposer-limit> <quorum> <early-exec-quorum> <approval-ratio> <gov-token-id>".to_string(), color, bold)),
  308. "dao import " => Some(("<name>".to_string(), color, bold)),
  309. "dao list " => Some(("[name]".to_string(), color, bold)),
  310. "dao balance " => Some(("<name>".to_string(), color, bold)),
  311. "dao mint " => Some(("<name>".to_string(), color, bold)),
  312. "dao propose-transfer " => Some(("<name> <duration> <amount> <token> <recipient> [spend-hook] [user-data]".to_string(), color, bold)),
  313. "dao propose-generic" => Some(("<name> <duration> [user-data]".to_string(), color, bold)),
  314. "dao proposals " => Some(("<name>".to_string(), color, bold)),
  315. "dao proposal " => Some(("[--(export|mint-proposal)] <bulla>".to_string(), color, bold)),
  316. "dao vote " => Some(("<bulla> <vote> [vote-weight]".to_string(), color, bold)),
  317. "dao exec " => Some(("[--early] <bulla>".to_string(), color, bold)),
  318. "scan " => Some(("[--reset]".to_string(), color, bold)),
  319. "scan --reset " => Some(("<height>".to_string(), color, bold)),
  320. "explorer " => Some(("(fetch-tx|simulate-tx|txs-history|clear-reverted|scanned-blocks)".to_string(), color, bold)),
  321. "explorer fetch-tx " => Some(("[--encode] <tx-hash>".to_string(), color, bold)),
  322. "explorer txs-history " => Some(("[--encode] [tx-hash]".to_string(), color, bold)),
  323. "explorer scanned-blocks " => Some(("[height]".to_string(), color, bold)),
  324. "alias " => Some(("(add|show|remove)".to_string(), color, bold)),
  325. "alias add " => Some(("<alias> <token>".to_string(), color, bold)),
  326. "alias show " => Some(("[-a, --alias <alias>] [-t, --token <token>]".to_string(), color, bold)),
  327. "alias remove " => Some(("<alias>".to_string(), color, bold)),
  328. "token " => Some(("(import|generate-mint|list|mint|freeze)".to_string(), color, bold)),
  329. "token import " => Some(("<secret-key> <token-blind>".to_string(), color, bold)),
  330. "token mint " => Some(("<token> <amount> <recipient> [spend-hook] [user-data]".to_string(), color, bold)),
  331. "token freeze " => Some(("<token>".to_string(), color, bold)),
  332. "contract " => Some(("(generate-deploy|list|deploy|lock)".to_string(), color, bold)),
  333. "contract deploy " => Some(("<deploy-auth> <wasm-path> <deploy-ix>".to_string(), color, bold)),
  334. "contract lock " => Some(("<deploy-auth>".to_string(), color, bold)),
  335. _ => None,
  336. }
  337. }
  338. /// Auxiliary function to start provided Drk as an interactive shell.
  339. /// Only sane/linenoise terminals are suported.
  340. pub async fn interactive(drk: &DrkPtr, endpoint: &Url, history_path: &str, ex: &ExecutorPtr) {
  341. // Expand the history file path
  342. let history_path = match expand_path(history_path) {
  343. Ok(p) => p,
  344. Err(e) => {
  345. eprintln!("Error while expanding history file path: {e}");
  346. return
  347. }
  348. };
  349. let history_path = history_path.into_os_string();
  350. let history_file = history_path.to_str().unwrap();
  351. // Set the completion callback. This will be called every time the
  352. // user uses the <tab> key.
  353. linenoise_set_completion_callback(completion);
  354. // Set the shell hints
  355. linenoise_set_hints_callback(hints);
  356. // Load history from file.The history file is just a plain text file
  357. // where entries are separated by newlines.
  358. let _ = linenoise_history_load(history_file);
  359. // Create a detached task to use for block subscription
  360. let mut subscription_active = false;
  361. let mut snooze_active = false;
  362. let subscription_task = StoppableTask::new();
  363. // Create an unbounded smol channel, so we can have a printing
  364. // queue the background task can submit messages to the shell.
  365. let (shell_sender, shell_receiver) = unbounded();
  366. // Start the interactive shell
  367. loop {
  368. // Wait for next line to process
  369. let line = listen_for_line(&snooze_active, &shell_receiver).await;
  370. // Grab input or end if Ctrl-D or Ctrl-C was pressed
  371. let Some(line) = line else { break };
  372. // Check if line is empty
  373. if line.is_empty() {
  374. continue
  375. }
  376. // Add line to history
  377. linenoise_history_add(&line);
  378. // Split commands
  379. let commands: Vec<&str> = line.split('|').collect();
  380. // Process each command
  381. let mut output = vec![];
  382. 'commands_loop: for (command_index, command) in commands.iter().enumerate() {
  383. let mut input = output;
  384. output = vec![];
  385. // Check if we have to output to a file
  386. let (mut command, file, append) = if command.contains('>') {
  387. // Check if we write or append to the file
  388. let mut split = ">";
  389. let mut append = false;
  390. if command.contains(">>") {
  391. split = ">>";
  392. append = true;
  393. }
  394. // Parse command parts
  395. let parts: Vec<&str> = command.split(split).collect();
  396. if parts.len() == 1 || parts[0].contains('>') {
  397. output.push(format!("Malformed command output file definition: {command}"));
  398. continue
  399. }
  400. let file = String::from(parts[1..].join("").trim());
  401. if file.is_empty() || file.contains('>') {
  402. output.push(format!("Malformed command output file definition: {command}"));
  403. continue
  404. }
  405. (parts[0], Some(file), append)
  406. } else {
  407. (*command, None, false)
  408. };
  409. // Check if we have to use a file as input
  410. if command.contains('<') {
  411. // Parse command parts
  412. let parts: Vec<&str> = command.split('<').collect();
  413. if parts.len() == 1 {
  414. output.push(format!("Malformed command input file definition: {command}"));
  415. continue
  416. }
  417. // Read the input file name
  418. let file = String::from(parts[1..].join("").trim());
  419. if file.is_empty() {
  420. output.push(format!("Malformed command input file definition: {command}"));
  421. continue
  422. }
  423. // Expand the input file path
  424. let file_path = match expand_path(&file) {
  425. Ok(p) => p,
  426. Err(e) => {
  427. output.push(format!("Error while expanding input file path: {e}"));
  428. continue
  429. }
  430. };
  431. // Read the file lines
  432. let file = match File::open(file_path) {
  433. Ok(f) => f,
  434. Err(e) => {
  435. output.push(format!("Error while openning input file: {e}"));
  436. continue
  437. }
  438. };
  439. input = vec![];
  440. for (index, line) in BufReader::new(file).lines().enumerate() {
  441. match line {
  442. Ok(l) => input.push(l),
  443. Err(e) => {
  444. output
  445. .push(format!("Error while reading input file line {index}: {e}"));
  446. continue 'commands_loop
  447. }
  448. }
  449. }
  450. command = parts[0];
  451. }
  452. // Parse command parts
  453. let parts: Vec<&str> = command.split_whitespace().collect();
  454. if parts.is_empty() {
  455. continue
  456. }
  457. // Handle command
  458. match parts[0] {
  459. "help" => help(&mut output),
  460. "kaching" => kaching().await,
  461. "ping" => handle_ping(drk, &mut output).await,
  462. "completions" => handle_completions(&parts, &mut output),
  463. "wallet" => handle_wallet(drk, &parts, &input, &mut output).await,
  464. "spend" => handle_spend(drk, &input, &mut output).await,
  465. "unspend" => handle_unspend(drk, &parts, &mut output).await,
  466. "transfer" => handle_transfer(drk, &parts, &mut output).await,
  467. "otc" => handle_otc(drk, &parts, &input, &mut output).await,
  468. "dao" => handle_dao(drk, &parts, &input, &mut output).await,
  469. "attach-fee" => handle_attach_fee(drk, &input, &mut output).await,
  470. "inspect" => handle_inspect(&input, &mut output).await,
  471. "broadcast" => handle_broadcast(drk, &input, &mut output).await,
  472. "subscribe" => {
  473. handle_subscribe(
  474. drk,
  475. endpoint,
  476. &mut subscription_active,
  477. &subscription_task,
  478. &shell_sender,
  479. ex,
  480. &mut output,
  481. )
  482. .await
  483. }
  484. "unsubscribe" => {
  485. handle_unsubscribe(&mut subscription_active, &subscription_task, &mut output)
  486. .await
  487. }
  488. "snooze" => snooze_active = true,
  489. "unsnooze" => snooze_active = false,
  490. "scan" => {
  491. handle_scan(
  492. drk,
  493. &subscription_active,
  494. &parts,
  495. &mut output,
  496. &(command_index + 1 == commands.len() && file.is_none()),
  497. )
  498. .await
  499. }
  500. "explorer" => handle_explorer(drk, &parts, &input, &mut output).await,
  501. "alias" => handle_alias(drk, &parts, &mut output).await,
  502. "token" => handle_token(drk, &parts, &mut output).await,
  503. "contract" => handle_contract(drk, &parts, &mut output).await,
  504. _ => output.push(format!("Unreconized command: {}", parts[0])),
  505. }
  506. // Write output to file, if requested
  507. if let Some(file) = file {
  508. // Expand the output file path
  509. let file_path = match expand_path(&file) {
  510. Ok(p) => p,
  511. Err(e) => {
  512. output.push(format!("Error while expanding output file path: {e}"));
  513. continue
  514. }
  515. };
  516. // Open the file
  517. let file = if append {
  518. OpenOptions::new().create(true).append(true).open(&file_path)
  519. } else {
  520. File::create(file_path)
  521. };
  522. let mut file = match file {
  523. Ok(f) => f,
  524. Err(e) => {
  525. output.push(format!("Error while openning output file: {e}"));
  526. continue
  527. }
  528. };
  529. // Seek end if we append to it
  530. if append {
  531. if let Err(e) = file.seek(SeekFrom::End(0)) {
  532. output.push(format!("Error while seeking end of output file: {e}"));
  533. continue
  534. }
  535. }
  536. // Write the output
  537. if let Err(e) = file.write_all((output.join("\n") + "\n").as_bytes()) {
  538. output.push(format!("Error while writing output file: {e}"));
  539. continue
  540. }
  541. output = vec![];
  542. }
  543. }
  544. // Handle last command output
  545. print_output(&output);
  546. }
  547. // Stop the subscription task if its active
  548. if subscription_active {
  549. subscription_task.stop().await;
  550. }
  551. // Write history file
  552. let _ = linenoise_history_save(history_file);
  553. }
  554. /// Auxiliary function to listen for linenoise input line and handle
  555. /// background task messages.
  556. async fn listen_for_line(
  557. snooze_active: &bool,
  558. shell_receiver: &Receiver<Vec<String>>,
  559. ) -> Option<String> {
  560. // Generate the linoise state structure
  561. let mut state = match LinenoiseState::edit_start(-1, -1, "drk> ") {
  562. Ok(s) => s,
  563. Err(e) => {
  564. eprintln!("Error while generating linenoise state: {e}");
  565. return None
  566. }
  567. };
  568. // Set stdin to non-blocking mode
  569. let fd = state.get_fd();
  570. unsafe {
  571. let flags = fcntl(fd, F_GETFL, 0);
  572. fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  573. }
  574. // Read until we get a line to process
  575. let mut line = None;
  576. loop {
  577. // Future that polls stdin for input
  578. let input_future = async {
  579. loop {
  580. match state.edit_feed() {
  581. Ok(Some(l)) => {
  582. line = Some(l);
  583. break
  584. }
  585. Ok(None) => break,
  586. Err(e) if e.kind() == ErrorKind::Interrupted => break,
  587. Err(e) if e.kind() == ErrorKind::WouldBlock => {
  588. // No data available, yield and retry
  589. msleep(10).await;
  590. continue
  591. }
  592. Err(e) => {
  593. eprintln!("Error while reading linenoise feed: {e}");
  594. break
  595. }
  596. }
  597. }
  598. };
  599. // Future that polls the channel
  600. let channel_future = async {
  601. loop {
  602. if !shell_receiver.is_empty() {
  603. break
  604. }
  605. msleep(1000).await;
  606. }
  607. };
  608. // Manage the futures
  609. select! {
  610. // When input is ready we break out the loop
  611. _ = input_future.fuse() => break,
  612. // Manage filled channel
  613. _ = channel_future.fuse() => {
  614. while !shell_receiver.is_empty() {
  615. match shell_receiver.recv().await {
  616. Ok(msg) => {
  617. // We only print if snooze is inactive,
  618. // but have to consume the message regardless,
  619. // so the queue gets empty.
  620. if *snooze_active {
  621. continue
  622. }
  623. // Hide prompt, print output, show prompt again
  624. let _ = state.hide();
  625. for line in msg {
  626. println!("{}\r", line.replace("\n", "\n\r"));
  627. }
  628. let _ = state.show();
  629. }
  630. Err(e) => {
  631. eprintln!("Error while reading shell receiver channel: {e}");
  632. break
  633. }
  634. }
  635. }
  636. }
  637. }
  638. }
  639. // Restore blocking mode
  640. unsafe {
  641. let flags = fcntl(fd, F_GETFL, 0);
  642. fcntl(fd, F_SETFL, flags & !O_NONBLOCK);
  643. }
  644. let _ = state.edit_stop();
  645. line
  646. }
  647. /// Auxiliary function to define the ping command handling.
  648. async fn handle_ping(drk: &DrkPtr, output: &mut Vec<String>) {
  649. if let Err(e) = drk.read().await.ping(output).await {
  650. output.push(format!("Error while executing ping command: {e}"))
  651. }
  652. }
  653. /// Auxiliary function to define the completions command handling.
  654. fn handle_completions(parts: &[&str], output: &mut Vec<String>) {
  655. // Check correct command structure
  656. if parts.len() != 2 {
  657. output.push(String::from("Malformed `completions` command"));
  658. output.push(String::from("Usage: completions <shell>"));
  659. return
  660. }
  661. match generate_completions(parts[1]) {
  662. Ok(completions) => output.push(completions),
  663. Err(e) => output.push(format!("Error while executing completions command: {e}")),
  664. }
  665. }
  666. /// Auxiliary function to define the wallet command handling.
  667. async fn handle_wallet(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
  668. // Check correct command structure
  669. if parts.len() < 2 {
  670. output.push(String::from("Malformed `wallet` command"));
  671. output.push(String::from("Usage: wallet (initialize|keygen|balance|address|addresses|default-address|secrets|import-secrets|tree|coins)"));
  672. return
  673. }
  674. // Handle subcommand
  675. match parts[1] {
  676. "initialize" => handle_wallet_initialize(drk, output).await,
  677. "keygen" => handle_wallet_keygen(drk, output).await,
  678. "balance" => handle_wallet_balance(drk, output).await,
  679. "address" => handle_wallet_address(drk, output).await,
  680. "addresses" => handle_wallet_addresses(drk, output).await,
  681. "default-address" => handle_wallet_default_address(drk, parts, output).await,
  682. "secrets" => handle_wallet_secrets(drk, output).await,
  683. "import-secrets" => handle_wallet_import_secrets(drk, input, output).await,
  684. "tree" => handle_wallet_tree(drk, output).await,
  685. "coins" => handle_wallet_coins(drk, output).await,
  686. _ => {
  687. output.push(format!("Unreconized wallet subcommand: {}", parts[1]));
  688. output.push(String::from("Usage: wallet (initialize|keygen|balance|address|addresses|default-address|secrets|import-secrets|tree|coins)"));
  689. }
  690. }
  691. }
  692. /// Auxiliary function to define the wallet initialize subcommand handling.
  693. async fn handle_wallet_initialize(drk: &DrkPtr, output: &mut Vec<String>) {
  694. let lock = drk.read().await;
  695. if let Err(e) = lock.initialize_wallet().await {
  696. output.push(format!("Error initializing wallet: {e}"));
  697. return
  698. }
  699. if let Err(e) = lock.initialize_money(output).await {
  700. output.push(format!("Failed to initialize Money: {e}"));
  701. return
  702. }
  703. if let Err(e) = lock.initialize_dao().await {
  704. output.push(format!("Failed to initialize DAO: {e}"));
  705. return
  706. }
  707. if let Err(e) = lock.initialize_deployooor() {
  708. output.push(format!("Failed to initialize Deployooor: {e}"));
  709. }
  710. }
  711. /// Auxiliary function to define the wallet keygen subcommand handling.
  712. async fn handle_wallet_keygen(drk: &DrkPtr, output: &mut Vec<String>) {
  713. if let Err(e) = drk.read().await.money_keygen(output).await {
  714. output.push(format!("Failed to generate keypair: {e}"));
  715. }
  716. }
  717. /// Auxiliary function to define the wallet balance subcommand handling.
  718. async fn handle_wallet_balance(drk: &DrkPtr, output: &mut Vec<String>) {
  719. let lock = drk.read().await;
  720. let balmap = match lock.money_balance().await {
  721. Ok(m) => m,
  722. Err(e) => {
  723. output.push(format!("Failed to fetch balances map: {e}"));
  724. return
  725. }
  726. };
  727. let aliases_map = match lock.get_aliases_mapped_by_token().await {
  728. Ok(m) => m,
  729. Err(e) => {
  730. output.push(format!("Failed to fetch aliases map: {e}"));
  731. return
  732. }
  733. };
  734. // Create a prettytable with the new data:
  735. let mut table = Table::new();
  736. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  737. table.set_titles(row!["Token ID", "Aliases", "Balance"]);
  738. for (token_id, balance) in balmap.iter() {
  739. let aliases = match aliases_map.get(token_id) {
  740. Some(a) => a,
  741. None => "-",
  742. };
  743. table.add_row(row![token_id, aliases, encode_base10(*balance, BALANCE_BASE10_DECIMALS)]);
  744. }
  745. if table.is_empty() {
  746. output.push(String::from("No unspent balances found"));
  747. } else {
  748. output.push(format!("{table}"));
  749. }
  750. }
  751. /// Auxiliary function to define the wallet address subcommand handling.
  752. async fn handle_wallet_address(drk: &DrkPtr, output: &mut Vec<String>) {
  753. match drk.read().await.default_address().await {
  754. Ok(address) => output.push(format!("{address}")),
  755. Err(e) => output.push(format!("Failed to fetch default address: {e}")),
  756. }
  757. }
  758. /// Auxiliary function to define the wallet addresses subcommand handling.
  759. async fn handle_wallet_addresses(drk: &DrkPtr, output: &mut Vec<String>) {
  760. let addresses = match drk.read().await.addresses().await {
  761. Ok(a) => a,
  762. Err(e) => {
  763. output.push(format!("Failed to fetch addresses: {e}"));
  764. return
  765. }
  766. };
  767. // Create a prettytable with the new data:
  768. let mut table = Table::new();
  769. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  770. table.set_titles(row!["Key ID", "Public Key", "Secret Key", "Is Default"]);
  771. for (key_id, public_key, secret_key, is_default) in addresses {
  772. let is_default = match is_default {
  773. 1 => "*",
  774. _ => "",
  775. };
  776. table.add_row(row![key_id, public_key, secret_key, is_default]);
  777. }
  778. if table.is_empty() {
  779. output.push(String::from("No addresses found"));
  780. } else {
  781. output.push(format!("{table}"));
  782. }
  783. }
  784. /// Auxiliary function to define the wallet default address subcommand handling.
  785. async fn handle_wallet_default_address(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  786. if parts.len() != 3 {
  787. output.push(String::from("Malformed `wallet default-address` subcommand"));
  788. output.push(String::from("Usage: wallet default-address <index>"));
  789. return
  790. }
  791. let index = match usize::from_str(parts[2]) {
  792. Ok(i) => i,
  793. Err(e) => {
  794. output.push(format!("Invalid address id: {e}"));
  795. return
  796. }
  797. };
  798. if let Err(e) = drk.read().await.set_default_address(index) {
  799. output.push(format!("Failed to set default address: {e}"));
  800. }
  801. }
  802. /// Auxiliary function to define the wallet secrets subcommand handling.
  803. async fn handle_wallet_secrets(drk: &DrkPtr, output: &mut Vec<String>) {
  804. match drk.read().await.get_money_secrets().await {
  805. Ok(secrets) => {
  806. for secret in secrets {
  807. output.push(format!("{secret}"));
  808. }
  809. }
  810. Err(e) => output.push(format!("Failed to fetch secrets: {e}")),
  811. }
  812. }
  813. /// Auxiliary function to define the wallet import secrets subcommand handling.
  814. async fn handle_wallet_import_secrets(drk: &DrkPtr, input: &[String], output: &mut Vec<String>) {
  815. let mut secrets = vec![];
  816. // Parse input or read from stdin
  817. if input.is_empty() {
  818. for (i, line) in stdin().lines().enumerate() {
  819. let Ok(line) = line else { continue };
  820. let Ok(bytes) = bs58::decode(&line.trim()).into_vec() else {
  821. output.push(format!("Warning: Failed to decode secret on line {i}"));
  822. continue
  823. };
  824. let Ok(secret) = deserialize_async(&bytes).await else {
  825. output.push(format!("Warning: Failed to deserialize secret on line {i}"));
  826. continue
  827. };
  828. secrets.push(secret);
  829. }
  830. } else {
  831. for (i, line) in input.iter().enumerate() {
  832. let Ok(bytes) = bs58::decode(&line.trim()).into_vec() else {
  833. output.push(format!("Warning: Failed to decode secret on line {i}"));
  834. continue
  835. };
  836. let Ok(secret) = deserialize_async(&bytes).await else {
  837. output.push(format!("Warning: Failed to deserialize secret on line {i}"));
  838. continue
  839. };
  840. secrets.push(secret);
  841. }
  842. }
  843. match drk.read().await.import_money_secrets(secrets, output).await {
  844. Ok(pubkeys) => {
  845. for key in pubkeys {
  846. output.push(format!("{key}"));
  847. }
  848. }
  849. Err(e) => output.push(format!("Failed to import secrets: {e}")),
  850. }
  851. }
  852. /// Auxiliary function to define the wallet tree subcommand handling.
  853. async fn handle_wallet_tree(drk: &DrkPtr, output: &mut Vec<String>) {
  854. match drk.read().await.get_money_tree().await {
  855. Ok(tree) => output.push(format!("{tree:#?}")),
  856. Err(e) => output.push(format!("Failed to fetch tree: {e}")),
  857. }
  858. }
  859. /// Auxiliary function to define the wallet coins subcommand handling.
  860. async fn handle_wallet_coins(drk: &DrkPtr, output: &mut Vec<String>) {
  861. let lock = drk.read().await;
  862. let coins = match lock.get_coins(true).await {
  863. Ok(c) => c,
  864. Err(e) => {
  865. output.push(format!("Failed to fetch coins: {e}"));
  866. return
  867. }
  868. };
  869. if coins.is_empty() {
  870. return
  871. }
  872. let aliases_map = match lock.get_aliases_mapped_by_token().await {
  873. Ok(m) => m,
  874. Err(e) => {
  875. output.push(format!("Failed to fetch aliases map: {e}"));
  876. return
  877. }
  878. };
  879. let mut table = Table::new();
  880. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  881. table.set_titles(row![
  882. "Coin",
  883. "Token ID",
  884. "Aliases",
  885. "Value",
  886. "Spend Hook",
  887. "User Data",
  888. "Creation Height",
  889. "Spent",
  890. "Spent Height",
  891. "Spent TX"
  892. ]);
  893. for coin in coins {
  894. let aliases = match aliases_map.get(&coin.0.note.token_id.to_string()) {
  895. Some(a) => a,
  896. None => "-",
  897. };
  898. let spend_hook = if coin.0.note.spend_hook != FuncId::none() {
  899. format!("{}", coin.0.note.spend_hook)
  900. } else {
  901. String::from("-")
  902. };
  903. let user_data = if coin.0.note.user_data != pallas::Base::ZERO {
  904. bs58::encode(&serialize_async(&coin.0.note.user_data).await).into_string().to_string()
  905. } else {
  906. String::from("-")
  907. };
  908. let spent_height = match coin.3 {
  909. Some(spent_height) => spent_height.to_string(),
  910. None => String::from("-"),
  911. };
  912. table.add_row(row![
  913. bs58::encode(&serialize_async(&coin.0.coin.inner()).await).into_string().to_string(),
  914. coin.0.note.token_id,
  915. aliases,
  916. format!(
  917. "{} ({})",
  918. coin.0.note.value,
  919. encode_base10(coin.0.note.value, BALANCE_BASE10_DECIMALS)
  920. ),
  921. spend_hook,
  922. user_data,
  923. coin.1,
  924. coin.2,
  925. spent_height,
  926. coin.4,
  927. ]);
  928. }
  929. output.push(format!("{table}"));
  930. }
  931. /// Auxiliary function to define the spend command handling.
  932. async fn handle_spend(drk: &DrkPtr, input: &[String], output: &mut Vec<String>) {
  933. let tx = match parse_tx_from_input(input).await {
  934. Ok(t) => t,
  935. Err(e) => {
  936. output.push(format!("Error while parsing transaction: {e}"));
  937. return
  938. }
  939. };
  940. if let Err(e) = drk.read().await.mark_tx_spend(&tx, output).await {
  941. output.push(format!("Failed to mark transaction coins as spent: {e}"))
  942. }
  943. }
  944. /// Auxiliary function to define the unspend command handling.
  945. async fn handle_unspend(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  946. // Check correct command structure
  947. if parts.len() != 2 {
  948. output.push(String::from("Malformed `unspend` command"));
  949. output.push(String::from("Usage: unspend <coin>"));
  950. return
  951. }
  952. let bytes = match bs58::decode(&parts[1]).into_vec() {
  953. Ok(b) => b,
  954. Err(e) => {
  955. output.push(format!("Invalid coin: {e}"));
  956. return
  957. }
  958. };
  959. let bytes: [u8; 32] = match bytes.try_into() {
  960. Ok(b) => b,
  961. Err(e) => {
  962. output.push(format!("Invalid coin: {e:?}"));
  963. return
  964. }
  965. };
  966. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  967. Some(v) => v,
  968. None => {
  969. output.push(String::from("Invalid coin"));
  970. return
  971. }
  972. };
  973. if let Err(e) = drk.read().await.unspend_coin(&Coin::from(elem)).await {
  974. output.push(format!("Failed to mark coin as unspent: {e}"))
  975. }
  976. }
  977. /// Auxiliary function to define the transfer command handling.
  978. async fn handle_transfer(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  979. // Check correct command structure
  980. if parts.len() < 4 || parts.len() > 7 {
  981. output.push(String::from("Malformed `transfer` command"));
  982. output.push(String::from(
  983. "Usage: transfer [--half-split] <amount> <token> <recipient> [spend_hook] [user_data]",
  984. ));
  985. return
  986. }
  987. // Parse command
  988. let mut index = 1;
  989. let mut half_split = false;
  990. if parts[index] == "--half-split" {
  991. half_split = true;
  992. index += 1;
  993. }
  994. let amount = String::from(parts[index]);
  995. if let Err(e) = f64::from_str(&amount) {
  996. output.push(format!("Invalid amount: {e}"));
  997. return
  998. }
  999. index += 1;
  1000. let lock = drk.read().await;
  1001. let token_id = match lock.get_token(String::from(parts[index])).await {
  1002. Ok(t) => t,
  1003. Err(e) => {
  1004. output.push(format!("Invalid token ID: {e}"));
  1005. return
  1006. }
  1007. };
  1008. index += 1;
  1009. let rcpt = match PublicKey::from_str(parts[index]) {
  1010. Ok(r) => r,
  1011. Err(e) => {
  1012. output.push(format!("Invalid recipient: {e}"));
  1013. return
  1014. }
  1015. };
  1016. index += 1;
  1017. let spend_hook = if index < parts.len() {
  1018. match FuncId::from_str(parts[index]) {
  1019. Ok(s) => Some(s),
  1020. Err(e) => {
  1021. output.push(format!("Invalid spend hook: {e}"));
  1022. return
  1023. }
  1024. }
  1025. } else {
  1026. None
  1027. };
  1028. index += 1;
  1029. let user_data = if index < parts.len() {
  1030. let bytes = match bs58::decode(&parts[index]).into_vec() {
  1031. Ok(b) => b,
  1032. Err(e) => {
  1033. output.push(format!("Invalid user data: {e}"));
  1034. return
  1035. }
  1036. };
  1037. let bytes: [u8; 32] = match bytes.try_into() {
  1038. Ok(b) => b,
  1039. Err(e) => {
  1040. output.push(format!("Invalid user data: {e:?}"));
  1041. return
  1042. }
  1043. };
  1044. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  1045. Some(v) => v,
  1046. None => {
  1047. output.push(String::from("Invalid user data"));
  1048. return
  1049. }
  1050. };
  1051. Some(elem)
  1052. } else {
  1053. None
  1054. };
  1055. match lock.transfer(&amount, token_id, rcpt, spend_hook, user_data, half_split).await {
  1056. Ok(t) => output.push(base64::encode(&serialize_async(&t).await)),
  1057. Err(e) => output.push(format!("Failed to create payment transaction: {e}")),
  1058. }
  1059. }
  1060. /// Auxiliary function to define the otc command handling.
  1061. async fn handle_otc(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
  1062. // Check correct command structure
  1063. if parts.len() < 2 {
  1064. output.push(String::from("Malformed `otc` command"));
  1065. output.push(String::from("Usage: otc (init|join|inspect|sign)"));
  1066. return
  1067. }
  1068. // Handle subcommand
  1069. match parts[1] {
  1070. "init" => handle_otc_init(drk, parts, output).await,
  1071. "join" => handle_otc_join(drk, parts, input, output).await,
  1072. "inspect" => handle_otc_inspect(drk, parts, input, output).await,
  1073. "sign" => handle_otc_sign(drk, parts, input, output).await,
  1074. _ => {
  1075. output.push(format!("Unreconized OTC subcommand: {}", parts[1]));
  1076. output.push(String::from("Usage: otc (init|join|inspect|sign)"));
  1077. }
  1078. }
  1079. }
  1080. /// Auxiliary function to define the otc init subcommand handling.
  1081. async fn handle_otc_init(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1082. // Check correct subcommand structure
  1083. if parts.len() != 4 {
  1084. output.push(String::from("Malformed `otc init` subcommand"));
  1085. output.push(String::from("Usage: otc init <value_pair> <token_pair>"));
  1086. return
  1087. }
  1088. let value_pair = match parse_value_pair(parts[2]) {
  1089. Ok(v) => v,
  1090. Err(e) => {
  1091. output.push(format!("Invalid value pair: {e}"));
  1092. return
  1093. }
  1094. };
  1095. let lock = drk.read().await;
  1096. let token_pair = match parse_token_pair(&lock, parts[3]).await {
  1097. Ok(t) => t,
  1098. Err(e) => {
  1099. output.push(format!("Invalid token pair: {e}"));
  1100. return
  1101. }
  1102. };
  1103. match lock.init_swap(value_pair, token_pair, None, None, None).await {
  1104. Ok(half) => output.push(base64::encode(&serialize_async(&half).await)),
  1105. Err(e) => output.push(format!("Failed to create swap transaction half: {e}")),
  1106. }
  1107. }
  1108. /// Auxiliary function to define the otc join subcommand handling.
  1109. async fn handle_otc_join(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
  1110. // Check correct subcommand structure
  1111. if parts.len() != 2 {
  1112. output.push(String::from("Malformed `otc join` subcommand"));
  1113. output.push(String::from("Usage: otc join"));
  1114. return
  1115. }
  1116. // Parse line from input or fallback to stdin if its empty
  1117. let buf = match input.len() {
  1118. 0 => {
  1119. let mut buf = String::new();
  1120. if let Err(e) = stdin().read_to_string(&mut buf) {
  1121. output.push(format!("Failed to read from stdin: {e}"));
  1122. return
  1123. };
  1124. buf
  1125. }
  1126. 1 => input[0].clone(),
  1127. _ => {
  1128. output.push(String::from("Multiline input provided"));
  1129. return
  1130. }
  1131. };
  1132. let Some(bytes) = base64::decode(buf.trim()) else {
  1133. output.push(String::from("Failed to decode partial swap data"));
  1134. return
  1135. };
  1136. let partial: PartialSwapData = match deserialize_async(&bytes).await {
  1137. Ok(p) => p,
  1138. Err(e) => {
  1139. output.push(format!("Failed to deserialize partial swap data: {e}"));
  1140. return
  1141. }
  1142. };
  1143. match drk.read().await.join_swap(partial, None, None, None).await {
  1144. Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
  1145. Err(e) => output.push(format!("Failed to create a join swap transaction: {e}")),
  1146. }
  1147. }
  1148. /// Auxiliary function to define the otc inspect subcommand handling.
  1149. async fn handle_otc_inspect(
  1150. drk: &DrkPtr,
  1151. parts: &[&str],
  1152. input: &[String],
  1153. output: &mut Vec<String>,
  1154. ) {
  1155. // Check correct subcommand structure
  1156. if parts.len() != 2 {
  1157. output.push(String::from("Malformed `otc inspect` subcommand"));
  1158. output.push(String::from("Usage: otc inspect"));
  1159. return
  1160. }
  1161. // Parse line from input or fallback to stdin if its empty
  1162. let buf = match input.len() {
  1163. 0 => {
  1164. let mut buf = String::new();
  1165. if let Err(e) = stdin().read_to_string(&mut buf) {
  1166. output.push(format!("Failed to read from stdin: {e}"));
  1167. return
  1168. };
  1169. buf
  1170. }
  1171. 1 => input[0].clone(),
  1172. _ => {
  1173. output.push(String::from("Multiline input provided"));
  1174. return
  1175. }
  1176. };
  1177. let Some(bytes) = base64::decode(buf.trim()) else {
  1178. output.push(String::from("Failed to decode swap transaction"));
  1179. return
  1180. };
  1181. if let Err(e) = drk.read().await.inspect_swap(bytes, output).await {
  1182. output.push(format!("Failed to inspect swap: {e}"));
  1183. }
  1184. }
  1185. /// Auxiliary function to define the otc sign subcommand handling.
  1186. async fn handle_otc_sign(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
  1187. // Check correct subcommand structure
  1188. if parts.len() != 2 {
  1189. output.push(String::from("Malformed `otc sign` subcommand"));
  1190. output.push(String::from("Usage: otc sign"));
  1191. return
  1192. }
  1193. let mut tx = match parse_tx_from_input(input).await {
  1194. Ok(t) => t,
  1195. Err(e) => {
  1196. output.push(format!("Error while parsing transaction: {e}"));
  1197. return
  1198. }
  1199. };
  1200. match drk.read().await.sign_swap(&mut tx).await {
  1201. Ok(_) => output.push(base64::encode(&serialize_async(&tx).await)),
  1202. Err(e) => output.push(format!("Failed to sign joined swap transaction: {e}")),
  1203. }
  1204. }
  1205. /// Auxiliary function to define the dao command handling.
  1206. async fn handle_dao(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
  1207. // Check correct command structure
  1208. if parts.len() < 2 {
  1209. output.push(String::from("Malformed `dao` command"));
  1210. output.push(String::from("Usage: dao (create|view|import|update-keys|list|balance|mint|propose-transfer|propose-generic|proposals|proposal|proposal-import|vote|exec|spend-hook)"));
  1211. return
  1212. }
  1213. // Handle subcommand
  1214. match parts[1] {
  1215. "create" => handle_dao_create(drk, parts, output).await,
  1216. "view" => handle_dao_view(parts, input, output).await,
  1217. "import" => handle_dao_import(drk, parts, input, output).await,
  1218. "update-keys" => handle_dao_update_keys(drk, parts, input, output).await,
  1219. "list" => handle_dao_list(drk, parts, output).await,
  1220. "balance" => handle_dao_balance(drk, parts, output).await,
  1221. "mint" => handle_dao_mint(drk, parts, output).await,
  1222. "propose-transfer" => handle_dao_propose_transfer(drk, parts, output).await,
  1223. "propose-generic" => handle_dao_propose_generic(drk, parts, output).await,
  1224. "proposals" => handle_dao_proposals(drk, parts, output).await,
  1225. "proposal" => handle_dao_proposal(drk, parts, output).await,
  1226. "proposal-import" => handle_dao_proposal_import(drk, parts, input, output).await,
  1227. "vote" => handle_dao_vote(drk, parts, output).await,
  1228. "exec" => handle_dao_exec(drk, parts, output).await,
  1229. "spend-hook" => handle_dao_spend_hook(parts, output).await,
  1230. _ => {
  1231. output.push(format!("Unreconized DAO subcommand: {}", parts[1]));
  1232. output.push(String::from("Usage: dao (create|view|import|update-keys|list|balance|mint|propose-transfer|propose-generic|proposals|proposal|proposal-import|vote|exec|spend-hook)"));
  1233. }
  1234. }
  1235. }
  1236. /// Auxiliary function to define the dao create subcommand handling.
  1237. async fn handle_dao_create(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1238. // Check correct subcommand structure
  1239. if parts.len() != 7 {
  1240. output.push(String::from("Malformed `dao create` subcommand"));
  1241. output.push(String::from("Usage: dao create <proposer-limit> <quorum> <early-exec-quorum> <approval-ratio> <gov-token-id>"));
  1242. return
  1243. }
  1244. if let Err(e) = f64::from_str(parts[2]) {
  1245. output.push(format!("Invalid proposer limit: {e}"));
  1246. return
  1247. }
  1248. let proposer_limit = match decode_base10(parts[2], BALANCE_BASE10_DECIMALS, true) {
  1249. Ok(p) => p,
  1250. Err(e) => {
  1251. output.push(format!("Error while parsing proposer limit: {e}"));
  1252. return
  1253. }
  1254. };
  1255. if let Err(e) = f64::from_str(parts[3]) {
  1256. output.push(format!("Invalid quorum: {e}"));
  1257. return
  1258. }
  1259. let quorum = match decode_base10(parts[3], BALANCE_BASE10_DECIMALS, true) {
  1260. Ok(q) => q,
  1261. Err(e) => {
  1262. output.push(format!("Error while parsing quorum: {e}"));
  1263. return
  1264. }
  1265. };
  1266. if let Err(e) = f64::from_str(parts[4]) {
  1267. output.push(format!("Invalid early exec quorum: {e}"));
  1268. return
  1269. }
  1270. let early_exec_quorum = match decode_base10(parts[4], BALANCE_BASE10_DECIMALS, true) {
  1271. Ok(e) => e,
  1272. Err(e) => {
  1273. output.push(format!("Error while parsing early exec quorum: {e}"));
  1274. return
  1275. }
  1276. };
  1277. let approval_ratio = match f64::from_str(parts[5]) {
  1278. Ok(a) => {
  1279. if a > 1.0 {
  1280. output.push(String::from("Error: Approval ratio cannot be >1.0"));
  1281. return
  1282. }
  1283. a
  1284. }
  1285. Err(e) => {
  1286. output.push(format!("Invalid approval ratio: {e}"));
  1287. return
  1288. }
  1289. };
  1290. let approval_ratio_base = 100_u64;
  1291. let approval_ratio_quot = (approval_ratio * approval_ratio_base as f64) as u64;
  1292. let gov_token_id = match drk.read().await.get_token(String::from(parts[6])).await {
  1293. Ok(g) => g,
  1294. Err(e) => {
  1295. output.push(format!("Invalid Token ID: {e}"));
  1296. return
  1297. }
  1298. };
  1299. let notes_keypair = Keypair::random(&mut OsRng);
  1300. let proposer_keypair = Keypair::random(&mut OsRng);
  1301. let proposals_keypair = Keypair::random(&mut OsRng);
  1302. let votes_keypair = Keypair::random(&mut OsRng);
  1303. let exec_keypair = Keypair::random(&mut OsRng);
  1304. let early_exec_keypair = Keypair::random(&mut OsRng);
  1305. let bulla_blind = BaseBlind::random(&mut OsRng);
  1306. let params = DaoParams::new(
  1307. proposer_limit,
  1308. quorum,
  1309. early_exec_quorum,
  1310. approval_ratio_base,
  1311. approval_ratio_quot,
  1312. gov_token_id,
  1313. Some(notes_keypair.secret),
  1314. notes_keypair.public,
  1315. Some(proposer_keypair.secret),
  1316. proposer_keypair.public,
  1317. Some(proposals_keypair.secret),
  1318. proposals_keypair.public,
  1319. Some(votes_keypair.secret),
  1320. votes_keypair.public,
  1321. Some(exec_keypair.secret),
  1322. exec_keypair.public,
  1323. Some(early_exec_keypair.secret),
  1324. early_exec_keypair.public,
  1325. bulla_blind,
  1326. );
  1327. output.push(params.toml_str());
  1328. }
  1329. /// Auxiliary function to define the dao view subcommand handling.
  1330. async fn handle_dao_view(parts: &[&str], input: &[String], output: &mut Vec<String>) {
  1331. // Check correct subcommand structure
  1332. if parts.len() != 2 {
  1333. output.push(String::from("Malformed `dao view` subcommand"));
  1334. output.push(String::from("Usage: dao view"));
  1335. return
  1336. }
  1337. // Parse line from input or fallback to stdin if its empty
  1338. let buf = match input.len() {
  1339. 0 => {
  1340. let mut buf = String::new();
  1341. if let Err(e) = stdin().read_to_string(&mut buf) {
  1342. output.push(format!("Failed to read from stdin: {e}"));
  1343. return
  1344. };
  1345. buf
  1346. }
  1347. 1 => input[0].clone(),
  1348. _ => {
  1349. output.push(String::from("Multiline input provided"));
  1350. return
  1351. }
  1352. };
  1353. let params = match DaoParams::from_toml_str(&buf) {
  1354. Ok(p) => p,
  1355. Err(e) => {
  1356. output.push(format!("Error while parsing DAO params: {e}"));
  1357. return
  1358. }
  1359. };
  1360. output.push(format!("{params}"));
  1361. }
  1362. /// Auxiliary function to define the dao import subcommand handling.
  1363. async fn handle_dao_import(
  1364. drk: &DrkPtr,
  1365. parts: &[&str],
  1366. input: &[String],
  1367. output: &mut Vec<String>,
  1368. ) {
  1369. // Check correct subcommand structure
  1370. if parts.len() != 3 {
  1371. output.push(String::from("Malformed `dao import` subcommand"));
  1372. output.push(String::from("Usage: dao import <name>"));
  1373. return
  1374. }
  1375. // Parse line from input or fallback to stdin if its empty
  1376. let buf = match input.len() {
  1377. 0 => {
  1378. let mut buf = String::new();
  1379. if let Err(e) = stdin().read_to_string(&mut buf) {
  1380. output.push(format!("Failed to read from stdin: {e}"));
  1381. return
  1382. };
  1383. buf
  1384. }
  1385. 1 => input[0].clone(),
  1386. _ => {
  1387. output.push(String::from("Multiline input provided"));
  1388. return
  1389. }
  1390. };
  1391. let params = match DaoParams::from_toml_str(&buf) {
  1392. Ok(p) => p,
  1393. Err(e) => {
  1394. output.push(format!("Error while parsing DAO params: {e}"));
  1395. return
  1396. }
  1397. };
  1398. if let Err(e) = drk.read().await.import_dao(parts[2], &params, output).await {
  1399. output.push(format!("Failed to import DAO: {e}"))
  1400. }
  1401. }
  1402. /// Auxiliary function to define the dao update keys subcommand handling.
  1403. async fn handle_dao_update_keys(
  1404. drk: &DrkPtr,
  1405. parts: &[&str],
  1406. input: &[String],
  1407. output: &mut Vec<String>,
  1408. ) {
  1409. // Check correct subcommand structure
  1410. if parts.len() != 2 {
  1411. output.push(String::from("Malformed `dao update-keys` subcommand"));
  1412. output.push(String::from("Usage: dao update-keys"));
  1413. return
  1414. }
  1415. // Parse line from input or fallback to stdin if its empty
  1416. let buf = match input.len() {
  1417. 0 => {
  1418. let mut buf = String::new();
  1419. if let Err(e) = stdin().read_to_string(&mut buf) {
  1420. output.push(format!("Failed to read from stdin: {e}"));
  1421. return
  1422. };
  1423. buf
  1424. }
  1425. 1 => input[0].clone(),
  1426. _ => {
  1427. output.push(String::from("Multiline input provided"));
  1428. return
  1429. }
  1430. };
  1431. let params = match DaoParams::from_toml_str(&buf) {
  1432. Ok(p) => p,
  1433. Err(e) => {
  1434. output.push(format!("Error while parsing DAO params: {e}"));
  1435. return
  1436. }
  1437. };
  1438. if let Err(e) = drk.read().await.update_dao_keys(&params, output).await {
  1439. output.push(format!("Failed to update DAO keys: {e}"))
  1440. }
  1441. }
  1442. /// Auxiliary function to define the dao list subcommand handling.
  1443. async fn handle_dao_list(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1444. // Check correct subcommand structure
  1445. if parts.len() != 2 && parts.len() != 3 {
  1446. output.push(String::from("Malformed `dao list` subcommand"));
  1447. output.push(String::from("Usage: dao list [name]"));
  1448. return
  1449. }
  1450. let name = if parts.len() == 3 { Some(String::from(parts[2])) } else { None };
  1451. if let Err(e) = drk.read().await.dao_list(&name, output).await {
  1452. output.push(format!("Failed to list DAO: {e}"))
  1453. }
  1454. }
  1455. /// Auxiliary function to define the dao balance subcommand handling.
  1456. async fn handle_dao_balance(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1457. // Check correct subcommand structure
  1458. if parts.len() != 3 {
  1459. output.push(String::from("Malformed `dao balance` subcommand"));
  1460. output.push(String::from("Usage: dao balance <name>"));
  1461. return
  1462. }
  1463. let lock = drk.read().await;
  1464. let balmap = match lock.dao_balance(parts[2]).await {
  1465. Ok(b) => b,
  1466. Err(e) => {
  1467. output.push(format!("Failed to fetch DAO balance: {e}"));
  1468. return
  1469. }
  1470. };
  1471. let aliases_map = match lock.get_aliases_mapped_by_token().await {
  1472. Ok(m) => m,
  1473. Err(e) => {
  1474. output.push(format!("Failed to fetch aliases map: {e}"));
  1475. return
  1476. }
  1477. };
  1478. let mut table = Table::new();
  1479. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  1480. table.set_titles(row!["Token ID", "Aliases", "Balance"]);
  1481. for (token_id, balance) in balmap.iter() {
  1482. let aliases = match aliases_map.get(token_id) {
  1483. Some(a) => a,
  1484. None => "-",
  1485. };
  1486. table.add_row(row![token_id, aliases, encode_base10(*balance, BALANCE_BASE10_DECIMALS)]);
  1487. }
  1488. if table.is_empty() {
  1489. output.push(String::from("No unspent balances found"))
  1490. } else {
  1491. output.push(format!("{table}"));
  1492. }
  1493. }
  1494. /// Auxiliary function to define the dao mint subcommand handling.
  1495. async fn handle_dao_mint(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1496. // Check correct subcommand structure
  1497. if parts.len() != 3 {
  1498. output.push(String::from("Malformed `dao mint` subcommand"));
  1499. output.push(String::from("Usage: dao mint <name>"));
  1500. return
  1501. }
  1502. match drk.read().await.dao_mint(parts[2]).await {
  1503. Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
  1504. Err(e) => output.push(format!("Failed to mint DAO: {e}")),
  1505. }
  1506. }
  1507. /// Auxiliary function to define the dao propose transfer subcommand handling.
  1508. async fn handle_dao_propose_transfer(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1509. // Check correct subcommand structure
  1510. if parts.len() < 7 || parts.len() > 9 {
  1511. output.push(String::from("Malformed `dao proposal-transfer` subcommand"));
  1512. output.push(String::from("Usage: dao proposal-transfer <name> <duration> <amount> <token> <recipient> [spend-hook] [user-data]"));
  1513. return
  1514. }
  1515. let duration = match u64::from_str(parts[3]) {
  1516. Ok(d) => d,
  1517. Err(e) => {
  1518. output.push(format!("Invalid duration: {e}"));
  1519. return
  1520. }
  1521. };
  1522. let amount = String::from(parts[4]);
  1523. if let Err(e) = f64::from_str(&amount) {
  1524. output.push(format!("Invalid amount: {e}"));
  1525. return
  1526. }
  1527. let lock = drk.read().await;
  1528. let token_id = match lock.get_token(String::from(parts[5])).await {
  1529. Ok(t) => t,
  1530. Err(e) => {
  1531. output.push(format!("Invalid token ID: {e}"));
  1532. return
  1533. }
  1534. };
  1535. let rcpt = match PublicKey::from_str(parts[6]) {
  1536. Ok(r) => r,
  1537. Err(e) => {
  1538. output.push(format!("Invalid recipient: {e}"));
  1539. return
  1540. }
  1541. };
  1542. let mut index = 7;
  1543. let spend_hook = if index < parts.len() {
  1544. match FuncId::from_str(parts[index]) {
  1545. Ok(s) => Some(s),
  1546. Err(e) => {
  1547. output.push(format!("Invalid spend hook: {e}"));
  1548. return
  1549. }
  1550. }
  1551. } else {
  1552. None
  1553. };
  1554. index += 1;
  1555. let user_data = if index < parts.len() {
  1556. let bytes = match bs58::decode(&parts[index]).into_vec() {
  1557. Ok(b) => b,
  1558. Err(e) => {
  1559. output.push(format!("Invalid user data: {e}"));
  1560. return
  1561. }
  1562. };
  1563. let bytes: [u8; 32] = match bytes.try_into() {
  1564. Ok(b) => b,
  1565. Err(e) => {
  1566. output.push(format!("Invalid user data: {e:?}"));
  1567. return
  1568. }
  1569. };
  1570. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  1571. Some(v) => v,
  1572. None => {
  1573. output.push(String::from("Invalid user data"));
  1574. return
  1575. }
  1576. };
  1577. Some(elem)
  1578. } else {
  1579. None
  1580. };
  1581. match drk
  1582. .read()
  1583. .await
  1584. .dao_propose_transfer(parts[2], duration, &amount, token_id, rcpt, spend_hook, user_data)
  1585. .await
  1586. {
  1587. Ok(proposal) => output.push(format!("Generated proposal: {}", proposal.bulla())),
  1588. Err(e) => output.push(format!("Failed to create DAO transfer proposal: {e}")),
  1589. }
  1590. }
  1591. /// Auxiliary function to define the dao propose generic subcommand handling.
  1592. async fn handle_dao_propose_generic(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1593. // Check correct subcommand structure
  1594. if parts.len() != 4 && parts.len() != 5 {
  1595. output.push(String::from("Malformed `dao proposal-generic` subcommand"));
  1596. output.push(String::from("Usage: dao proposal-generic <name> <duration> [user-data]"));
  1597. return
  1598. }
  1599. let duration = match u64::from_str(parts[3]) {
  1600. Ok(d) => d,
  1601. Err(e) => {
  1602. output.push(format!("Invalid duration: {e}"));
  1603. return
  1604. }
  1605. };
  1606. let user_data = if parts.len() == 5 {
  1607. let bytes = match bs58::decode(&parts[4]).into_vec() {
  1608. Ok(b) => b,
  1609. Err(e) => {
  1610. output.push(format!("Invalid user data: {e}"));
  1611. return
  1612. }
  1613. };
  1614. let bytes: [u8; 32] = match bytes.try_into() {
  1615. Ok(b) => b,
  1616. Err(e) => {
  1617. output.push(format!("Invalid user data: {e:?}"));
  1618. return
  1619. }
  1620. };
  1621. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  1622. Some(v) => v,
  1623. None => {
  1624. output.push(String::from("Invalid user data"));
  1625. return
  1626. }
  1627. };
  1628. Some(elem)
  1629. } else {
  1630. None
  1631. };
  1632. match drk.read().await.dao_propose_generic(parts[2], duration, user_data).await {
  1633. Ok(proposal) => output.push(format!("Generated proposal: {}", proposal.bulla())),
  1634. Err(e) => output.push(format!("Failed to create DAO generic proposal: {e}")),
  1635. }
  1636. }
  1637. /// Auxiliary function to define the dao proposals subcommand handling.
  1638. async fn handle_dao_proposals(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1639. // Check correct subcommand structure
  1640. if parts.len() != 3 {
  1641. output.push(String::from("Malformed `dao proposals` subcommand"));
  1642. output.push(String::from("Usage: dao proposals <name>"));
  1643. return
  1644. }
  1645. match drk.read().await.get_dao_proposals(parts[2]).await {
  1646. Ok(proposals) => {
  1647. for (i, proposal) in proposals.iter().enumerate() {
  1648. output.push(format!("{i}. {}", proposal.bulla()));
  1649. }
  1650. }
  1651. Err(e) => output.push(format!("Failed to retrieve DAO proposals: {e}")),
  1652. }
  1653. }
  1654. /// Auxiliary function to define the dao proposal subcommand handling.
  1655. async fn handle_dao_proposal(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1656. // Check correct subcommand structure
  1657. if parts.len() != 3 && parts.len() != 4 {
  1658. output.push(String::from("Malformed `dao proposal` subcommand"));
  1659. output.push(String::from("Usage: dao proposal [--(export|mint-proposal)] <bulla>"));
  1660. return
  1661. }
  1662. let mut index = 2;
  1663. let (export, mint_proposal) = if parts.len() == 4 {
  1664. index += 1;
  1665. match parts[index] {
  1666. "--export" => (true, false),
  1667. "--mint-proposal" => (false, true),
  1668. _ => {
  1669. output.push(String::from("Malformed `dao proposal` subcommand"));
  1670. output.push(String::from("Usage: dao proposal [--(export|mint-proposal)] <bulla>"));
  1671. return
  1672. }
  1673. }
  1674. } else {
  1675. (false, false)
  1676. };
  1677. let bulla = match DaoProposalBulla::from_str(parts[index]) {
  1678. Ok(b) => b,
  1679. Err(e) => {
  1680. output.push(format!("Invalid proposal bulla: {e}"));
  1681. return
  1682. }
  1683. };
  1684. let lock = drk.read().await;
  1685. let proposal = match lock.get_dao_proposal_by_bulla(&bulla).await {
  1686. Ok(p) => p,
  1687. Err(e) => {
  1688. output.push(format!("Failed to fetch DAO proposal: {e}"));
  1689. return
  1690. }
  1691. };
  1692. if export {
  1693. // Retrieve the DAO
  1694. let dao = match lock.get_dao_by_bulla(&proposal.proposal.dao_bulla).await {
  1695. Ok(d) => d,
  1696. Err(e) => {
  1697. output.push(format!("Failed to fetch DAO: {e}"));
  1698. return
  1699. }
  1700. };
  1701. // Encypt the proposal
  1702. let enc_note =
  1703. AeadEncryptedNote::encrypt(&proposal, &dao.params.dao.proposals_public_key, &mut OsRng)
  1704. .unwrap();
  1705. // Export it to base64
  1706. output.push(base64::encode(&serialize_async(&enc_note).await));
  1707. return
  1708. }
  1709. if mint_proposal {
  1710. // Identify proposal type by its auth calls
  1711. for call in &proposal.proposal.auth_calls {
  1712. // We only support transfer right now
  1713. if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
  1714. match lock.dao_transfer_proposal_tx(&proposal).await {
  1715. Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
  1716. Err(e) => output.push(format!("Failed to create DAO transfer proposal: {e}")),
  1717. }
  1718. return
  1719. }
  1720. }
  1721. // If proposal has no auth calls, we consider it a generic one
  1722. if proposal.proposal.auth_calls.is_empty() {
  1723. match lock.dao_generic_proposal_tx(&proposal).await {
  1724. Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
  1725. Err(e) => output.push(format!("Failed to create DAO generic proposal: {e}")),
  1726. }
  1727. return
  1728. }
  1729. output.push(String::from("Unsuported DAO proposal"));
  1730. return
  1731. }
  1732. output.push(format!("{proposal}"));
  1733. let mut contract_calls = "\nInvoked contracts:\n".to_string();
  1734. for call in proposal.proposal.auth_calls {
  1735. contract_calls.push_str(&format!(
  1736. "\tContract: {}\n\tFunction: {}\n\tData: ",
  1737. call.contract_id, call.function_code
  1738. ));
  1739. if call.auth_data.is_empty() {
  1740. contract_calls.push_str("-\n");
  1741. continue;
  1742. }
  1743. if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
  1744. // We know that the plaintext data live in the data plaintext vec
  1745. if proposal.data.is_none() {
  1746. contract_calls.push_str("-\n");
  1747. continue;
  1748. }
  1749. let coin: CoinAttributes = match deserialize_async(proposal.data.as_ref().unwrap())
  1750. .await
  1751. {
  1752. Ok(c) => c,
  1753. Err(e) => {
  1754. output.push(format!("Failed to deserialize transfer proposal coin data: {e}"));
  1755. return
  1756. }
  1757. };
  1758. let spend_hook = if coin.spend_hook == FuncId::none() {
  1759. "-".to_string()
  1760. } else {
  1761. format!("{}", coin.spend_hook)
  1762. };
  1763. let user_data = if coin.user_data == pallas::Base::ZERO {
  1764. "-".to_string()
  1765. } else {
  1766. format!("{:?}", coin.user_data)
  1767. };
  1768. contract_calls.push_str(&format!(
  1769. "\n\t\t{}: {}\n\t\t{}: {} ({})\n\t\t{}: {}\n\t\t{}: {}\n\t\t{}: {}\n\t\t{}: {}\n\n",
  1770. "Recipient",
  1771. coin.public_key,
  1772. "Amount",
  1773. coin.value,
  1774. encode_base10(coin.value, BALANCE_BASE10_DECIMALS),
  1775. "Token",
  1776. coin.token_id,
  1777. "Spend hook",
  1778. spend_hook,
  1779. "User data",
  1780. user_data,
  1781. "Blind",
  1782. coin.blind
  1783. ));
  1784. }
  1785. }
  1786. output.push(contract_calls);
  1787. let votes = match lock.get_dao_proposal_votes(&bulla).await {
  1788. Ok(v) => v,
  1789. Err(e) => {
  1790. output.push(format!("Failed to fetch DAO proposal votes: {e}"));
  1791. return
  1792. }
  1793. };
  1794. let mut total_yes_vote_value = 0;
  1795. let mut total_no_vote_value = 0;
  1796. let mut total_all_vote_value = 0;
  1797. let mut table = Table::new();
  1798. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  1799. table.set_titles(row!["Transaction", "Tokens", "Vote"]);
  1800. for vote in votes {
  1801. let vote_option = if vote.vote_option {
  1802. total_yes_vote_value += vote.all_vote_value;
  1803. "Yes"
  1804. } else {
  1805. total_no_vote_value += vote.all_vote_value;
  1806. "No"
  1807. };
  1808. total_all_vote_value += vote.all_vote_value;
  1809. table.add_row(row![
  1810. vote.tx_hash,
  1811. encode_base10(vote.all_vote_value, BALANCE_BASE10_DECIMALS),
  1812. vote_option
  1813. ]);
  1814. }
  1815. let outcome = if table.is_empty() {
  1816. output.push(String::from("Votes: No votes found"));
  1817. "Unknown"
  1818. } else {
  1819. output.push(String::from("Votes:"));
  1820. output.push(format!("{table}"));
  1821. output.push(format!(
  1822. "Total tokens votes: {}",
  1823. encode_base10(total_all_vote_value, BALANCE_BASE10_DECIMALS)
  1824. ));
  1825. let approval_ratio = (total_yes_vote_value as f64 * 100.0) / total_all_vote_value as f64;
  1826. output.push(format!(
  1827. "Total tokens Yes votes: {} ({approval_ratio:.2}%)",
  1828. encode_base10(total_yes_vote_value, BALANCE_BASE10_DECIMALS)
  1829. ));
  1830. output.push(format!(
  1831. "Total tokens No votes: {} ({:.2}%)",
  1832. encode_base10(total_no_vote_value, BALANCE_BASE10_DECIMALS),
  1833. (total_no_vote_value as f64 * 100.0) / total_all_vote_value as f64
  1834. ));
  1835. let dao = match lock.get_dao_by_bulla(&proposal.proposal.dao_bulla).await {
  1836. Ok(d) => d,
  1837. Err(e) => {
  1838. output.push(format!("Failed to fetch DAO: {e}"));
  1839. return
  1840. }
  1841. };
  1842. if total_all_vote_value >= dao.params.dao.quorum &&
  1843. approval_ratio >=
  1844. (dao.params.dao.approval_ratio_quot / dao.params.dao.approval_ratio_base)
  1845. as f64
  1846. {
  1847. "Approved"
  1848. } else {
  1849. "Rejected"
  1850. }
  1851. };
  1852. if let Some(exec_tx_hash) = proposal.exec_tx_hash {
  1853. output.push(format!("Proposal was executed on transaction: {exec_tx_hash}"));
  1854. return
  1855. }
  1856. // Retrieve next block height and current block time target,
  1857. // to compute their window.
  1858. let next_block_height = match lock.get_next_block_height().await {
  1859. Ok(n) => n,
  1860. Err(e) => {
  1861. output.push(format!("Failed to fetch next block height: {e}"));
  1862. return
  1863. }
  1864. };
  1865. let block_target = match lock.get_block_target().await {
  1866. Ok(b) => b,
  1867. Err(e) => {
  1868. output.push(format!("Failed to fetch block target: {e}"));
  1869. return
  1870. }
  1871. };
  1872. let current_window = blockwindow(next_block_height, block_target);
  1873. let end_time = proposal.proposal.creation_blockwindow + proposal.proposal.duration_blockwindows;
  1874. let (voting_status, proposal_status_message) = if current_window < end_time {
  1875. ("Ongoing", format!("Current proposal outcome: {outcome}"))
  1876. } else {
  1877. ("Concluded", format!("Proposal outcome: {outcome}"))
  1878. };
  1879. output.push(format!("Voting status: {voting_status}"));
  1880. output.push(proposal_status_message);
  1881. }
  1882. /// Auxiliary function to define the dao proposal import subcommand handling.
  1883. async fn handle_dao_proposal_import(
  1884. drk: &DrkPtr,
  1885. parts: &[&str],
  1886. input: &[String],
  1887. output: &mut Vec<String>,
  1888. ) {
  1889. // Check correct subcommand structure
  1890. if parts.len() != 2 {
  1891. output.push(String::from("Malformed `dao proposal-import` subcommand"));
  1892. output.push(String::from("Usage: dao proposal-import"));
  1893. return
  1894. }
  1895. // Parse line from input or fallback to stdin if its empty
  1896. let buf = match input.len() {
  1897. 0 => {
  1898. let mut buf = String::new();
  1899. if let Err(e) = stdin().read_to_string(&mut buf) {
  1900. output.push(format!("Failed to read from stdin: {e}"));
  1901. return
  1902. };
  1903. buf
  1904. }
  1905. 1 => input[0].clone(),
  1906. _ => {
  1907. output.push(String::from("Multiline input provided"));
  1908. return
  1909. }
  1910. };
  1911. let Some(bytes) = base64::decode(buf.trim()) else {
  1912. output.push(String::from("Failed to decode encrypted proposal data"));
  1913. return
  1914. };
  1915. let encrypted_proposal: AeadEncryptedNote = match deserialize_async(&bytes).await {
  1916. Ok(e) => e,
  1917. Err(e) => {
  1918. output.push(format!("Failed to deserialize encrypted proposal data: {e}"));
  1919. return
  1920. }
  1921. };
  1922. let lock = drk.read().await;
  1923. let daos = match lock.get_daos().await {
  1924. Ok(d) => d,
  1925. Err(e) => {
  1926. output.push(format!("Failed to retrieve DAOs: {e}"));
  1927. return
  1928. }
  1929. };
  1930. for dao in &daos {
  1931. // Check if we have the proposals key
  1932. let Some(proposals_secret_key) = dao.params.proposals_secret_key else { continue };
  1933. // Try to decrypt the proposal
  1934. let Ok(proposal) = encrypted_proposal.decrypt::<ProposalRecord>(&proposals_secret_key)
  1935. else {
  1936. continue
  1937. };
  1938. let proposal = match lock.get_dao_proposal_by_bulla(&proposal.bulla()).await {
  1939. Ok(p) => {
  1940. let mut our_proposal = p;
  1941. our_proposal.data = proposal.data;
  1942. our_proposal
  1943. }
  1944. Err(_) => proposal,
  1945. };
  1946. if let Err(e) = lock.put_dao_proposal(&proposal).await {
  1947. output.push(format!("Failed to put DAO proposal: {e}"));
  1948. }
  1949. }
  1950. output.push(String::from("Couldn't decrypt the proposal with out DAO keys"));
  1951. }
  1952. /// Auxiliary function to define the dao vote subcommand handling.
  1953. async fn handle_dao_vote(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1954. // Check correct subcommand structure
  1955. if parts.len() != 4 && parts.len() != 5 {
  1956. output.push(String::from("Malformed `dao vote` subcommand"));
  1957. output.push(String::from("Usage: dao vote <bulla> <vote> [vote-weight]"));
  1958. return
  1959. }
  1960. let bulla = match DaoProposalBulla::from_str(parts[2]) {
  1961. Ok(b) => b,
  1962. Err(e) => {
  1963. output.push(format!("Invalid proposal bulla: {e}"));
  1964. return
  1965. }
  1966. };
  1967. let vote = match u8::from_str(parts[3]) {
  1968. Ok(v) => {
  1969. if v > 1 {
  1970. output.push(String::from("Vote can be either 0 (NO) or 1 (YES)"));
  1971. return
  1972. }
  1973. v != 0
  1974. }
  1975. Err(e) => {
  1976. output.push(format!("Invalid vote: {e}"));
  1977. return
  1978. }
  1979. };
  1980. let weight = if parts.len() == 5 {
  1981. if let Err(e) = f64::from_str(parts[4]) {
  1982. output.push(format!("Invalid vote weight: {e}"));
  1983. return
  1984. }
  1985. match decode_base10(parts[4], BALANCE_BASE10_DECIMALS, true) {
  1986. Ok(w) => Some(w),
  1987. Err(e) => {
  1988. output.push(format!("Error while parsing vote weight: {e}"));
  1989. return
  1990. }
  1991. }
  1992. } else {
  1993. None
  1994. };
  1995. match drk.read().await.dao_vote(&bulla, vote, weight).await {
  1996. Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
  1997. Err(e) => output.push(format!("Failed to create DAO Vote transaction: {e}")),
  1998. }
  1999. }
  2000. /// Auxiliary function to define the dao exec subcommand handling.
  2001. async fn handle_dao_exec(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2002. // Check correct subcommand structure
  2003. if parts.len() != 3 && parts.len() != 4 {
  2004. output.push(String::from("Malformed `dao exec` subcommand"));
  2005. output.push(String::from("Usage: dao exec [--early] <bulla>"));
  2006. return
  2007. }
  2008. let mut index = 2;
  2009. let mut early = false;
  2010. if parts[index] == "--early" {
  2011. early = true;
  2012. index += 1;
  2013. }
  2014. let bulla = match DaoProposalBulla::from_str(parts[index]) {
  2015. Ok(b) => b,
  2016. Err(e) => {
  2017. output.push(format!("Invalid proposal bulla: {e}"));
  2018. return
  2019. }
  2020. };
  2021. let lock = drk.read().await;
  2022. let proposal = match lock.get_dao_proposal_by_bulla(&bulla).await {
  2023. Ok(p) => p,
  2024. Err(e) => {
  2025. output.push(format!("Failed to fetch DAO proposal: {e}"));
  2026. return
  2027. }
  2028. };
  2029. // Identify proposal type by its auth calls
  2030. for call in &proposal.proposal.auth_calls {
  2031. // We only support transfer right now
  2032. if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
  2033. match lock.dao_exec_transfer(&proposal, early).await {
  2034. Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
  2035. Err(e) => output.push(format!("Failed to execute DAO transfer proposal: {e}")),
  2036. };
  2037. return
  2038. }
  2039. }
  2040. // If proposal has no auth calls, we consider it a generic one
  2041. if proposal.proposal.auth_calls.is_empty() {
  2042. match lock.dao_exec_generic(&proposal, early).await {
  2043. Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
  2044. Err(e) => output.push(format!("Failed to execute DAO generic proposal: {e}")),
  2045. };
  2046. return
  2047. }
  2048. output.push(String::from("Unsuported DAO proposal"));
  2049. }
  2050. /// Auxiliary function to define the dao spent hook subcommand handling.
  2051. async fn handle_dao_spend_hook(parts: &[&str], output: &mut Vec<String>) {
  2052. // Check correct subcommand structure
  2053. if parts.len() != 2 {
  2054. output.push(String::from("Malformed `dao spent-hook` subcommand"));
  2055. output.push(String::from("Usage: dao spent-hook"));
  2056. return
  2057. }
  2058. let spend_hook =
  2059. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }.to_func_id();
  2060. output.push(format!("{spend_hook}"));
  2061. }
  2062. /// Auxiliary function to define the attach fee command handling.
  2063. async fn handle_attach_fee(drk: &DrkPtr, input: &[String], output: &mut Vec<String>) {
  2064. let mut tx = match parse_tx_from_input(input).await {
  2065. Ok(t) => t,
  2066. Err(e) => {
  2067. output.push(format!("Error while parsing transaction: {e}"));
  2068. return
  2069. }
  2070. };
  2071. match drk.read().await.attach_fee(&mut tx).await {
  2072. Ok(_) => output.push(base64::encode(&serialize_async(&tx).await)),
  2073. Err(e) => output.push(format!("Failed to attach the fee call to the transaction: {e}")),
  2074. }
  2075. }
  2076. /// Auxiliary function to define the inspect command handling.
  2077. async fn handle_inspect(input: &[String], output: &mut Vec<String>) {
  2078. match parse_tx_from_input(input).await {
  2079. Ok(tx) => output.push(format!("{tx:#?}")),
  2080. Err(e) => output.push(format!("Error while parsing transaction: {e}")),
  2081. }
  2082. }
  2083. /// Auxiliary function to define the broadcast command handling.
  2084. async fn handle_broadcast(drk: &DrkPtr, input: &[String], output: &mut Vec<String>) {
  2085. let tx = match parse_tx_from_input(input).await {
  2086. Ok(t) => t,
  2087. Err(e) => {
  2088. output.push(format!("Error while parsing transaction: {e}"));
  2089. return
  2090. }
  2091. };
  2092. let lock = drk.read().await;
  2093. if let Err(e) = lock.simulate_tx(&tx).await {
  2094. output.push(format!("Failed to simulate tx: {e}"));
  2095. return
  2096. };
  2097. if let Err(e) = lock.mark_tx_spend(&tx, output).await {
  2098. output.push(format!("Failed to mark transaction coins as spent: {e}"));
  2099. return
  2100. };
  2101. match lock.broadcast_tx(&tx, output).await {
  2102. Ok(txid) => output.push(format!("Transaction ID: {txid}")),
  2103. Err(e) => output.push(format!("Failed to broadcast transaction: {e}")),
  2104. }
  2105. }
  2106. /// Auxiliary function to define the subscribe command handling.
  2107. async fn handle_subscribe(
  2108. drk: &DrkPtr,
  2109. endpoint: &Url,
  2110. subscription_active: &mut bool,
  2111. subscription_task: &StoppableTaskPtr,
  2112. shell_sender: &Sender<Vec<String>>,
  2113. ex: &ExecutorPtr,
  2114. output: &mut Vec<String>,
  2115. ) {
  2116. if *subscription_active {
  2117. output.push(String::from("Subscription is already active!"));
  2118. return
  2119. }
  2120. // Start the subcristion task
  2121. let drk_ = drk.clone();
  2122. let endpoint_ = endpoint.clone();
  2123. let shell_sender_ = shell_sender.clone();
  2124. let ex_ = ex.clone();
  2125. subscription_task.clone().start(
  2126. async move { subscribe_blocks(&drk_, shell_sender_, endpoint_, &ex_).await },
  2127. |res| async {
  2128. match res {
  2129. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  2130. Err(e) => println!("Failed starting subscription task: {e}"),
  2131. }
  2132. },
  2133. Error::DetachedTaskStopped,
  2134. ex.clone(),
  2135. );
  2136. *subscription_active = true;
  2137. }
  2138. /// Auxiliary function to define the unsubscribe command handling.
  2139. async fn handle_unsubscribe(
  2140. subscription_active: &mut bool,
  2141. subscription_task: &StoppableTaskPtr,
  2142. output: &mut Vec<String>,
  2143. ) {
  2144. if !*subscription_active {
  2145. output.push(String::from("Subscription is already inactive!"));
  2146. return
  2147. }
  2148. subscription_task.stop().await;
  2149. *subscription_active = false;
  2150. }
  2151. /// Auxiliary function to define the scan command handling.
  2152. async fn handle_scan(
  2153. drk: &DrkPtr,
  2154. subscription_active: &bool,
  2155. parts: &[&str],
  2156. output: &mut Vec<String>,
  2157. print: &bool,
  2158. ) {
  2159. if *subscription_active {
  2160. append_or_print(output, None, print, vec![String::from("Subscription is already active!")])
  2161. .await;
  2162. return
  2163. }
  2164. // Check correct command structure
  2165. if parts.len() != 1 && parts.len() != 3 {
  2166. append_or_print(output, None, print, vec![String::from("Malformed `scan` command")]).await;
  2167. return
  2168. }
  2169. // Check if reset was requested
  2170. let lock = drk.read().await;
  2171. if parts.len() == 3 {
  2172. if parts[1] != "--reset" {
  2173. append_or_print(
  2174. output,
  2175. None,
  2176. print,
  2177. vec![
  2178. String::from("Malformed `scan` command"),
  2179. String::from("Usage: scan --reset <height>"),
  2180. ],
  2181. )
  2182. .await;
  2183. return
  2184. }
  2185. let height = match u32::from_str(parts[2]) {
  2186. Ok(h) => h,
  2187. Err(e) => {
  2188. append_or_print(output, None, print, vec![format!("Invalid reset height: {e}")])
  2189. .await;
  2190. return
  2191. }
  2192. };
  2193. let mut buf = vec![];
  2194. if let Err(e) = lock.reset_to_height(height, &mut buf).await {
  2195. buf.push(format!("Failed during wallet reset: {e}"));
  2196. append_or_print(output, None, print, buf).await;
  2197. return
  2198. }
  2199. append_or_print(output, None, print, buf).await;
  2200. }
  2201. if let Err(e) = lock.scan_blocks(output, None, print).await {
  2202. append_or_print(output, None, print, vec![format!("Failed during scanning: {e}")]).await;
  2203. return
  2204. }
  2205. append_or_print(output, None, print, vec![String::from("Finished scanning blockchain")]).await;
  2206. }
  2207. /// Auxiliary function to define the explorer command handling.
  2208. async fn handle_explorer(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
  2209. // Check correct command structure
  2210. if parts.len() < 2 {
  2211. output.push(String::from("Malformed `explorer` command"));
  2212. output.push(String::from(
  2213. "Usage: explorer (fetch-tx|simulate-tx|txs-history|clear-reverted|scanned-blocks)",
  2214. ));
  2215. return
  2216. }
  2217. // Handle subcommand
  2218. match parts[1] {
  2219. "fetch-tx" => handle_explorer_fetch_tx(drk, parts, output).await,
  2220. "simulate-tx" => handle_explorer_simulate_tx(drk, parts, input, output).await,
  2221. "txs-history" => handle_explorer_txs_history(drk, parts, output).await,
  2222. "clear-reverted" => handle_explorer_clear_reverted(drk, parts, output).await,
  2223. "scanned-blocks" => handle_explorer_scanned_blocks(drk, parts, output).await,
  2224. _ => {
  2225. output.push(format!("Unreconized explorer subcommand: {}", parts[1]));
  2226. output.push(String::from(
  2227. "Usage: explorer (fetch-tx|simulate-tx|txs-history|clear-reverted|scanned-blocks)",
  2228. ));
  2229. }
  2230. }
  2231. }
  2232. /// Auxiliary function to define the explorer fetch transaction subcommand handling.
  2233. async fn handle_explorer_fetch_tx(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2234. // Check correct subcommand structure
  2235. if parts.len() != 3 && parts.len() != 4 {
  2236. output.push(String::from("Malformed `explorer fetch-tx` subcommand"));
  2237. output.push(String::from("Usage: explorer fetch-tx [--encode] <tx-hash>"));
  2238. return
  2239. }
  2240. let mut index = 2;
  2241. let mut encode = false;
  2242. if parts[index] == "--encode" {
  2243. encode = true;
  2244. index += 1;
  2245. }
  2246. let hash = match blake3::Hash::from_hex(parts[index]) {
  2247. Ok(h) => h,
  2248. Err(e) => {
  2249. output.push(format!("Invalid transaction hash: {e}"));
  2250. return
  2251. }
  2252. };
  2253. let tx_hash = TransactionHash(*hash.as_bytes());
  2254. let tx = match drk.read().await.get_tx(&tx_hash).await {
  2255. Ok(tx) => tx,
  2256. Err(e) => {
  2257. output.push(format!("Failed to fetch transaction: {e}"));
  2258. return
  2259. }
  2260. };
  2261. let Some(tx) = tx else {
  2262. output.push(String::from("Transaction was not found"));
  2263. return
  2264. };
  2265. // Make sure the tx is correct
  2266. if tx.hash() != tx_hash {
  2267. output.push(format!("Transaction hash missmatch: {tx_hash} - {}", tx.hash()));
  2268. return
  2269. }
  2270. if encode {
  2271. output.push(base64::encode(&serialize_async(&tx).await));
  2272. return
  2273. }
  2274. output.push(format!("Transaction ID: {tx_hash}"));
  2275. output.push(format!("{tx:?}"));
  2276. }
  2277. /// Auxiliary function to define the explorer simulate transaction subcommand handling.
  2278. async fn handle_explorer_simulate_tx(
  2279. drk: &DrkPtr,
  2280. parts: &[&str],
  2281. input: &[String],
  2282. output: &mut Vec<String>,
  2283. ) {
  2284. // Check correct subcommand structure
  2285. if parts.len() != 2 {
  2286. output.push(String::from("Malformed `explorer simulate-tx` subcommand"));
  2287. output.push(String::from("Usage: explorer simulate-tx"));
  2288. return
  2289. }
  2290. let tx = match parse_tx_from_input(input).await {
  2291. Ok(t) => t,
  2292. Err(e) => {
  2293. output.push(format!("Error while parsing transaction: {e}"));
  2294. return
  2295. }
  2296. };
  2297. match drk.read().await.simulate_tx(&tx).await {
  2298. Ok(is_valid) => {
  2299. output.push(format!("Transaction ID: {}", tx.hash()));
  2300. output.push(format!("State: {}", if is_valid { "valid" } else { "invalid" }));
  2301. }
  2302. Err(e) => output.push(format!("Failed to simulate tx: {e}")),
  2303. }
  2304. }
  2305. /// Auxiliary function to define the explorer transactions history subcommand handling.
  2306. async fn handle_explorer_txs_history(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2307. // Check correct command structure
  2308. if parts.len() < 2 || parts.len() > 4 {
  2309. output.push(String::from("Malformed `explorer txs-history` command"));
  2310. output.push(String::from("Usage: explorer txs-history [--encode] [tx-hash]"));
  2311. return
  2312. }
  2313. let lock = drk.read().await;
  2314. if parts.len() > 2 {
  2315. let mut index = 2;
  2316. let mut encode = false;
  2317. if parts[index] == "--encode" {
  2318. encode = true;
  2319. index += 1;
  2320. }
  2321. let (tx_hash, status, block_height, tx) =
  2322. match lock.get_tx_history_record(parts[index]).await {
  2323. Ok(i) => i,
  2324. Err(e) => {
  2325. output.push(format!("Failed to fetch transaction: {e}"));
  2326. return
  2327. }
  2328. };
  2329. if encode {
  2330. output.push(base64::encode(&serialize_async(&tx).await));
  2331. return
  2332. }
  2333. output.push(format!("Transaction ID: {tx_hash}"));
  2334. output.push(format!("Status: {status}"));
  2335. match block_height {
  2336. Some(block_height) => output.push(format!("Block height: {block_height}")),
  2337. None => output.push(String::from("Block height: -")),
  2338. }
  2339. output.push(format!("{tx:?}"));
  2340. return
  2341. }
  2342. let map = match lock.get_txs_history() {
  2343. Ok(m) => m,
  2344. Err(e) => {
  2345. output.push(format!("Failed to retrieve transactions history records: {e}"));
  2346. return
  2347. }
  2348. };
  2349. // Create a prettytable with the new data:
  2350. let mut table = Table::new();
  2351. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  2352. table.set_titles(row!["Transaction Hash", "Status", "Block Height"]);
  2353. for (txs_hash, status, block_height) in map.iter() {
  2354. let block_height = match block_height {
  2355. Some(block_height) => block_height.to_string(),
  2356. None => String::from("-"),
  2357. };
  2358. table.add_row(row![txs_hash, status, block_height]);
  2359. }
  2360. if table.is_empty() {
  2361. output.push(String::from("No transactions found"));
  2362. } else {
  2363. output.push(format!("{table}"));
  2364. }
  2365. }
  2366. /// Auxiliary function to define the explorer clear reverted subcommand handling.
  2367. async fn handle_explorer_clear_reverted(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2368. // Check correct subcommand structure
  2369. if parts.len() != 2 {
  2370. output.push(String::from("Malformed `explorer clear-reverted` subcommand"));
  2371. output.push(String::from("Usage: explorer clear-reverted"));
  2372. return
  2373. }
  2374. if let Err(e) = drk.read().await.remove_reverted_txs(output) {
  2375. output.push(format!("Failed to remove reverted transactions: {e}"));
  2376. }
  2377. }
  2378. /// Auxiliary function to define the explorer scanned blocks subcommand handling.
  2379. async fn handle_explorer_scanned_blocks(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2380. // Check correct subcommand structure
  2381. if parts.len() != 2 && parts.len() != 3 {
  2382. output.push(String::from("Malformed `explorer scanned-blocks` subcommand"));
  2383. output.push(String::from("Usage: explorer scanned-blocks [height]"));
  2384. return
  2385. }
  2386. let lock = drk.read().await;
  2387. if parts.len() == 3 {
  2388. let height = match u32::from_str(parts[2]) {
  2389. Ok(d) => d,
  2390. Err(e) => {
  2391. output.push(format!("Invalid height: {e}"));
  2392. return
  2393. }
  2394. };
  2395. match lock.get_scanned_block_hash(&height) {
  2396. Ok(hash) => {
  2397. output.push(format!("Height: {height}"));
  2398. output.push(format!("Hash: {hash}"));
  2399. }
  2400. Err(e) => output.push(format!("Failed to retrieve scanned block record: {e}")),
  2401. };
  2402. return
  2403. }
  2404. let map = match lock.get_scanned_block_records() {
  2405. Ok(m) => m,
  2406. Err(e) => {
  2407. output.push(format!("Failed to retrieve scanned blocks records: {e}"));
  2408. return
  2409. }
  2410. };
  2411. // Create a prettytable with the new data:
  2412. let mut table = Table::new();
  2413. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  2414. table.set_titles(row!["Height", "Hash"]);
  2415. for (height, hash) in map.iter() {
  2416. table.add_row(row![height, hash]);
  2417. }
  2418. if table.is_empty() {
  2419. output.push(String::from("No scanned blocks records found"));
  2420. } else {
  2421. output.push(format!("{table}"));
  2422. }
  2423. }
  2424. /// Auxiliary function to define the alias command handling.
  2425. async fn handle_alias(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2426. // Check correct command structure
  2427. if parts.len() < 2 {
  2428. output.push(String::from("Malformed `alias` command"));
  2429. output.push(String::from("Usage: alias (add|show|remove)"));
  2430. return
  2431. }
  2432. // Handle subcommand
  2433. match parts[1] {
  2434. "add" => handle_alias_add(drk, parts, output).await,
  2435. "show" => handle_alias_show(drk, parts, output).await,
  2436. "remove" => handle_alias_remove(drk, parts, output).await,
  2437. _ => {
  2438. output.push(format!("Unreconized alias subcommand: {}", parts[1]));
  2439. output.push(String::from("Usage: alias (add|show|remove)"));
  2440. }
  2441. }
  2442. }
  2443. /// Auxiliary function to define the alias add subcommand handling.
  2444. async fn handle_alias_add(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2445. // Check correct subcommand structure
  2446. if parts.len() != 4 {
  2447. output.push(String::from("Malformed `alias add` subcommand"));
  2448. output.push(String::from("Usage: alias add <alias> <token>"));
  2449. return
  2450. }
  2451. if parts[2].len() > 5 {
  2452. output.push(String::from("Error: Alias exceeds 5 characters"));
  2453. return
  2454. }
  2455. let token_id = match TokenId::from_str(parts[3]) {
  2456. Ok(t) => t,
  2457. Err(e) => {
  2458. output.push(format!("Invalid Token ID: {e}"));
  2459. return
  2460. }
  2461. };
  2462. if let Err(e) = drk.read().await.add_alias(String::from(parts[2]), token_id, output).await {
  2463. output.push(format!("Failed to add alias: {e}"));
  2464. }
  2465. }
  2466. /// Auxiliary function to define the alias show subcommand handling.
  2467. async fn handle_alias_show(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2468. // Check correct command structure
  2469. if parts.len() != 2 && parts.len() != 4 && parts.len() != 6 {
  2470. output.push(String::from("Malformed `alias show` command"));
  2471. output.push(String::from("Usage: alias show [-a, --alias <alias>] [-t, --token <token>]"));
  2472. return
  2473. }
  2474. let mut alias = None;
  2475. let mut token_id = None;
  2476. if parts.len() > 2 {
  2477. let mut index = 2;
  2478. if parts[index] == "-a" || parts[index] == "--alias" {
  2479. alias = Some(String::from(parts[index + 1]));
  2480. index += 2;
  2481. }
  2482. if index < parts.len() && (parts[index] == "-t" || parts[index] == "--token") {
  2483. match TokenId::from_str(parts[index + 1]) {
  2484. Ok(t) => token_id = Some(t),
  2485. Err(e) => {
  2486. output.push(format!("Invalid Token ID: {e}"));
  2487. return
  2488. }
  2489. };
  2490. index += 2;
  2491. }
  2492. // Check alias again in case it was after token
  2493. if index < parts.len() && (parts[index] == "-a" || parts[index] == "--alias") {
  2494. alias = Some(String::from(parts[index + 1]));
  2495. }
  2496. }
  2497. let map = match drk.read().await.get_aliases(alias, token_id).await {
  2498. Ok(m) => m,
  2499. Err(e) => {
  2500. output.push(format!("Failed to fetch aliases map: {e}"));
  2501. return
  2502. }
  2503. };
  2504. // Create a prettytable with the new data:
  2505. let mut table = Table::new();
  2506. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  2507. table.set_titles(row!["Alias", "Token ID"]);
  2508. for (alias, token_id) in map.iter() {
  2509. table.add_row(row![alias, token_id]);
  2510. }
  2511. if table.is_empty() {
  2512. output.push(String::from("No aliases found"));
  2513. } else {
  2514. output.push(format!("{table}"));
  2515. }
  2516. }
  2517. /// Auxiliary function to define the alias remove subcommand handling.
  2518. async fn handle_alias_remove(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2519. // Check correct subcommand structure
  2520. if parts.len() != 3 {
  2521. output.push(String::from("Malformed `alias remove` subcommand"));
  2522. output.push(String::from("Usage: alias remove <alias>"));
  2523. return
  2524. }
  2525. if let Err(e) = drk.read().await.remove_alias(String::from(parts[2]), output).await {
  2526. output.push(format!("Failed to remove alias: {e}"));
  2527. }
  2528. }
  2529. /// Auxiliary function to define the token command handling.
  2530. async fn handle_token(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2531. // Check correct command structure
  2532. if parts.len() < 2 {
  2533. output.push(String::from("Malformed `token` command"));
  2534. output.push(String::from("Usage: token (import|generate-mint|list|mint|freeze)"));
  2535. return
  2536. }
  2537. // Handle subcommand
  2538. match parts[1] {
  2539. "import" => handle_token_import(drk, parts, output).await,
  2540. "generate-mint" => handle_token_generate_mint(drk, parts, output).await,
  2541. "list" => handle_token_list(drk, parts, output).await,
  2542. "mint" => handle_token_mint(drk, parts, output).await,
  2543. "freeze" => handle_token_freeze(drk, parts, output).await,
  2544. _ => {
  2545. output.push(format!("Unreconized token subcommand: {}", parts[1]));
  2546. output.push(String::from("Usage: token (import|generate-mint|list|mint|freeze)"));
  2547. }
  2548. }
  2549. }
  2550. /// Auxiliary function to define the token import subcommand handling.
  2551. async fn handle_token_import(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2552. // Check correct subcommand structure
  2553. if parts.len() != 4 {
  2554. output.push(String::from("Malformed `token import` subcommand"));
  2555. output.push(String::from("Usage: token import <secret-key> <token-blind>"));
  2556. return
  2557. }
  2558. let mint_authority = match SecretKey::from_str(parts[2]) {
  2559. Ok(ma) => ma,
  2560. Err(e) => {
  2561. output.push(format!("Invalid mint authority: {e}"));
  2562. return
  2563. }
  2564. };
  2565. let token_blind = match BaseBlind::from_str(parts[3]) {
  2566. Ok(tb) => tb,
  2567. Err(e) => {
  2568. output.push(format!("Invalid token blind: {e}"));
  2569. return
  2570. }
  2571. };
  2572. match drk.read().await.import_mint_authority(mint_authority, token_blind).await {
  2573. Ok(token_id) => {
  2574. output.push(format!("Successfully imported mint authority for token ID: {token_id}"))
  2575. }
  2576. Err(e) => output.push(format!("Failed to import mint authority: {e}")),
  2577. }
  2578. }
  2579. /// Auxiliary function to define the token generate mint subcommand handling.
  2580. async fn handle_token_generate_mint(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2581. // Check correct subcommand structure
  2582. if parts.len() != 2 {
  2583. output.push(String::from("Malformed `token generate-mint` subcommand"));
  2584. output.push(String::from("Usage: token generate-mint"));
  2585. return
  2586. }
  2587. let mint_authority = SecretKey::random(&mut OsRng);
  2588. let token_blind = BaseBlind::random(&mut OsRng);
  2589. match drk.read().await.import_mint_authority(mint_authority, token_blind).await {
  2590. Ok(token_id) => {
  2591. output.push(format!("Successfully imported mint authority for token ID: {token_id}"))
  2592. }
  2593. Err(e) => output.push(format!("Failed to import mint authority: {e}")),
  2594. }
  2595. }
  2596. /// Auxiliary function to define the token list subcommand handling.
  2597. async fn handle_token_list(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2598. // Check correct subcommand structure
  2599. if parts.len() != 2 {
  2600. output.push(String::from("Malformed `token list` subcommand"));
  2601. output.push(String::from("Usage: token list"));
  2602. return
  2603. }
  2604. let lock = drk.read().await;
  2605. let tokens = match lock.get_mint_authorities().await {
  2606. Ok(m) => m,
  2607. Err(e) => {
  2608. output.push(format!("Failed to fetch mint authorities: {e}"));
  2609. return
  2610. }
  2611. };
  2612. let aliases_map = match lock.get_aliases_mapped_by_token().await {
  2613. Ok(m) => m,
  2614. Err(e) => {
  2615. output.push(format!("Failed to fetch aliases map: {e}"));
  2616. return
  2617. }
  2618. };
  2619. let mut table = Table::new();
  2620. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  2621. table.set_titles(row![
  2622. "Token ID",
  2623. "Aliases",
  2624. "Mint Authority",
  2625. "Token Blind",
  2626. "Frozen",
  2627. "Freeze Height"
  2628. ]);
  2629. for (token_id, authority, blind, frozen, freeze_height) in tokens {
  2630. let aliases = match aliases_map.get(&token_id.to_string()) {
  2631. Some(a) => a,
  2632. None => "-",
  2633. };
  2634. let freeze_height = match freeze_height {
  2635. Some(freeze_height) => freeze_height.to_string(),
  2636. None => String::from("-"),
  2637. };
  2638. table.add_row(row![token_id, aliases, authority, blind, frozen, freeze_height]);
  2639. }
  2640. if table.is_empty() {
  2641. output.push(String::from("No tokens found"));
  2642. } else {
  2643. output.push(format!("{table}"));
  2644. }
  2645. }
  2646. /// Auxiliary function to define the token mint subcommand handling.
  2647. async fn handle_token_mint(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2648. // Check correct command structure
  2649. if parts.len() < 5 || parts.len() > 7 {
  2650. output.push(String::from("Malformed `token mint` subcommand"));
  2651. output.push(String::from(
  2652. "Usage: token mint <token> <amount> <recipient> [spend-hook] [user-data]",
  2653. ));
  2654. return
  2655. }
  2656. let amount = String::from(parts[3]);
  2657. if let Err(e) = f64::from_str(&amount) {
  2658. output.push(format!("Invalid amount: {e}"));
  2659. return
  2660. }
  2661. let rcpt = match PublicKey::from_str(parts[4]) {
  2662. Ok(r) => r,
  2663. Err(e) => {
  2664. output.push(format!("Invalid recipient: {e}"));
  2665. return
  2666. }
  2667. };
  2668. let lock = drk.read().await;
  2669. let token_id = match lock.get_token(String::from(parts[2])).await {
  2670. Ok(t) => t,
  2671. Err(e) => {
  2672. output.push(format!("Invalid token ID: {e}"));
  2673. return
  2674. }
  2675. };
  2676. // Parse command
  2677. let mut index = 5;
  2678. let spend_hook = if index < parts.len() {
  2679. match FuncId::from_str(parts[index]) {
  2680. Ok(s) => Some(s),
  2681. Err(e) => {
  2682. output.push(format!("Invalid spend hook: {e}"));
  2683. return
  2684. }
  2685. }
  2686. } else {
  2687. None
  2688. };
  2689. index += 1;
  2690. let user_data = if index < parts.len() {
  2691. let bytes = match bs58::decode(&parts[index]).into_vec() {
  2692. Ok(b) => b,
  2693. Err(e) => {
  2694. output.push(format!("Invalid user data: {e}"));
  2695. return
  2696. }
  2697. };
  2698. let bytes: [u8; 32] = match bytes.try_into() {
  2699. Ok(b) => b,
  2700. Err(e) => {
  2701. output.push(format!("Invalid user data: {e:?}"));
  2702. return
  2703. }
  2704. };
  2705. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  2706. Some(v) => v,
  2707. None => {
  2708. output.push(String::from("Invalid user data"));
  2709. return
  2710. }
  2711. };
  2712. Some(elem)
  2713. } else {
  2714. None
  2715. };
  2716. match lock.mint_token(&amount, rcpt, token_id, spend_hook, user_data).await {
  2717. Ok(t) => output.push(base64::encode(&serialize_async(&t).await)),
  2718. Err(e) => output.push(format!("Failed to create token mint transaction: {e}")),
  2719. }
  2720. }
  2721. /// Auxiliary function to define the token freeze subcommand handling.
  2722. async fn handle_token_freeze(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2723. // Check correct subcommand structure
  2724. if parts.len() != 3 {
  2725. output.push(String::from("Malformed `token freeze` subcommand"));
  2726. output.push(String::from("Usage: token freeze <token>"));
  2727. return
  2728. }
  2729. let lock = drk.read().await;
  2730. let token_id = match lock.get_token(String::from(parts[2])).await {
  2731. Ok(t) => t,
  2732. Err(e) => {
  2733. output.push(format!("Invalid token ID: {e}"));
  2734. return
  2735. }
  2736. };
  2737. match lock.freeze_token(token_id).await {
  2738. Ok(t) => output.push(base64::encode(&serialize_async(&t).await)),
  2739. Err(e) => output.push(format!("Failed to create token freeze transaction: {e}")),
  2740. }
  2741. }
  2742. /// Auxiliary function to define the contract command handling.
  2743. async fn handle_contract(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2744. // Check correct command structure
  2745. if parts.len() < 2 {
  2746. output.push(String::from("Malformed `contract` command"));
  2747. output.push(String::from("Usage: contract (generate-deploy|list|deploy|lock)"));
  2748. return
  2749. }
  2750. // Handle subcommand
  2751. match parts[1] {
  2752. "generate-deploy" => handle_contract_generate_deploy(drk, parts, output).await,
  2753. "list" => handle_contract_list(drk, parts, output).await,
  2754. "deploy" => handle_contract_deploy(drk, parts, output).await,
  2755. "lock" => handle_contract_lock(drk, parts, output).await,
  2756. _ => {
  2757. output.push(format!("Unreconized contract subcommand: {}", parts[1]));
  2758. output.push(String::from("Usage: contract (generate-deploy|list|deploy|lock)"));
  2759. }
  2760. }
  2761. }
  2762. /// Auxiliary function to define the contract generate deploy subcommand handling.
  2763. async fn handle_contract_generate_deploy(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2764. // Check correct subcommand structure
  2765. if parts.len() != 2 {
  2766. output.push(String::from("Malformed `contract generate-deploy` subcommand"));
  2767. output.push(String::from("Usage: contract generate-deploy"));
  2768. return
  2769. }
  2770. if let Err(e) = drk.read().await.deploy_auth_keygen(output).await {
  2771. output.push(format!("Error creating deploy auth keypair: {e}"));
  2772. }
  2773. }
  2774. /// Auxiliary function to define the contract list subcommand handling.
  2775. async fn handle_contract_list(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2776. // Check correct subcommand structure
  2777. if parts.len() != 2 {
  2778. output.push(String::from("Malformed `contract list` subcommand"));
  2779. output.push(String::from("Usage: contract list"));
  2780. return
  2781. }
  2782. let auths = match drk.read().await.list_deploy_auth().await {
  2783. Ok(a) => a,
  2784. Err(e) => {
  2785. output.push(format!("Failed to fetch deploy authorities: {e}"));
  2786. return
  2787. }
  2788. };
  2789. let mut table = Table::new();
  2790. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  2791. table.set_titles(row!["Index", "Contract ID", "Frozen", "Freeze Height"]);
  2792. for (idx, contract_id, frozen, freeze_height) in auths {
  2793. let freeze_height = match freeze_height {
  2794. Some(freeze_height) => freeze_height.to_string(),
  2795. None => String::from("-"),
  2796. };
  2797. table.add_row(row![idx, contract_id, frozen, freeze_height]);
  2798. }
  2799. if table.is_empty() {
  2800. output.push(String::from("No deploy authorities found"));
  2801. } else {
  2802. output.push(format!("{table}"));
  2803. }
  2804. }
  2805. /// Auxiliary function to define the contract deploy subcommand handling.
  2806. async fn handle_contract_deploy(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2807. // Check correct subcommand structure
  2808. if parts.len() != 5 {
  2809. output.push(String::from("Malformed `contract deploy` subcommand"));
  2810. output.push(String::from("Usage: contract deploy <deploy-auth> <wasm-path> <deploy-ix>"));
  2811. return
  2812. }
  2813. let deploy_auth = match u64::from_str(parts[2]) {
  2814. Ok(d) => d,
  2815. Err(e) => {
  2816. output.push(format!("Invalid deploy authority: {e}"));
  2817. return
  2818. }
  2819. };
  2820. // Read the wasm bincode and deploy instruction
  2821. let file_path = match expand_path(parts[3]) {
  2822. Ok(p) => p,
  2823. Err(e) => {
  2824. output.push(format!("Error while expanding wasm bincode file path: {e}"));
  2825. return
  2826. }
  2827. };
  2828. let wasm_bin = match smol::fs::read(file_path).await {
  2829. Ok(w) => w,
  2830. Err(e) => {
  2831. output.push(format!("Error while reading wasm bincode file: {e}"));
  2832. return
  2833. }
  2834. };
  2835. let file_path = match expand_path(parts[4]) {
  2836. Ok(p) => p,
  2837. Err(e) => {
  2838. output.push(format!("Error while expanding deploy instruction file path: {e}"));
  2839. return
  2840. }
  2841. };
  2842. let deploy_ix = match smol::fs::read(file_path).await {
  2843. Ok(d) => d,
  2844. Err(e) => {
  2845. output.push(format!("Error while reading deploy instruction file: {e}"));
  2846. return
  2847. }
  2848. };
  2849. let lock = drk.read().await;
  2850. let mut tx = match lock.deploy_contract(deploy_auth, wasm_bin, deploy_ix).await {
  2851. Ok(v) => v,
  2852. Err(e) => {
  2853. output.push(format!("Error creating contract deployment tx: {e}"));
  2854. return
  2855. }
  2856. };
  2857. match lock.attach_fee(&mut tx).await {
  2858. Ok(_) => output.push(base64::encode(&serialize_async(&tx).await)),
  2859. Err(e) => output.push(format!("Failed to attach the fee call to the transaction: {e}")),
  2860. }
  2861. }
  2862. /// Auxiliary function to define the contract lock subcommand handling.
  2863. async fn handle_contract_lock(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2864. // Check correct subcommand structure
  2865. if parts.len() != 3 {
  2866. output.push(String::from("Malformed `contract lock` subcommand"));
  2867. output.push(String::from("Usage: contract lock <deploy-auth>"));
  2868. return
  2869. }
  2870. let deploy_auth = match u64::from_str(parts[2]) {
  2871. Ok(d) => d,
  2872. Err(e) => {
  2873. output.push(format!("Invalid deploy authority: {e}"));
  2874. return
  2875. }
  2876. };
  2877. let lock = drk.read().await;
  2878. let mut tx = match lock.lock_contract(deploy_auth).await {
  2879. Ok(v) => v,
  2880. Err(e) => {
  2881. output.push(format!("Error creating contract lock tx: {e}"));
  2882. return
  2883. }
  2884. };
  2885. match lock.attach_fee(&mut tx).await {
  2886. Ok(_) => output.push(base64::encode(&serialize_async(&tx).await)),
  2887. Err(e) => output.push(format!("Failed to attach the fee call to the transaction: {e}")),
  2888. }
  2889. }