interactive.rs 111 KB

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