main.rs 87 KB

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