main.rs 84 KB

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