main.rs 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661
  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. io::{stdin, Read},
  20. process::exit,
  21. str::FromStr,
  22. };
  23. use log::info;
  24. use prettytable::{format, row, Table};
  25. use rand::rngs::OsRng;
  26. use smol::{fs::read_to_string, stream::StreamExt};
  27. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  28. use url::Url;
  29. use darkfi::{
  30. async_daemonize, cli_desc,
  31. system::ExecutorPtr,
  32. util::{
  33. encoding::base64,
  34. parse::{decode_base10, encode_base10},
  35. path::{expand_path, get_config_path},
  36. },
  37. zk::halo2::Field,
  38. Error, Result,
  39. };
  40. use darkfi_dao_contract::{blockwindow, model::DaoProposalBulla, DaoFunction};
  41. use darkfi_money_contract::model::{Coin, CoinAttributes, TokenId};
  42. use darkfi_sdk::{
  43. crypto::{
  44. note::AeadEncryptedNote, BaseBlind, FuncId, FuncRef, Keypair, PublicKey, SecretKey,
  45. DAO_CONTRACT_ID,
  46. },
  47. pasta::{group::ff::PrimeField, pallas},
  48. tx::TransactionHash,
  49. };
  50. use darkfi_serial::{deserialize_async, serialize_async};
  51. use drk::{
  52. cli_util::{
  53. generate_completions, kaching, parse_token_pair, parse_tx_from_stdin, parse_value_pair,
  54. print_output,
  55. },
  56. dao::{DaoParams, ProposalRecord},
  57. interactive::interactive,
  58. money::BALANCE_BASE10_DECIMALS,
  59. swap::PartialSwapData,
  60. Drk,
  61. };
  62. const CONFIG_FILE: &str = "drk_config.toml";
  63. const CONFIG_FILE_CONTENTS: &str = include_str!("../drk_config.toml");
  64. // Dev Note: when adding/modifying args here,
  65. // don't forget to update cli_util::generate_completions()
  66. // and interactive::help().
  67. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  68. #[serde(default)]
  69. #[structopt(name = "drk", about = cli_desc!())]
  70. struct Args {
  71. #[structopt(short, long)]
  72. /// Configuration file to use
  73. config: Option<String>,
  74. #[structopt(short, long, default_value = "testnet")]
  75. /// Blockchain network to use
  76. network: String,
  77. #[structopt(subcommand)]
  78. /// Sub command to execute
  79. command: Subcmd,
  80. #[structopt(short, long)]
  81. /// Flag indicating whether you want some fun in your life
  82. fun: bool,
  83. #[structopt(short, long)]
  84. /// Set log file to ouput into
  85. log: Option<String>,
  86. #[structopt(short, parse(from_occurrences))]
  87. /// Increase verbosity (-vvv supported)
  88. verbose: u8,
  89. }
  90. // Dev Note: when adding/modifying commands here,
  91. // don't forget to update cli_util::generate_completions()
  92. #[derive(Clone, Debug, Deserialize, StructOpt)]
  93. enum Subcmd {
  94. /// Enter Drk interactive shell
  95. Interactive,
  96. /// Fun
  97. Kaching,
  98. /// Send a ping request to the darkfid RPC endpoint
  99. Ping,
  100. /// Generate a SHELL completion script and print to stdout
  101. Completions {
  102. /// The Shell you want to generate script for
  103. shell: String,
  104. },
  105. /// Wallet operations
  106. Wallet {
  107. #[structopt(subcommand)]
  108. /// Sub command to execute
  109. command: WalletSubcmd,
  110. },
  111. /// Read a transaction from stdin and mark its input coins as spent
  112. Spend,
  113. /// Unspend a coin
  114. Unspend {
  115. /// base58-encoded coin to mark as unspent
  116. coin: String,
  117. },
  118. /// Create a payment transaction
  119. Transfer {
  120. /// Amount to send
  121. amount: String,
  122. /// Token ID to send
  123. token: String,
  124. /// Recipient address
  125. recipient: String,
  126. /// Optional contract spend hook to use
  127. spend_hook: Option<String>,
  128. /// Optional user data to use
  129. user_data: Option<String>,
  130. #[structopt(long)]
  131. /// Split the output coin into two equal halves
  132. half_split: bool,
  133. },
  134. /// OTC atomic swap
  135. Otc {
  136. #[structopt(subcommand)]
  137. /// Sub command to execute
  138. command: OtcSubcmd,
  139. },
  140. /// DAO functionalities
  141. Dao {
  142. #[structopt(subcommand)]
  143. /// Sub command to execute
  144. command: DaoSubcmd,
  145. },
  146. /// Attach the fee call to a transaction given from stdin
  147. AttachFee,
  148. /// Inspect a transaction from stdin
  149. Inspect,
  150. /// Read a transaction from stdin and broadcast it
  151. Broadcast,
  152. /// Scan the blockchain and parse relevant transactions
  153. Scan {
  154. #[structopt(long)]
  155. /// Reset wallet state to provided block height and start scanning
  156. reset: Option<u32>,
  157. },
  158. /// Explorer related subcommands
  159. Explorer {
  160. #[structopt(subcommand)]
  161. /// Sub command to execute
  162. command: ExplorerSubcmd,
  163. },
  164. /// Manage Token aliases
  165. Alias {
  166. #[structopt(subcommand)]
  167. /// Sub command to execute
  168. command: AliasSubcmd,
  169. },
  170. /// Token functionalities
  171. Token {
  172. #[structopt(subcommand)]
  173. /// Sub command to execute
  174. command: TokenSubcmd,
  175. },
  176. /// Contract functionalities
  177. Contract {
  178. #[structopt(subcommand)]
  179. /// Sub command to execute
  180. command: ContractSubcmd,
  181. },
  182. }
  183. #[derive(Clone, Debug, Deserialize, StructOpt)]
  184. enum WalletSubcmd {
  185. /// Initialize wallet database
  186. Initialize,
  187. /// Generate a new keypair in the wallet
  188. Keygen,
  189. /// Query the wallet for known balances
  190. Balance,
  191. /// Get the default address in the wallet
  192. Address,
  193. /// Print all the addresses in the wallet
  194. Addresses,
  195. /// Set the default address in the wallet
  196. DefaultAddress {
  197. /// Identifier of the address
  198. index: usize,
  199. },
  200. /// Print all the secret keys from the wallet
  201. Secrets,
  202. /// Import secret keys from stdin into the wallet, separated by newlines
  203. ImportSecrets,
  204. /// Print the Merkle tree in the wallet
  205. Tree,
  206. /// Print all the coins in the wallet
  207. Coins,
  208. }
  209. #[derive(Clone, Debug, Deserialize, StructOpt)]
  210. enum OtcSubcmd {
  211. /// Initialize the first half of the atomic swap
  212. Init {
  213. /// Value pair to send:recv (11.55:99.42)
  214. #[structopt(short, long)]
  215. value_pair: String,
  216. /// Token pair to send:recv (f00:b4r)
  217. #[structopt(short, long)]
  218. token_pair: String,
  219. },
  220. /// Build entire swap tx given the first half from stdin
  221. Join,
  222. /// Inspect a swap half or the full swap tx from stdin
  223. Inspect,
  224. /// Sign a swap transaction given from stdin
  225. Sign,
  226. }
  227. #[derive(Clone, Debug, Deserialize, StructOpt)]
  228. enum DaoSubcmd {
  229. /// Create DAO parameters
  230. Create {
  231. /// The minimum amount of governance tokens needed to open a proposal for this DAO
  232. proposer_limit: String,
  233. /// Minimal threshold of participating total tokens needed for a proposal to pass
  234. quorum: String,
  235. /// Minimal threshold of participating total tokens needed for a proposal to
  236. /// be considered as strongly supported, enabling early execution.
  237. /// Must be greater or equal to normal quorum.
  238. early_exec_quorum: String,
  239. /// The ratio of winning votes/total votes needed for a proposal to pass (2 decimals)
  240. approval_ratio: f64,
  241. /// DAO's governance token ID
  242. gov_token_id: String,
  243. },
  244. /// View DAO data from stdin
  245. View,
  246. /// Import DAO data from stdin
  247. Import {
  248. /// Name identifier for the DAO
  249. name: String,
  250. },
  251. /// Update DAO keys from stdin
  252. UpdateKeys,
  253. /// List imported DAOs (or info about a specific one)
  254. List {
  255. /// Name identifier for the DAO (optional)
  256. name: Option<String>,
  257. },
  258. /// Show the balance of a DAO
  259. Balance {
  260. /// Name identifier for the DAO
  261. name: String,
  262. },
  263. /// Mint an imported DAO on-chain
  264. Mint {
  265. /// Name identifier for the DAO
  266. name: String,
  267. },
  268. /// Create a transfer proposal for a DAO
  269. ProposeTransfer {
  270. /// Name identifier for the DAO
  271. name: String,
  272. /// Duration of the proposal, in block windows
  273. duration: u64,
  274. /// Amount to send
  275. amount: String,
  276. /// Token ID to send
  277. token: String,
  278. /// Recipient address
  279. recipient: String,
  280. /// Optional contract spend hook to use
  281. spend_hook: Option<String>,
  282. /// Optional user data to use
  283. user_data: Option<String>,
  284. },
  285. /// Create a generic proposal for a DAO
  286. ProposeGeneric {
  287. /// Name identifier for the DAO
  288. name: String,
  289. /// Duration of the proposal, in block windows
  290. duration: u64,
  291. /// Optional user data to use
  292. user_data: Option<String>,
  293. },
  294. /// List DAO proposals
  295. Proposals {
  296. /// Name identifier for the DAO
  297. name: String,
  298. },
  299. /// View a DAO proposal data
  300. Proposal {
  301. /// Bulla identifier for the proposal
  302. bulla: String,
  303. #[structopt(long)]
  304. /// Encrypt the proposal and encode it to base64
  305. export: bool,
  306. #[structopt(long)]
  307. /// Create the proposal transaction
  308. mint_proposal: bool,
  309. },
  310. /// Import a base64 encoded and encrypted proposal from stdin
  311. ProposalImport,
  312. /// Vote on a given proposal
  313. Vote {
  314. /// Bulla identifier for the proposal
  315. bulla: String,
  316. /// Vote (0 for NO, 1 for YES)
  317. vote: u8,
  318. /// Optional vote weight (amount of governance tokens)
  319. vote_weight: Option<String>,
  320. },
  321. /// Execute a DAO proposal
  322. Exec {
  323. /// Bulla identifier for the proposal
  324. bulla: String,
  325. #[structopt(long)]
  326. /// Execute the proposal early
  327. early: bool,
  328. },
  329. /// Print the DAO contract base58-encoded spend hook
  330. SpendHook,
  331. }
  332. #[derive(Clone, Debug, Deserialize, StructOpt)]
  333. enum ExplorerSubcmd {
  334. /// Fetch a blockchain transaction by hash
  335. FetchTx {
  336. /// Transaction hash
  337. tx_hash: String,
  338. #[structopt(long)]
  339. /// Print the full transaction information
  340. full: bool,
  341. #[structopt(long)]
  342. /// Encode transaction to base58
  343. encode: bool,
  344. },
  345. /// Read a transaction from stdin and simulate it
  346. SimulateTx,
  347. /// Fetch broadcasted transactions history
  348. TxsHistory {
  349. /// Fetch specific history record (optional)
  350. tx_hash: Option<String>,
  351. #[structopt(long)]
  352. /// Encode specific history record transaction to base58
  353. encode: bool,
  354. },
  355. /// Remove reverted transactions from history
  356. ClearReverted,
  357. /// Fetch scanned blocks records
  358. ScannedBlocks {
  359. /// Fetch specific height record (optional)
  360. height: Option<u32>,
  361. },
  362. }
  363. #[derive(Clone, Debug, Deserialize, StructOpt)]
  364. enum AliasSubcmd {
  365. /// Create a Token alias
  366. Add {
  367. /// Token alias
  368. alias: String,
  369. /// Token to create alias for
  370. token: String,
  371. },
  372. /// Print alias info of optional arguments.
  373. /// If no argument is provided, list all the aliases in the wallet.
  374. Show {
  375. /// Token alias to search for
  376. #[structopt(short, long)]
  377. alias: Option<String>,
  378. /// Token to search alias for
  379. #[structopt(short, long)]
  380. token: Option<String>,
  381. },
  382. /// Remove a Token alias
  383. Remove {
  384. /// Token alias to remove
  385. alias: String,
  386. },
  387. }
  388. #[derive(Clone, Debug, Deserialize, StructOpt)]
  389. enum TokenSubcmd {
  390. /// Import a mint authority
  391. Import {
  392. /// Mint authority secret key
  393. secret_key: String,
  394. /// Mint authority token blind
  395. token_blind: String,
  396. },
  397. /// Generate a new mint authority
  398. GenerateMint,
  399. /// List token IDs with available mint authorities
  400. List,
  401. /// Mint tokens
  402. Mint {
  403. /// Token ID to mint
  404. token: String,
  405. /// Amount to mint
  406. amount: String,
  407. /// Recipient of the minted tokens
  408. recipient: String,
  409. /// Optional contract spend hook to use
  410. spend_hook: Option<String>,
  411. /// Optional user data to use
  412. user_data: Option<String>,
  413. },
  414. /// Freeze a token mint
  415. Freeze {
  416. /// Token ID to freeze
  417. token: String,
  418. },
  419. }
  420. #[derive(Clone, Debug, Deserialize, StructOpt)]
  421. enum ContractSubcmd {
  422. /// Generate a new deploy authority
  423. GenerateDeploy,
  424. /// List deploy authorities in the wallet
  425. List,
  426. /// Deploy a smart contract
  427. Deploy {
  428. /// Contract ID (deploy authority)
  429. deploy_auth: u64,
  430. /// Path to contract wasm bincode
  431. wasm_path: String,
  432. /// Path to serialized deploy instruction
  433. deploy_ix: String,
  434. },
  435. /// Lock a smart contract
  436. Lock {
  437. /// Contract ID (deploy authority)
  438. deploy_auth: u64,
  439. },
  440. }
  441. /// Defines a blockchain network configuration.
  442. /// Default values correspond to a local network.
  443. #[derive(Clone, Debug, serde::Deserialize, structopt::StructOpt, structopt_toml::StructOptToml)]
  444. #[structopt()]
  445. struct BlockchainNetwork {
  446. #[structopt(long, default_value = "~/.local/share/darkfi/drk/localnet/cache")]
  447. /// Path to blockchain cache database
  448. cache_path: String,
  449. #[structopt(long, default_value = "~/.local/share/darkfi/drk/localnet/wallet.db")]
  450. /// Path to wallet database
  451. wallet_path: String,
  452. #[structopt(long, default_value = "changeme")]
  453. /// Password for the wallet database
  454. wallet_pass: String,
  455. #[structopt(short, long, default_value = "tcp://127.0.0.1:8240")]
  456. /// darkfid JSON-RPC endpoint
  457. endpoint: Url,
  458. #[structopt(long, default_value = "~/.local/share/darkfi/drk/localnet/history.txt")]
  459. /// Path to interactive shell history file
  460. history_path: String,
  461. }
  462. /// Auxiliary function to parse darkfid configuration file and extract requested
  463. /// blockchain network config.
  464. async fn parse_blockchain_config(
  465. config: Option<String>,
  466. network: &str,
  467. ) -> Result<BlockchainNetwork> {
  468. // Grab config path
  469. let config_path = get_config_path(config, CONFIG_FILE)?;
  470. // Parse TOML file contents
  471. let contents = read_to_string(&config_path).await?;
  472. let contents: toml::Value = match toml::from_str(&contents) {
  473. Ok(v) => v,
  474. Err(e) => {
  475. eprintln!("Failed parsing TOML config: {e}");
  476. return Err(Error::ParseFailed("Failed parsing TOML config"))
  477. }
  478. };
  479. // Grab requested network config
  480. let Some(table) = contents.as_table() else { return Err(Error::ParseFailed("TOML not a map")) };
  481. let Some(network_configs) = table.get("network_config") else {
  482. return Err(Error::ParseFailed("TOML does not contain network configurations"))
  483. };
  484. let Some(network_configs) = network_configs.as_table() else {
  485. return Err(Error::ParseFailed("`network_config` not a map"))
  486. };
  487. let Some(network_config) = network_configs.get(network) else {
  488. return Err(Error::ParseFailed("TOML does not contain requested network configuration"))
  489. };
  490. let network_config = toml::to_string(&network_config).unwrap();
  491. let network_config =
  492. match BlockchainNetwork::from_iter_with_toml::<Vec<String>>(&network_config, vec![]) {
  493. Ok(v) => v,
  494. Err(e) => {
  495. eprintln!("Failed parsing requested network configuration: {e}");
  496. return Err(Error::ParseFailed("Failed parsing requested network configuration"))
  497. }
  498. };
  499. Ok(network_config)
  500. }
  501. /// Auxiliary function to create a `Drk` wallet for provided configuration.
  502. async fn new_wallet(
  503. cache_path: String,
  504. wallet_path: String,
  505. wallet_pass: String,
  506. endpoint: Option<Url>,
  507. ex: &ExecutorPtr,
  508. fun: bool,
  509. ) -> Drk {
  510. // Script kiddies protection
  511. if wallet_pass == "changeme" {
  512. eprintln!("Please don't use default wallet password...");
  513. exit(2);
  514. }
  515. match Drk::new(cache_path, wallet_path, wallet_pass, endpoint, ex, fun).await {
  516. Ok(wallet) => wallet,
  517. Err(e) => {
  518. eprintln!("Error initializing wallet: {e:?}");
  519. exit(2);
  520. }
  521. }
  522. }
  523. async_daemonize!(realmain);
  524. async fn realmain(args: Args, ex: ExecutorPtr) -> Result<()> {
  525. // Grab blockchain network configuration
  526. let blockchain_config = match args.network.as_str() {
  527. "localnet" => parse_blockchain_config(args.config, "localnet").await?,
  528. "testnet" => parse_blockchain_config(args.config, "testnet").await?,
  529. "mainnet" => parse_blockchain_config(args.config, "mainnet").await?,
  530. _ => {
  531. eprintln!("Unsupported chain `{}`", args.network);
  532. return Err(Error::UnsupportedChain)
  533. }
  534. };
  535. match args.command {
  536. Subcmd::Interactive => {
  537. let drk = new_wallet(
  538. blockchain_config.cache_path,
  539. blockchain_config.wallet_path,
  540. blockchain_config.wallet_pass,
  541. Some(blockchain_config.endpoint.clone()),
  542. &ex,
  543. args.fun,
  544. )
  545. .await
  546. .into_ptr();
  547. interactive(&drk, &blockchain_config.endpoint, &blockchain_config.history_path, &ex)
  548. .await;
  549. drk.read().await.stop_rpc_client().await?;
  550. Ok(())
  551. }
  552. Subcmd::Kaching => {
  553. if !args.fun {
  554. println!("Apparently you don't like fun...");
  555. return Ok(())
  556. }
  557. kaching().await;
  558. Ok(())
  559. }
  560. Subcmd::Ping => {
  561. let drk = new_wallet(
  562. blockchain_config.cache_path,
  563. blockchain_config.wallet_path,
  564. blockchain_config.wallet_pass,
  565. Some(blockchain_config.endpoint),
  566. &ex,
  567. args.fun,
  568. )
  569. .await;
  570. let mut output = vec![];
  571. if let Err(e) = drk.ping(&mut output).await {
  572. print_output(&output);
  573. return Err(e)
  574. };
  575. print_output(&output);
  576. drk.stop_rpc_client().await
  577. }
  578. Subcmd::Completions { shell } => {
  579. println!("{}", generate_completions(&shell)?);
  580. Ok(())
  581. }
  582. Subcmd::Wallet { command } => {
  583. let drk = new_wallet(
  584. blockchain_config.cache_path,
  585. blockchain_config.wallet_path,
  586. blockchain_config.wallet_pass,
  587. None,
  588. &ex,
  589. args.fun,
  590. )
  591. .await;
  592. match command {
  593. WalletSubcmd::Initialize => {
  594. if let Err(e) = drk.initialize_wallet().await {
  595. eprintln!("Error initializing wallet: {e:?}");
  596. exit(2);
  597. }
  598. if let Err(e) = drk.initialize_money().await {
  599. eprintln!("Failed to initialize Money: {e:?}");
  600. exit(2);
  601. }
  602. if let Err(e) = drk.initialize_dao().await {
  603. eprintln!("Failed to initialize DAO: {e:?}");
  604. exit(2);
  605. }
  606. if let Err(e) = drk.initialize_deployooor() {
  607. eprintln!("Failed to initialize Deployooor: {e:?}");
  608. exit(2);
  609. }
  610. }
  611. WalletSubcmd::Keygen => {
  612. let mut output = vec![];
  613. if let Err(e) = drk.money_keygen(&mut output).await {
  614. print_output(&output);
  615. eprintln!("Failed to generate keypair: {e:?}");
  616. exit(2);
  617. }
  618. print_output(&output);
  619. }
  620. WalletSubcmd::Balance => {
  621. let balmap = drk.money_balance().await?;
  622. let aliases_map = drk.get_aliases_mapped_by_token().await?;
  623. // Create a prettytable with the new data:
  624. let mut table = Table::new();
  625. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  626. table.set_titles(row!["Token ID", "Aliases", "Balance"]);
  627. for (token_id, balance) in balmap.iter() {
  628. let aliases = match aliases_map.get(token_id) {
  629. Some(a) => a,
  630. None => "-",
  631. };
  632. table.add_row(row![
  633. token_id,
  634. aliases,
  635. encode_base10(*balance, BALANCE_BASE10_DECIMALS)
  636. ]);
  637. }
  638. if table.is_empty() {
  639. println!("No unspent balances found");
  640. } else {
  641. println!("{table}");
  642. }
  643. }
  644. WalletSubcmd::Address => match drk.default_address().await {
  645. Ok(address) => println!("{address}"),
  646. Err(e) => {
  647. eprintln!("Failed to fetch default address: {e:?}");
  648. exit(2);
  649. }
  650. },
  651. WalletSubcmd::Addresses => {
  652. let addresses = drk.addresses().await?;
  653. // Create a prettytable with the new data:
  654. let mut table = Table::new();
  655. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  656. table.set_titles(row!["Key ID", "Public Key", "Secret Key", "Is Default"]);
  657. for (key_id, public_key, secret_key, is_default) in addresses {
  658. let is_default = match is_default {
  659. 1 => "*",
  660. _ => "",
  661. };
  662. table.add_row(row![key_id, public_key, secret_key, is_default]);
  663. }
  664. if table.is_empty() {
  665. println!("No addresses found");
  666. } else {
  667. println!("{table}");
  668. }
  669. }
  670. WalletSubcmd::DefaultAddress { index } => {
  671. if let Err(e) = drk.set_default_address(index) {
  672. eprintln!("Failed to set default address: {e:?}");
  673. exit(2);
  674. }
  675. }
  676. WalletSubcmd::Secrets => {
  677. for secret in drk.get_money_secrets().await? {
  678. println!("{secret}");
  679. }
  680. }
  681. WalletSubcmd::ImportSecrets => {
  682. let mut secrets = vec![];
  683. let lines = stdin().lines();
  684. for (i, line) in lines.enumerate() {
  685. if let Ok(line) = line {
  686. let bytes = bs58::decode(&line.trim()).into_vec()?;
  687. let Ok(secret) = deserialize_async(&bytes).await else {
  688. println!("Warning: Failed to deserialize secret on line {i}");
  689. continue
  690. };
  691. secrets.push(secret);
  692. }
  693. }
  694. let mut output = vec![];
  695. let pubkeys = match drk.import_money_secrets(secrets, &mut output).await {
  696. Ok(p) => {
  697. print_output(&output);
  698. p
  699. }
  700. Err(e) => {
  701. print_output(&output);
  702. eprintln!("Failed to import secret keys into wallet: {e:?}");
  703. exit(2);
  704. }
  705. };
  706. for key in pubkeys {
  707. println!("{key}");
  708. }
  709. }
  710. WalletSubcmd::Tree => {
  711. println!("{:#?}", drk.get_money_tree().await?);
  712. }
  713. WalletSubcmd::Coins => {
  714. let coins = drk.get_coins(true).await?;
  715. if coins.is_empty() {
  716. return Ok(())
  717. }
  718. let aliases_map = drk.get_aliases_mapped_by_token().await?;
  719. let mut table = Table::new();
  720. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  721. table.set_titles(row![
  722. "Coin",
  723. "Token ID",
  724. "Aliases",
  725. "Value",
  726. "Spend Hook",
  727. "User Data",
  728. "Creation Height",
  729. "Spent",
  730. "Spent Height",
  731. "Spent TX"
  732. ]);
  733. for coin in coins {
  734. let aliases = match aliases_map.get(&coin.0.note.token_id.to_string()) {
  735. Some(a) => a,
  736. None => "-",
  737. };
  738. let spend_hook = if coin.0.note.spend_hook != FuncId::none() {
  739. format!("{}", coin.0.note.spend_hook)
  740. } else {
  741. String::from("-")
  742. };
  743. let user_data = if coin.0.note.user_data != pallas::Base::ZERO {
  744. bs58::encode(&serialize_async(&coin.0.note.user_data).await)
  745. .into_string()
  746. .to_string()
  747. } else {
  748. String::from("-")
  749. };
  750. let spent_height = match coin.3 {
  751. Some(spent_height) => spent_height.to_string(),
  752. None => String::from("-"),
  753. };
  754. table.add_row(row![
  755. bs58::encode(&serialize_async(&coin.0.coin.inner()).await)
  756. .into_string()
  757. .to_string(),
  758. coin.0.note.token_id,
  759. aliases,
  760. format!(
  761. "{} ({})",
  762. coin.0.note.value,
  763. encode_base10(coin.0.note.value, BALANCE_BASE10_DECIMALS)
  764. ),
  765. spend_hook,
  766. user_data,
  767. coin.1,
  768. coin.2,
  769. spent_height,
  770. coin.4,
  771. ]);
  772. }
  773. println!("{table}");
  774. }
  775. }
  776. Ok(())
  777. }
  778. Subcmd::Spend => {
  779. let tx = parse_tx_from_stdin().await?;
  780. let drk = new_wallet(
  781. blockchain_config.cache_path,
  782. blockchain_config.wallet_path,
  783. blockchain_config.wallet_pass,
  784. None,
  785. &ex,
  786. args.fun,
  787. )
  788. .await;
  789. let mut output = vec![];
  790. if let Err(e) = drk.mark_tx_spend(&tx, &mut output).await {
  791. print_output(&output);
  792. eprintln!("Failed to mark transaction coins as spent: {e:?}");
  793. exit(2);
  794. };
  795. print_output(&output);
  796. Ok(())
  797. }
  798. Subcmd::Unspend { coin } => {
  799. let bytes: [u8; 32] = match bs58::decode(&coin).into_vec()?.try_into() {
  800. Ok(b) => b,
  801. Err(e) => {
  802. eprintln!("Invalid coin: {e:?}");
  803. exit(2);
  804. }
  805. };
  806. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  807. Some(v) => v,
  808. None => {
  809. eprintln!("Invalid coin");
  810. exit(2);
  811. }
  812. };
  813. let coin = Coin::from(elem);
  814. let drk = new_wallet(
  815. blockchain_config.cache_path,
  816. blockchain_config.wallet_path,
  817. blockchain_config.wallet_pass,
  818. None,
  819. &ex,
  820. args.fun,
  821. )
  822. .await;
  823. if let Err(e) = drk.unspend_coin(&coin).await {
  824. eprintln!("Failed to mark coin as unspent: {e:?}");
  825. exit(2);
  826. }
  827. Ok(())
  828. }
  829. Subcmd::Transfer { amount, token, recipient, spend_hook, user_data, half_split } => {
  830. let drk = new_wallet(
  831. blockchain_config.cache_path,
  832. blockchain_config.wallet_path,
  833. blockchain_config.wallet_pass,
  834. Some(blockchain_config.endpoint),
  835. &ex,
  836. args.fun,
  837. )
  838. .await;
  839. if let Err(e) = f64::from_str(&amount) {
  840. eprintln!("Invalid amount: {e:?}");
  841. exit(2);
  842. }
  843. let rcpt = match PublicKey::from_str(&recipient) {
  844. Ok(r) => r,
  845. Err(e) => {
  846. eprintln!("Invalid recipient: {e:?}");
  847. exit(2);
  848. }
  849. };
  850. let token_id = match drk.get_token(token).await {
  851. Ok(t) => t,
  852. Err(e) => {
  853. eprintln!("Invalid token alias: {e:?}");
  854. exit(2);
  855. }
  856. };
  857. let spend_hook = match spend_hook {
  858. Some(s) => match FuncId::from_str(&s) {
  859. Ok(s) => Some(s),
  860. Err(e) => {
  861. eprintln!("Invalid spend hook: {e:?}");
  862. exit(2);
  863. }
  864. },
  865. None => None,
  866. };
  867. let user_data = match user_data {
  868. Some(u) => {
  869. let bytes: [u8; 32] = match bs58::decode(&u).into_vec()?.try_into() {
  870. Ok(b) => b,
  871. Err(e) => {
  872. eprintln!("Invalid user data: {e:?}");
  873. exit(2);
  874. }
  875. };
  876. match pallas::Base::from_repr(bytes).into() {
  877. Some(v) => Some(v),
  878. None => {
  879. eprintln!("Invalid user data");
  880. exit(2);
  881. }
  882. }
  883. }
  884. None => None,
  885. };
  886. let tx = match drk
  887. .transfer(&amount, token_id, rcpt, spend_hook, user_data, half_split)
  888. .await
  889. {
  890. Ok(t) => t,
  891. Err(e) => {
  892. eprintln!("Failed to create payment transaction: {e:?}");
  893. exit(2);
  894. }
  895. };
  896. println!("{}", base64::encode(&serialize_async(&tx).await));
  897. drk.stop_rpc_client().await
  898. }
  899. Subcmd::Otc { command } => match command {
  900. OtcSubcmd::Init { value_pair, token_pair } => {
  901. let drk = new_wallet(
  902. blockchain_config.cache_path,
  903. blockchain_config.wallet_path,
  904. blockchain_config.wallet_pass,
  905. Some(blockchain_config.endpoint),
  906. &ex,
  907. args.fun,
  908. )
  909. .await;
  910. let value_pair = parse_value_pair(&value_pair)?;
  911. let token_pair = parse_token_pair(&drk, &token_pair).await?;
  912. let half = match drk.init_swap(value_pair, token_pair, None, None, None).await {
  913. Ok(h) => h,
  914. Err(e) => {
  915. eprintln!("Failed to create swap transaction half: {e:?}");
  916. exit(2);
  917. }
  918. };
  919. println!("{}", base64::encode(&serialize_async(&half).await));
  920. drk.stop_rpc_client().await
  921. }
  922. OtcSubcmd::Join => {
  923. let mut buf = String::new();
  924. stdin().read_to_string(&mut buf)?;
  925. let Some(bytes) = base64::decode(buf.trim()) else {
  926. eprintln!("Failed to decode partial swap data");
  927. exit(2);
  928. };
  929. let partial: PartialSwapData = deserialize_async(&bytes).await?;
  930. let drk = new_wallet(
  931. blockchain_config.cache_path,
  932. blockchain_config.wallet_path,
  933. blockchain_config.wallet_pass,
  934. Some(blockchain_config.endpoint),
  935. &ex,
  936. args.fun,
  937. )
  938. .await;
  939. let tx = match drk.join_swap(partial, None, None, None).await {
  940. Ok(tx) => tx,
  941. Err(e) => {
  942. eprintln!("Failed to create a join swap transaction: {e:?}");
  943. exit(2);
  944. }
  945. };
  946. println!("{}", base64::encode(&serialize_async(&tx).await));
  947. drk.stop_rpc_client().await
  948. }
  949. OtcSubcmd::Inspect => {
  950. let mut buf = String::new();
  951. stdin().read_to_string(&mut buf)?;
  952. let Some(bytes) = base64::decode(buf.trim()) else {
  953. eprintln!("Failed to decode swap transaction");
  954. exit(2);
  955. };
  956. let drk = new_wallet(
  957. blockchain_config.cache_path,
  958. blockchain_config.wallet_path,
  959. blockchain_config.wallet_pass,
  960. None,
  961. &ex,
  962. args.fun,
  963. )
  964. .await;
  965. let mut output = vec![];
  966. if let Err(e) = drk.inspect_swap(bytes, &mut output).await {
  967. print_output(&output);
  968. eprintln!("Failed to inspect swap: {e:?}");
  969. exit(2);
  970. };
  971. print_output(&output);
  972. Ok(())
  973. }
  974. OtcSubcmd::Sign => {
  975. let mut tx = parse_tx_from_stdin().await?;
  976. let drk = new_wallet(
  977. blockchain_config.cache_path,
  978. blockchain_config.wallet_path,
  979. blockchain_config.wallet_pass,
  980. None,
  981. &ex,
  982. args.fun,
  983. )
  984. .await;
  985. if let Err(e) = drk.sign_swap(&mut tx).await {
  986. eprintln!("Failed to sign joined swap transaction: {e:?}");
  987. exit(2);
  988. };
  989. println!("{}", base64::encode(&serialize_async(&tx).await));
  990. Ok(())
  991. }
  992. },
  993. Subcmd::Dao { command } => match command {
  994. DaoSubcmd::Create {
  995. proposer_limit,
  996. quorum,
  997. early_exec_quorum,
  998. approval_ratio,
  999. gov_token_id,
  1000. } => {
  1001. if let Err(e) = f64::from_str(&proposer_limit) {
  1002. eprintln!("Invalid proposer limit: {e:?}");
  1003. exit(2);
  1004. }
  1005. if let Err(e) = f64::from_str(&quorum) {
  1006. eprintln!("Invalid quorum: {e:?}");
  1007. exit(2);
  1008. }
  1009. if let Err(e) = f64::from_str(&early_exec_quorum) {
  1010. eprintln!("Invalid early exec quorum: {e:?}");
  1011. exit(2);
  1012. }
  1013. let proposer_limit = decode_base10(&proposer_limit, BALANCE_BASE10_DECIMALS, true)?;
  1014. let quorum = decode_base10(&quorum, BALANCE_BASE10_DECIMALS, true)?;
  1015. let early_exec_quorum =
  1016. decode_base10(&early_exec_quorum, BALANCE_BASE10_DECIMALS, true)?;
  1017. if approval_ratio > 1.0 {
  1018. eprintln!("Error: Approval ratio cannot be >1.0");
  1019. exit(2);
  1020. }
  1021. let approval_ratio_base = 100_u64;
  1022. let approval_ratio_quot = (approval_ratio * approval_ratio_base as f64) as u64;
  1023. let drk = new_wallet(
  1024. blockchain_config.cache_path,
  1025. blockchain_config.wallet_path,
  1026. blockchain_config.wallet_pass,
  1027. None,
  1028. &ex,
  1029. args.fun,
  1030. )
  1031. .await;
  1032. let gov_token_id = match drk.get_token(gov_token_id).await {
  1033. Ok(g) => g,
  1034. Err(e) => {
  1035. eprintln!("Invalid Token ID: {e:?}");
  1036. exit(2);
  1037. }
  1038. };
  1039. let notes_keypair = Keypair::random(&mut OsRng);
  1040. let proposer_keypair = Keypair::random(&mut OsRng);
  1041. let proposals_keypair = Keypair::random(&mut OsRng);
  1042. let votes_keypair = Keypair::random(&mut OsRng);
  1043. let exec_keypair = Keypair::random(&mut OsRng);
  1044. let early_exec_keypair = Keypair::random(&mut OsRng);
  1045. let bulla_blind = BaseBlind::random(&mut OsRng);
  1046. let params = DaoParams::new(
  1047. proposer_limit,
  1048. quorum,
  1049. early_exec_quorum,
  1050. approval_ratio_base,
  1051. approval_ratio_quot,
  1052. gov_token_id,
  1053. Some(notes_keypair.secret),
  1054. notes_keypair.public,
  1055. Some(proposer_keypair.secret),
  1056. proposer_keypair.public,
  1057. Some(proposals_keypair.secret),
  1058. proposals_keypair.public,
  1059. Some(votes_keypair.secret),
  1060. votes_keypair.public,
  1061. Some(exec_keypair.secret),
  1062. exec_keypair.public,
  1063. Some(early_exec_keypair.secret),
  1064. early_exec_keypair.public,
  1065. bulla_blind,
  1066. );
  1067. println!("{}", params.toml_str());
  1068. Ok(())
  1069. }
  1070. DaoSubcmd::View => {
  1071. let mut buf = String::new();
  1072. stdin().read_to_string(&mut buf)?;
  1073. let params = DaoParams::from_toml_str(&buf)?;
  1074. println!("{params}");
  1075. Ok(())
  1076. }
  1077. DaoSubcmd::Import { name } => {
  1078. let mut buf = String::new();
  1079. stdin().read_to_string(&mut buf)?;
  1080. let params = DaoParams::from_toml_str(&buf)?;
  1081. let drk = new_wallet(
  1082. blockchain_config.cache_path,
  1083. blockchain_config.wallet_path,
  1084. blockchain_config.wallet_pass,
  1085. None,
  1086. &ex,
  1087. args.fun,
  1088. )
  1089. .await;
  1090. let mut output = vec![];
  1091. if let Err(e) = drk.import_dao(&name, &params, &mut output).await {
  1092. print_output(&output);
  1093. eprintln!("Failed to import DAO: {e:?}");
  1094. exit(2);
  1095. }
  1096. print_output(&output);
  1097. Ok(())
  1098. }
  1099. DaoSubcmd::UpdateKeys => {
  1100. let mut buf = String::new();
  1101. stdin().read_to_string(&mut buf)?;
  1102. let params = DaoParams::from_toml_str(&buf)?;
  1103. let drk = new_wallet(
  1104. blockchain_config.cache_path,
  1105. blockchain_config.wallet_path,
  1106. blockchain_config.wallet_pass,
  1107. None,
  1108. &ex,
  1109. args.fun,
  1110. )
  1111. .await;
  1112. let mut output = vec![];
  1113. if let Err(e) = drk.update_dao_keys(&params, &mut output).await {
  1114. print_output(&output);
  1115. eprintln!("Failed to update DAO keys: {e:?}");
  1116. exit(2);
  1117. }
  1118. print_output(&output);
  1119. Ok(())
  1120. }
  1121. DaoSubcmd::List { name } => {
  1122. let drk = new_wallet(
  1123. blockchain_config.cache_path,
  1124. blockchain_config.wallet_path,
  1125. blockchain_config.wallet_pass,
  1126. None,
  1127. &ex,
  1128. args.fun,
  1129. )
  1130. .await;
  1131. let mut output = vec![];
  1132. if let Err(e) = drk.dao_list(&name, &mut output).await {
  1133. print_output(&output);
  1134. eprintln!("Failed to list DAO: {e:?}");
  1135. exit(2);
  1136. }
  1137. print_output(&output);
  1138. Ok(())
  1139. }
  1140. DaoSubcmd::Balance { name } => {
  1141. let drk = new_wallet(
  1142. blockchain_config.cache_path,
  1143. blockchain_config.wallet_path,
  1144. blockchain_config.wallet_pass,
  1145. None,
  1146. &ex,
  1147. args.fun,
  1148. )
  1149. .await;
  1150. let balmap = match drk.dao_balance(&name).await {
  1151. Ok(b) => b,
  1152. Err(e) => {
  1153. eprintln!("Failed to fetch DAO balance: {e:?}");
  1154. exit(2);
  1155. }
  1156. };
  1157. let aliases_map = match drk.get_aliases_mapped_by_token().await {
  1158. Ok(a) => a,
  1159. Err(e) => {
  1160. eprintln!("Failed to fetch wallet aliases: {e:?}");
  1161. exit(2);
  1162. }
  1163. };
  1164. // Create a prettytable with the new data:
  1165. let mut table = Table::new();
  1166. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  1167. table.set_titles(row!["Token ID", "Aliases", "Balance"]);
  1168. for (token_id, balance) in balmap.iter() {
  1169. let aliases = match aliases_map.get(token_id) {
  1170. Some(a) => a,
  1171. None => "-",
  1172. };
  1173. table.add_row(row![
  1174. token_id,
  1175. aliases,
  1176. encode_base10(*balance, BALANCE_BASE10_DECIMALS)
  1177. ]);
  1178. }
  1179. if table.is_empty() {
  1180. println!("No unspent balances found");
  1181. } else {
  1182. println!("{table}");
  1183. }
  1184. Ok(())
  1185. }
  1186. DaoSubcmd::Mint { name } => {
  1187. let drk = new_wallet(
  1188. blockchain_config.cache_path,
  1189. blockchain_config.wallet_path,
  1190. blockchain_config.wallet_pass,
  1191. Some(blockchain_config.endpoint),
  1192. &ex,
  1193. args.fun,
  1194. )
  1195. .await;
  1196. let tx = match drk.dao_mint(&name).await {
  1197. Ok(tx) => tx,
  1198. Err(e) => {
  1199. eprintln!("Failed to mint DAO: {e:?}");
  1200. exit(2);
  1201. }
  1202. };
  1203. println!("{}", base64::encode(&serialize_async(&tx).await));
  1204. drk.stop_rpc_client().await
  1205. }
  1206. DaoSubcmd::ProposeTransfer {
  1207. name,
  1208. duration,
  1209. amount,
  1210. token,
  1211. recipient,
  1212. spend_hook,
  1213. user_data,
  1214. } => {
  1215. let drk = new_wallet(
  1216. blockchain_config.cache_path,
  1217. blockchain_config.wallet_path,
  1218. blockchain_config.wallet_pass,
  1219. Some(blockchain_config.endpoint),
  1220. &ex,
  1221. args.fun,
  1222. )
  1223. .await;
  1224. if let Err(e) = f64::from_str(&amount) {
  1225. eprintln!("Invalid amount: {e:?}");
  1226. exit(2);
  1227. }
  1228. let rcpt = match PublicKey::from_str(&recipient) {
  1229. Ok(r) => r,
  1230. Err(e) => {
  1231. eprintln!("Invalid recipient: {e:?}");
  1232. exit(2);
  1233. }
  1234. };
  1235. let token_id = match drk.get_token(token).await {
  1236. Ok(t) => t,
  1237. Err(e) => {
  1238. eprintln!("Invalid token alias: {e:?}");
  1239. exit(2);
  1240. }
  1241. };
  1242. let spend_hook = match spend_hook {
  1243. Some(s) => match FuncId::from_str(&s) {
  1244. Ok(s) => Some(s),
  1245. Err(e) => {
  1246. eprintln!("Invalid spend hook: {e:?}");
  1247. exit(2);
  1248. }
  1249. },
  1250. None => None,
  1251. };
  1252. let user_data = match user_data {
  1253. Some(u) => {
  1254. let bytes: [u8; 32] = match bs58::decode(&u).into_vec()?.try_into() {
  1255. Ok(b) => b,
  1256. Err(e) => {
  1257. eprintln!("Invalid user data: {e:?}");
  1258. exit(2);
  1259. }
  1260. };
  1261. match pallas::Base::from_repr(bytes).into() {
  1262. Some(v) => Some(v),
  1263. None => {
  1264. eprintln!("Invalid user data");
  1265. exit(2);
  1266. }
  1267. }
  1268. }
  1269. None => None,
  1270. };
  1271. let proposal = match drk
  1272. .dao_propose_transfer(
  1273. &name, duration, &amount, token_id, rcpt, spend_hook, user_data,
  1274. )
  1275. .await
  1276. {
  1277. Ok(p) => p,
  1278. Err(e) => {
  1279. eprintln!("Failed to create DAO transfer proposal: {e:?}");
  1280. exit(2);
  1281. }
  1282. };
  1283. println!("Generated proposal: {}", proposal.bulla());
  1284. drk.stop_rpc_client().await
  1285. }
  1286. DaoSubcmd::ProposeGeneric { name, duration, user_data } => {
  1287. let drk = new_wallet(
  1288. blockchain_config.cache_path,
  1289. blockchain_config.wallet_path,
  1290. blockchain_config.wallet_pass,
  1291. Some(blockchain_config.endpoint),
  1292. &ex,
  1293. args.fun,
  1294. )
  1295. .await;
  1296. let user_data = match user_data {
  1297. Some(u) => {
  1298. let bytes: [u8; 32] = match bs58::decode(&u).into_vec()?.try_into() {
  1299. Ok(b) => b,
  1300. Err(e) => {
  1301. eprintln!("Invalid user data: {e:?}");
  1302. exit(2);
  1303. }
  1304. };
  1305. match pallas::Base::from_repr(bytes).into() {
  1306. Some(v) => Some(v),
  1307. None => {
  1308. eprintln!("Invalid user data");
  1309. exit(2);
  1310. }
  1311. }
  1312. }
  1313. None => None,
  1314. };
  1315. let proposal = match drk.dao_propose_generic(&name, duration, user_data).await {
  1316. Ok(p) => p,
  1317. Err(e) => {
  1318. eprintln!("Failed to create DAO generic proposal: {e:?}");
  1319. exit(2);
  1320. }
  1321. };
  1322. println!("Generated proposal: {}", proposal.bulla());
  1323. drk.stop_rpc_client().await
  1324. }
  1325. DaoSubcmd::Proposals { name } => {
  1326. let drk = new_wallet(
  1327. blockchain_config.cache_path,
  1328. blockchain_config.wallet_path,
  1329. blockchain_config.wallet_pass,
  1330. None,
  1331. &ex,
  1332. args.fun,
  1333. )
  1334. .await;
  1335. let proposals = drk.get_dao_proposals(&name).await?;
  1336. for (i, proposal) in proposals.iter().enumerate() {
  1337. println!("{i}. {}", proposal.bulla());
  1338. }
  1339. Ok(())
  1340. }
  1341. DaoSubcmd::Proposal { bulla, export, mint_proposal } => {
  1342. let bulla = match DaoProposalBulla::from_str(&bulla) {
  1343. Ok(b) => b,
  1344. Err(e) => {
  1345. eprintln!("Invalid proposal bulla: {e:?}");
  1346. exit(2);
  1347. }
  1348. };
  1349. let drk = new_wallet(
  1350. blockchain_config.cache_path,
  1351. blockchain_config.wallet_path,
  1352. blockchain_config.wallet_pass,
  1353. Some(blockchain_config.endpoint),
  1354. &ex,
  1355. args.fun,
  1356. )
  1357. .await;
  1358. let proposal = drk.get_dao_proposal_by_bulla(&bulla).await?;
  1359. if export {
  1360. // Retrieve the DAO
  1361. let dao = drk.get_dao_by_bulla(&proposal.proposal.dao_bulla).await?;
  1362. // Encypt the proposal
  1363. let enc_note = AeadEncryptedNote::encrypt(
  1364. &proposal,
  1365. &dao.params.dao.proposals_public_key,
  1366. &mut OsRng,
  1367. )
  1368. .unwrap();
  1369. // Export it to base64
  1370. println!("{}", base64::encode(&serialize_async(&enc_note).await));
  1371. return drk.stop_rpc_client().await
  1372. }
  1373. if mint_proposal {
  1374. // Identify proposal type by its auth calls
  1375. for call in &proposal.proposal.auth_calls {
  1376. // We only support transfer right now
  1377. if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
  1378. let tx = match drk.dao_transfer_proposal_tx(&proposal).await {
  1379. Ok(tx) => tx,
  1380. Err(e) => {
  1381. eprintln!("Failed to create DAO transfer proposal: {e:?}");
  1382. exit(2);
  1383. }
  1384. };
  1385. println!("{}", base64::encode(&serialize_async(&tx).await));
  1386. return drk.stop_rpc_client().await
  1387. }
  1388. }
  1389. // If proposal has no auth calls, we consider it a generic one
  1390. if proposal.proposal.auth_calls.is_empty() {
  1391. let tx = match drk.dao_generic_proposal_tx(&proposal).await {
  1392. Ok(tx) => tx,
  1393. Err(e) => {
  1394. eprintln!("Failed to create DAO generic proposal: {e:?}");
  1395. exit(2);
  1396. }
  1397. };
  1398. println!("{}", base64::encode(&serialize_async(&tx).await));
  1399. return drk.stop_rpc_client().await
  1400. }
  1401. eprintln!("Unsuported DAO proposal");
  1402. exit(2);
  1403. }
  1404. println!("{proposal}");
  1405. let mut contract_calls = "\nInvoked contracts:\n".to_string();
  1406. for call in proposal.proposal.auth_calls {
  1407. contract_calls.push_str(&format!(
  1408. "\tContract: {}\n\tFunction: {}\n\tData: ",
  1409. call.contract_id, call.function_code
  1410. ));
  1411. if call.auth_data.is_empty() {
  1412. contract_calls.push_str("-\n");
  1413. continue;
  1414. }
  1415. if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
  1416. // We know that the plaintext data live in the data plaintext vec
  1417. if proposal.data.is_none() {
  1418. contract_calls.push_str("-\n");
  1419. continue;
  1420. }
  1421. let coin: CoinAttributes =
  1422. deserialize_async(proposal.data.as_ref().unwrap()).await?;
  1423. let spend_hook = if coin.spend_hook == FuncId::none() {
  1424. "-".to_string()
  1425. } else {
  1426. format!("{}", coin.spend_hook)
  1427. };
  1428. let user_data = if coin.user_data == pallas::Base::ZERO {
  1429. "-".to_string()
  1430. } else {
  1431. format!("{:?}", coin.user_data)
  1432. };
  1433. contract_calls.push_str(&format!("\n\t\t{}: {}\n\t\t{}: {} ({})\n\t\t{}: {}\n\t\t{}: {}\n\t\t{}: {}\n\t\t{}: {}\n\n",
  1434. "Recipient",
  1435. coin.public_key,
  1436. "Amount",
  1437. coin.value,
  1438. encode_base10(coin.value, BALANCE_BASE10_DECIMALS),
  1439. "Token",
  1440. coin.token_id,
  1441. "Spend hook",
  1442. spend_hook,
  1443. "User data",
  1444. user_data,
  1445. "Blind",
  1446. coin.blind));
  1447. }
  1448. }
  1449. println!("{contract_calls}");
  1450. let votes = drk.get_dao_proposal_votes(&bulla).await?;
  1451. let mut total_yes_vote_value = 0;
  1452. let mut total_no_vote_value = 0;
  1453. let mut total_all_vote_value = 0;
  1454. let mut table = Table::new();
  1455. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  1456. table.set_titles(row!["Transaction", "Tokens", "Vote"]);
  1457. for vote in votes {
  1458. let vote_option = if vote.vote_option {
  1459. total_yes_vote_value += vote.all_vote_value;
  1460. "Yes"
  1461. } else {
  1462. total_no_vote_value += vote.all_vote_value;
  1463. "No"
  1464. };
  1465. total_all_vote_value += vote.all_vote_value;
  1466. table.add_row(row![
  1467. vote.tx_hash,
  1468. encode_base10(vote.all_vote_value, BALANCE_BASE10_DECIMALS),
  1469. vote_option
  1470. ]);
  1471. }
  1472. let outcome = if table.is_empty() {
  1473. println!("Votes: No votes found");
  1474. "Unknown"
  1475. } else {
  1476. println!("Votes:");
  1477. println!("{table}");
  1478. println!(
  1479. "Total tokens votes: {}",
  1480. encode_base10(total_all_vote_value, BALANCE_BASE10_DECIMALS)
  1481. );
  1482. let approval_ratio =
  1483. (total_yes_vote_value as f64 * 100.0) / total_all_vote_value as f64;
  1484. println!(
  1485. "Total tokens Yes votes: {} ({approval_ratio:.2}%)",
  1486. encode_base10(total_yes_vote_value, BALANCE_BASE10_DECIMALS)
  1487. );
  1488. println!(
  1489. "Total tokens No votes: {} ({:.2}%)",
  1490. encode_base10(total_no_vote_value, BALANCE_BASE10_DECIMALS),
  1491. (total_no_vote_value as f64 * 100.0) / total_all_vote_value as f64
  1492. );
  1493. let dao = drk.get_dao_by_bulla(&proposal.proposal.dao_bulla).await?;
  1494. if total_all_vote_value >= dao.params.dao.quorum &&
  1495. approval_ratio >=
  1496. (dao.params.dao.approval_ratio_quot /
  1497. dao.params.dao.approval_ratio_base)
  1498. as f64
  1499. {
  1500. "Approved"
  1501. } else {
  1502. "Rejected"
  1503. }
  1504. };
  1505. if let Some(exec_tx_hash) = proposal.exec_tx_hash {
  1506. println!("Proposal was executed on transaction: {exec_tx_hash}");
  1507. return drk.stop_rpc_client().await
  1508. }
  1509. // Retrieve next block height and current block time target,
  1510. // to compute their window.
  1511. let next_block_height = drk.get_next_block_height().await?;
  1512. let block_target = drk.get_block_target().await?;
  1513. let current_window = blockwindow(next_block_height, block_target);
  1514. let end_time = proposal.proposal.creation_blockwindow +
  1515. proposal.proposal.duration_blockwindows;
  1516. let (voting_status, proposal_status_message) = if current_window < end_time {
  1517. ("Ongoing", format!("Current proposal outcome: {outcome}"))
  1518. } else {
  1519. ("Concluded", format!("Proposal outcome: {outcome}"))
  1520. };
  1521. println!("Voting status: {voting_status}");
  1522. println!("{proposal_status_message}");
  1523. drk.stop_rpc_client().await
  1524. }
  1525. DaoSubcmd::ProposalImport => {
  1526. let mut buf = String::new();
  1527. stdin().read_to_string(&mut buf)?;
  1528. let Some(bytes) = base64::decode(buf.trim()) else {
  1529. eprintln!("Failed to decode encrypted proposal data");
  1530. exit(2);
  1531. };
  1532. let encrypted_proposal: AeadEncryptedNote = deserialize_async(&bytes).await?;
  1533. let drk = new_wallet(
  1534. blockchain_config.cache_path,
  1535. blockchain_config.wallet_path,
  1536. blockchain_config.wallet_pass,
  1537. None,
  1538. &ex,
  1539. args.fun,
  1540. )
  1541. .await;
  1542. // Retrieve all DAOs to try to decrypt the proposal
  1543. let daos = drk.get_daos().await?;
  1544. for dao in &daos {
  1545. // Check if we have the proposals key
  1546. let Some(proposals_secret_key) = dao.params.proposals_secret_key else {
  1547. continue
  1548. };
  1549. // Try to decrypt the proposal
  1550. let Ok(proposal) =
  1551. encrypted_proposal.decrypt::<ProposalRecord>(&proposals_secret_key)
  1552. else {
  1553. continue
  1554. };
  1555. let proposal = match drk.get_dao_proposal_by_bulla(&proposal.bulla()).await {
  1556. Ok(p) => {
  1557. let mut our_proposal = p;
  1558. our_proposal.data = proposal.data;
  1559. our_proposal
  1560. }
  1561. Err(_) => proposal,
  1562. };
  1563. return drk.put_dao_proposal(&proposal).await
  1564. }
  1565. eprintln!("Couldn't decrypt the proposal with out DAO keys");
  1566. exit(2);
  1567. }
  1568. DaoSubcmd::Vote { bulla, vote, vote_weight } => {
  1569. let bulla = match DaoProposalBulla::from_str(&bulla) {
  1570. Ok(b) => b,
  1571. Err(e) => {
  1572. eprintln!("Invalid proposal bulla: {e:?}");
  1573. exit(2);
  1574. }
  1575. };
  1576. if vote > 1 {
  1577. eprintln!("Vote can be either 0 (NO) or 1 (YES)");
  1578. exit(2);
  1579. }
  1580. let vote = vote != 0;
  1581. let weight = match vote_weight {
  1582. Some(w) => {
  1583. if let Err(e) = f64::from_str(&w) {
  1584. eprintln!("Invalid vote weight: {e:?}");
  1585. exit(2);
  1586. }
  1587. Some(decode_base10(&w, BALANCE_BASE10_DECIMALS, true)?)
  1588. }
  1589. None => None,
  1590. };
  1591. let drk = new_wallet(
  1592. blockchain_config.cache_path,
  1593. blockchain_config.wallet_path,
  1594. blockchain_config.wallet_pass,
  1595. Some(blockchain_config.endpoint),
  1596. &ex,
  1597. args.fun,
  1598. )
  1599. .await;
  1600. let tx = match drk.dao_vote(&bulla, vote, weight).await {
  1601. Ok(tx) => tx,
  1602. Err(e) => {
  1603. eprintln!("Failed to create DAO Vote transaction: {e:?}");
  1604. exit(2);
  1605. }
  1606. };
  1607. println!("{}", base64::encode(&serialize_async(&tx).await));
  1608. drk.stop_rpc_client().await
  1609. }
  1610. DaoSubcmd::Exec { bulla, early } => {
  1611. let bulla = match DaoProposalBulla::from_str(&bulla) {
  1612. Ok(b) => b,
  1613. Err(e) => {
  1614. eprintln!("Invalid proposal bulla: {e:?}");
  1615. exit(2);
  1616. }
  1617. };
  1618. let drk = new_wallet(
  1619. blockchain_config.cache_path,
  1620. blockchain_config.wallet_path,
  1621. blockchain_config.wallet_pass,
  1622. Some(blockchain_config.endpoint),
  1623. &ex,
  1624. args.fun,
  1625. )
  1626. .await;
  1627. let proposal = drk.get_dao_proposal_by_bulla(&bulla).await?;
  1628. // Identify proposal type by its auth calls
  1629. for call in &proposal.proposal.auth_calls {
  1630. // We only support transfer right now
  1631. if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
  1632. let tx = match drk.dao_exec_transfer(&proposal, early).await {
  1633. Ok(tx) => tx,
  1634. Err(e) => {
  1635. eprintln!("Failed to execute DAO transfer proposal: {e:?}");
  1636. exit(2);
  1637. }
  1638. };
  1639. println!("{}", base64::encode(&serialize_async(&tx).await));
  1640. return drk.stop_rpc_client().await
  1641. }
  1642. }
  1643. // If proposal has no auth calls, we consider it a generic one
  1644. if proposal.proposal.auth_calls.is_empty() {
  1645. let tx = match drk.dao_exec_generic(&proposal, early).await {
  1646. Ok(tx) => tx,
  1647. Err(e) => {
  1648. eprintln!("Failed to execute DAO generic proposal: {e:?}");
  1649. exit(2);
  1650. }
  1651. };
  1652. println!("{}", base64::encode(&serialize_async(&tx).await));
  1653. return drk.stop_rpc_client().await
  1654. }
  1655. eprintln!("Unsuported DAO proposal");
  1656. exit(2);
  1657. }
  1658. DaoSubcmd::SpendHook => {
  1659. let spend_hook =
  1660. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  1661. .to_func_id();
  1662. println!("{spend_hook}");
  1663. Ok(())
  1664. }
  1665. },
  1666. Subcmd::AttachFee => {
  1667. let mut tx = parse_tx_from_stdin().await?;
  1668. let drk = new_wallet(
  1669. blockchain_config.cache_path,
  1670. blockchain_config.wallet_path,
  1671. blockchain_config.wallet_pass,
  1672. Some(blockchain_config.endpoint),
  1673. &ex,
  1674. args.fun,
  1675. )
  1676. .await;
  1677. if let Err(e) = drk.attach_fee(&mut tx).await {
  1678. eprintln!("Failed to attach the fee call to the transaction: {e:?}");
  1679. exit(2);
  1680. };
  1681. println!("{}", base64::encode(&serialize_async(&tx).await));
  1682. drk.stop_rpc_client().await
  1683. }
  1684. Subcmd::Inspect => {
  1685. let tx = parse_tx_from_stdin().await?;
  1686. println!("{tx:#?}");
  1687. Ok(())
  1688. }
  1689. Subcmd::Broadcast => {
  1690. let tx = parse_tx_from_stdin().await?;
  1691. let drk = new_wallet(
  1692. blockchain_config.cache_path,
  1693. blockchain_config.wallet_path,
  1694. blockchain_config.wallet_pass,
  1695. Some(blockchain_config.endpoint),
  1696. &ex,
  1697. args.fun,
  1698. )
  1699. .await;
  1700. if let Err(e) = drk.simulate_tx(&tx).await {
  1701. eprintln!("Failed to simulate tx: {e:?}");
  1702. exit(2);
  1703. };
  1704. let mut output = vec![];
  1705. if let Err(e) = drk.mark_tx_spend(&tx, &mut output).await {
  1706. print_output(&output);
  1707. eprintln!("Failed to mark transaction coins as spent: {e:?}");
  1708. exit(2);
  1709. };
  1710. let txid = match drk.broadcast_tx(&tx, &mut output).await {
  1711. Ok(t) => t,
  1712. Err(e) => {
  1713. print_output(&output);
  1714. eprintln!("Failed to broadcast transaction: {e:?}");
  1715. exit(2);
  1716. }
  1717. };
  1718. print_output(&output);
  1719. println!("Transaction ID: {txid}");
  1720. drk.stop_rpc_client().await
  1721. }
  1722. Subcmd::Scan { reset } => {
  1723. let drk = new_wallet(
  1724. blockchain_config.cache_path,
  1725. blockchain_config.wallet_path,
  1726. blockchain_config.wallet_pass,
  1727. Some(blockchain_config.endpoint),
  1728. &ex,
  1729. args.fun,
  1730. )
  1731. .await;
  1732. if let Some(height) = reset {
  1733. let mut buf = vec![];
  1734. if let Err(e) = drk.reset_to_height(height, &mut buf) {
  1735. print_output(&buf);
  1736. eprintln!("Failed during wallet reset: {e:?}");
  1737. exit(2);
  1738. }
  1739. print_output(&buf);
  1740. }
  1741. if let Err(e) = drk.scan_blocks(&mut vec![], None, &true).await {
  1742. eprintln!("Failed during scanning: {e:?}");
  1743. exit(2);
  1744. }
  1745. println!("Finished scanning blockchain");
  1746. drk.stop_rpc_client().await
  1747. }
  1748. Subcmd::Explorer { command } => match command {
  1749. ExplorerSubcmd::FetchTx { tx_hash, full, encode } => {
  1750. let tx_hash = TransactionHash(*blake3::Hash::from_hex(&tx_hash)?.as_bytes());
  1751. let drk = new_wallet(
  1752. blockchain_config.cache_path,
  1753. blockchain_config.wallet_path,
  1754. blockchain_config.wallet_pass,
  1755. Some(blockchain_config.endpoint),
  1756. &ex,
  1757. args.fun,
  1758. )
  1759. .await;
  1760. let tx = match drk.get_tx(&tx_hash).await {
  1761. Ok(tx) => tx,
  1762. Err(e) => {
  1763. eprintln!("Failed to fetch transaction: {e:?}");
  1764. exit(2);
  1765. }
  1766. };
  1767. let Some(tx) = tx else {
  1768. println!("Transaction was not found");
  1769. exit(1);
  1770. };
  1771. // Make sure the tx is correct
  1772. assert_eq!(tx.hash(), tx_hash);
  1773. if encode {
  1774. println!("{}", base64::encode(&serialize_async(&tx).await));
  1775. exit(1)
  1776. }
  1777. println!("Transaction ID: {tx_hash}");
  1778. if full {
  1779. println!("{tx:?}");
  1780. }
  1781. drk.stop_rpc_client().await
  1782. }
  1783. ExplorerSubcmd::SimulateTx => {
  1784. let tx = parse_tx_from_stdin().await?;
  1785. let drk = new_wallet(
  1786. blockchain_config.cache_path,
  1787. blockchain_config.wallet_path,
  1788. blockchain_config.wallet_pass,
  1789. Some(blockchain_config.endpoint),
  1790. &ex,
  1791. args.fun,
  1792. )
  1793. .await;
  1794. let is_valid = match drk.simulate_tx(&tx).await {
  1795. Ok(b) => b,
  1796. Err(e) => {
  1797. eprintln!("Failed to simulate tx: {e:?}");
  1798. exit(2);
  1799. }
  1800. };
  1801. println!("Transaction ID: {}", tx.hash());
  1802. println!("State: {}", if is_valid { "valid" } else { "invalid" });
  1803. drk.stop_rpc_client().await
  1804. }
  1805. ExplorerSubcmd::TxsHistory { tx_hash, encode } => {
  1806. let drk = new_wallet(
  1807. blockchain_config.cache_path,
  1808. blockchain_config.wallet_path,
  1809. blockchain_config.wallet_pass,
  1810. None,
  1811. &ex,
  1812. args.fun,
  1813. )
  1814. .await;
  1815. if let Some(c) = tx_hash {
  1816. let (tx_hash, status, block_height, tx) = drk.get_tx_history_record(&c).await?;
  1817. if encode {
  1818. println!("{}", base64::encode(&serialize_async(&tx).await));
  1819. exit(1)
  1820. }
  1821. println!("Transaction ID: {tx_hash}");
  1822. println!("Status: {status}");
  1823. match block_height {
  1824. Some(block_height) => println!("Block height: {block_height}"),
  1825. None => println!("Block height: -"),
  1826. }
  1827. println!("{tx:?}");
  1828. return Ok(())
  1829. }
  1830. let map = match drk.get_txs_history() {
  1831. Ok(m) => m,
  1832. Err(e) => {
  1833. eprintln!("Failed to retrieve transactions history records: {e:?}");
  1834. exit(2);
  1835. }
  1836. };
  1837. // Create a prettytable with the new data:
  1838. let mut table = Table::new();
  1839. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  1840. table.set_titles(row!["Transaction Hash", "Status", "Block Height"]);
  1841. for (txs_hash, status, block_height) in map.iter() {
  1842. let block_height = match block_height {
  1843. Some(block_height) => block_height.to_string(),
  1844. None => String::from("-"),
  1845. };
  1846. table.add_row(row![txs_hash, status, block_height]);
  1847. }
  1848. if table.is_empty() {
  1849. println!("No transactions found");
  1850. } else {
  1851. println!("{table}");
  1852. }
  1853. Ok(())
  1854. }
  1855. ExplorerSubcmd::ClearReverted => {
  1856. let drk = new_wallet(
  1857. blockchain_config.cache_path,
  1858. blockchain_config.wallet_path,
  1859. blockchain_config.wallet_pass,
  1860. None,
  1861. &ex,
  1862. args.fun,
  1863. )
  1864. .await;
  1865. if let Err(e) = drk.remove_reverted_txs() {
  1866. eprintln!("Failed to remove reverted transactions: {e:?}");
  1867. exit(2);
  1868. };
  1869. Ok(())
  1870. }
  1871. ExplorerSubcmd::ScannedBlocks { height } => {
  1872. let drk = new_wallet(
  1873. blockchain_config.cache_path,
  1874. blockchain_config.wallet_path,
  1875. blockchain_config.wallet_pass,
  1876. None,
  1877. &ex,
  1878. args.fun,
  1879. )
  1880. .await;
  1881. if let Some(height) = height {
  1882. let hash = match drk.get_scanned_block_hash(&height) {
  1883. Ok(h) => h,
  1884. Err(e) => {
  1885. eprintln!("Failed to retrieve scanned block record: {e:?}");
  1886. exit(2);
  1887. }
  1888. };
  1889. println!("Height: {height}");
  1890. println!("Hash: {hash}");
  1891. return Ok(())
  1892. }
  1893. let map = match drk.get_scanned_block_records() {
  1894. Ok(m) => m,
  1895. Err(e) => {
  1896. eprintln!("Failed to retrieve scanned blocks records: {e:?}");
  1897. exit(2);
  1898. }
  1899. };
  1900. // Create a prettytable with the new data:
  1901. let mut table = Table::new();
  1902. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  1903. table.set_titles(row!["Height", "Hash"]);
  1904. for (height, hash) in map.iter() {
  1905. table.add_row(row![height, hash]);
  1906. }
  1907. if table.is_empty() {
  1908. println!("No scanned blocks records found");
  1909. } else {
  1910. println!("{table}");
  1911. }
  1912. Ok(())
  1913. }
  1914. },
  1915. Subcmd::Alias { command } => match command {
  1916. AliasSubcmd::Add { alias, token } => {
  1917. if alias.chars().count() > 5 {
  1918. eprintln!("Error: Alias exceeds 5 characters");
  1919. exit(2);
  1920. }
  1921. let token_id = match TokenId::from_str(token.as_str()) {
  1922. Ok(t) => t,
  1923. Err(e) => {
  1924. eprintln!("Invalid Token ID: {e:?}");
  1925. exit(2);
  1926. }
  1927. };
  1928. let drk = new_wallet(
  1929. blockchain_config.cache_path,
  1930. blockchain_config.wallet_path,
  1931. blockchain_config.wallet_pass,
  1932. None,
  1933. &ex,
  1934. args.fun,
  1935. )
  1936. .await;
  1937. if let Err(e) = drk.add_alias(alias, token_id).await {
  1938. eprintln!("Failed to add alias: {e:?}");
  1939. exit(2);
  1940. }
  1941. Ok(())
  1942. }
  1943. AliasSubcmd::Show { alias, token } => {
  1944. let token_id = match token {
  1945. Some(t) => match TokenId::from_str(t.as_str()) {
  1946. Ok(t) => Some(t),
  1947. Err(e) => {
  1948. eprintln!("Invalid Token ID: {e:?}");
  1949. exit(2);
  1950. }
  1951. },
  1952. None => None,
  1953. };
  1954. let drk = new_wallet(
  1955. blockchain_config.cache_path,
  1956. blockchain_config.wallet_path,
  1957. blockchain_config.wallet_pass,
  1958. None,
  1959. &ex,
  1960. args.fun,
  1961. )
  1962. .await;
  1963. let map = drk.get_aliases(alias, token_id).await?;
  1964. // Create a prettytable with the new data:
  1965. let mut table = Table::new();
  1966. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  1967. table.set_titles(row!["Alias", "Token ID"]);
  1968. for (alias, token_id) in map.iter() {
  1969. table.add_row(row![alias, token_id]);
  1970. }
  1971. if table.is_empty() {
  1972. println!("No aliases found");
  1973. } else {
  1974. println!("{table}");
  1975. }
  1976. Ok(())
  1977. }
  1978. AliasSubcmd::Remove { alias } => {
  1979. let drk = new_wallet(
  1980. blockchain_config.cache_path,
  1981. blockchain_config.wallet_path,
  1982. blockchain_config.wallet_pass,
  1983. None,
  1984. &ex,
  1985. args.fun,
  1986. )
  1987. .await;
  1988. if let Err(e) = drk.remove_alias(alias).await {
  1989. eprintln!("Failed to remove alias: {e:?}");
  1990. exit(2);
  1991. }
  1992. Ok(())
  1993. }
  1994. },
  1995. Subcmd::Token { command } => match command {
  1996. TokenSubcmd::Import { secret_key, token_blind } => {
  1997. let mint_authority = match SecretKey::from_str(&secret_key) {
  1998. Ok(ma) => ma,
  1999. Err(e) => {
  2000. eprintln!("Invalid mint authority: {e:?}");
  2001. exit(2);
  2002. }
  2003. };
  2004. let token_blind = match BaseBlind::from_str(&token_blind) {
  2005. Ok(tb) => tb,
  2006. Err(e) => {
  2007. eprintln!("Invalid token blind: {e:?}");
  2008. exit(2);
  2009. }
  2010. };
  2011. let drk = new_wallet(
  2012. blockchain_config.cache_path,
  2013. blockchain_config.wallet_path,
  2014. blockchain_config.wallet_pass,
  2015. None,
  2016. &ex,
  2017. args.fun,
  2018. )
  2019. .await;
  2020. let token_id = drk.import_mint_authority(mint_authority, token_blind).await?;
  2021. println!("Successfully imported mint authority for token ID: {token_id}");
  2022. Ok(())
  2023. }
  2024. TokenSubcmd::GenerateMint => {
  2025. let drk = new_wallet(
  2026. blockchain_config.cache_path,
  2027. blockchain_config.wallet_path,
  2028. blockchain_config.wallet_pass,
  2029. None,
  2030. &ex,
  2031. args.fun,
  2032. )
  2033. .await;
  2034. let mint_authority = SecretKey::random(&mut OsRng);
  2035. let token_blind = BaseBlind::random(&mut OsRng);
  2036. let token_id = drk.import_mint_authority(mint_authority, token_blind).await?;
  2037. println!("Successfully imported mint authority for token ID: {token_id}");
  2038. Ok(())
  2039. }
  2040. TokenSubcmd::List => {
  2041. let drk = new_wallet(
  2042. blockchain_config.cache_path,
  2043. blockchain_config.wallet_path,
  2044. blockchain_config.wallet_pass,
  2045. None,
  2046. &ex,
  2047. args.fun,
  2048. )
  2049. .await;
  2050. let tokens = drk.get_mint_authorities().await?;
  2051. let aliases_map = match drk.get_aliases_mapped_by_token().await {
  2052. Ok(map) => map,
  2053. Err(e) => {
  2054. eprintln!("Failed to fetch wallet aliases: {e:?}");
  2055. exit(2);
  2056. }
  2057. };
  2058. let mut table = Table::new();
  2059. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  2060. table.set_titles(row![
  2061. "Token ID",
  2062. "Aliases",
  2063. "Mint Authority",
  2064. "Token Blind",
  2065. "Frozen",
  2066. "Freeze Height"
  2067. ]);
  2068. for (token_id, authority, blind, frozen, freeze_height) in tokens {
  2069. let aliases = match aliases_map.get(&token_id.to_string()) {
  2070. Some(a) => a,
  2071. None => "-",
  2072. };
  2073. let freeze_height = match freeze_height {
  2074. Some(freeze_height) => freeze_height.to_string(),
  2075. None => String::from("-"),
  2076. };
  2077. table.add_row(row![token_id, aliases, authority, blind, frozen, freeze_height]);
  2078. }
  2079. if table.is_empty() {
  2080. println!("No tokens found");
  2081. } else {
  2082. println!("{table}");
  2083. }
  2084. Ok(())
  2085. }
  2086. TokenSubcmd::Mint { token, amount, recipient, spend_hook, user_data } => {
  2087. let drk = new_wallet(
  2088. blockchain_config.cache_path,
  2089. blockchain_config.wallet_path,
  2090. blockchain_config.wallet_pass,
  2091. Some(blockchain_config.endpoint),
  2092. &ex,
  2093. args.fun,
  2094. )
  2095. .await;
  2096. if let Err(e) = f64::from_str(&amount) {
  2097. eprintln!("Invalid amount: {e:?}");
  2098. exit(2);
  2099. }
  2100. let rcpt = match PublicKey::from_str(&recipient) {
  2101. Ok(r) => r,
  2102. Err(e) => {
  2103. eprintln!("Invalid recipient: {e:?}");
  2104. exit(2);
  2105. }
  2106. };
  2107. let token_id = match drk.get_token(token).await {
  2108. Ok(t) => t,
  2109. Err(e) => {
  2110. eprintln!("Invalid Token ID: {e:?}");
  2111. exit(2);
  2112. }
  2113. };
  2114. let spend_hook = match spend_hook {
  2115. Some(s) => match FuncId::from_str(&s) {
  2116. Ok(s) => Some(s),
  2117. Err(e) => {
  2118. eprintln!("Invalid spend hook: {e:?}");
  2119. exit(2);
  2120. }
  2121. },
  2122. None => None,
  2123. };
  2124. let user_data = match user_data {
  2125. Some(u) => {
  2126. let bytes: [u8; 32] = match bs58::decode(&u).into_vec()?.try_into() {
  2127. Ok(b) => b,
  2128. Err(e) => {
  2129. eprintln!("Invalid user data: {e:?}");
  2130. exit(2);
  2131. }
  2132. };
  2133. match pallas::Base::from_repr(bytes).into() {
  2134. Some(v) => Some(v),
  2135. None => {
  2136. eprintln!("Invalid user data");
  2137. exit(2);
  2138. }
  2139. }
  2140. }
  2141. None => None,
  2142. };
  2143. let tx = match drk.mint_token(&amount, rcpt, token_id, spend_hook, user_data).await
  2144. {
  2145. Ok(tx) => tx,
  2146. Err(e) => {
  2147. eprintln!("Failed to create token mint transaction: {e:?}");
  2148. exit(2);
  2149. }
  2150. };
  2151. println!("{}", base64::encode(&serialize_async(&tx).await));
  2152. drk.stop_rpc_client().await
  2153. }
  2154. TokenSubcmd::Freeze { token } => {
  2155. let drk = new_wallet(
  2156. blockchain_config.cache_path,
  2157. blockchain_config.wallet_path,
  2158. blockchain_config.wallet_pass,
  2159. Some(blockchain_config.endpoint),
  2160. &ex,
  2161. args.fun,
  2162. )
  2163. .await;
  2164. let token_id = match drk.get_token(token).await {
  2165. Ok(t) => t,
  2166. Err(e) => {
  2167. eprintln!("Invalid Token ID: {e:?}");
  2168. exit(2);
  2169. }
  2170. };
  2171. let tx = match drk.freeze_token(token_id).await {
  2172. Ok(tx) => tx,
  2173. Err(e) => {
  2174. eprintln!("Failed to create token freeze transaction: {e:?}");
  2175. exit(2);
  2176. }
  2177. };
  2178. println!("{}", base64::encode(&serialize_async(&tx).await));
  2179. drk.stop_rpc_client().await
  2180. }
  2181. },
  2182. Subcmd::Contract { command } => match command {
  2183. ContractSubcmd::GenerateDeploy => {
  2184. let drk = new_wallet(
  2185. blockchain_config.cache_path,
  2186. blockchain_config.wallet_path,
  2187. blockchain_config.wallet_pass,
  2188. None,
  2189. &ex,
  2190. args.fun,
  2191. )
  2192. .await;
  2193. if let Err(e) = drk.deploy_auth_keygen().await {
  2194. eprintln!("Error creating deploy auth keypair: {e}");
  2195. exit(2);
  2196. }
  2197. Ok(())
  2198. }
  2199. ContractSubcmd::List => {
  2200. let drk = new_wallet(
  2201. blockchain_config.cache_path,
  2202. blockchain_config.wallet_path,
  2203. blockchain_config.wallet_pass,
  2204. None,
  2205. &ex,
  2206. args.fun,
  2207. )
  2208. .await;
  2209. let auths = drk.list_deploy_auth().await?;
  2210. let mut table = Table::new();
  2211. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  2212. table.set_titles(row!["Index", "Contract ID", "Frozen", "Freeze Height"]);
  2213. for (idx, contract_id, frozen, freeze_height) in auths {
  2214. let freeze_height = match freeze_height {
  2215. Some(freeze_height) => freeze_height.to_string(),
  2216. None => String::from("-"),
  2217. };
  2218. table.add_row(row![idx, contract_id, frozen, freeze_height]);
  2219. }
  2220. if table.is_empty() {
  2221. println!("No deploy authorities found");
  2222. } else {
  2223. println!("{table}");
  2224. }
  2225. Ok(())
  2226. }
  2227. ContractSubcmd::Deploy { deploy_auth, wasm_path, deploy_ix } => {
  2228. // Read the wasm bincode and deploy instruction
  2229. let wasm_bin = smol::fs::read(expand_path(&wasm_path)?).await?;
  2230. let deploy_ix = smol::fs::read(expand_path(&deploy_ix)?).await?;
  2231. let drk = new_wallet(
  2232. blockchain_config.cache_path,
  2233. blockchain_config.wallet_path,
  2234. blockchain_config.wallet_pass,
  2235. Some(blockchain_config.endpoint),
  2236. &ex,
  2237. args.fun,
  2238. )
  2239. .await;
  2240. let mut tx = match drk.deploy_contract(deploy_auth, wasm_bin, deploy_ix).await {
  2241. Ok(v) => v,
  2242. Err(e) => {
  2243. eprintln!("Error creating contract deployment tx: {e}");
  2244. exit(2);
  2245. }
  2246. };
  2247. if let Err(e) = drk.attach_fee(&mut tx).await {
  2248. eprintln!("Failed to attach the fee call to the transaction: {e:?}");
  2249. exit(2);
  2250. };
  2251. println!("{}", base64::encode(&serialize_async(&tx).await));
  2252. drk.stop_rpc_client().await
  2253. }
  2254. ContractSubcmd::Lock { deploy_auth } => {
  2255. let drk = new_wallet(
  2256. blockchain_config.cache_path,
  2257. blockchain_config.wallet_path,
  2258. blockchain_config.wallet_pass,
  2259. Some(blockchain_config.endpoint),
  2260. &ex,
  2261. args.fun,
  2262. )
  2263. .await;
  2264. let mut tx = match drk.lock_contract(deploy_auth).await {
  2265. Ok(v) => v,
  2266. Err(e) => {
  2267. eprintln!("Error creating contract lock tx: {e}");
  2268. exit(2);
  2269. }
  2270. };
  2271. if let Err(e) = drk.attach_fee(&mut tx).await {
  2272. eprintln!("Failed to attach the fee call to the transaction: {e:?}");
  2273. exit(2);
  2274. };
  2275. println!("{}", base64::encode(&serialize_async(&tx).await));
  2276. drk.stop_rpc_client().await
  2277. }
  2278. },
  2279. }
  2280. }