interactive.rs 110 KB

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